repoName
stringlengths
7
77
tree
stringlengths
0
2.85M
readme
stringlengths
0
4.9M
NEAR-Edu_portal
.eslintrc.js README.md components header.module.css helpers airtable.ts countries.ts email.ts migrateFromAirtable.ts near.ts nextAuthEmailProvider.ts paths.ts profile.ts registrations.ts session.ts statusCodes.ts string.ts time.ts timeZones.ts types.ts user.ts next-auth.d.ts next-env.d.ts package-lock.json package.json pages api auth [...nextauth].ts enroll.ts migrate.ts send-scheduled-emails.ts update-profile.ts prettier.config.js prisma migrations 20220506194202_install_nextauth migration.sql 20220510184422_add_fields_to_user migration.sql 20220512165445_add_model_registration migration.sql 20220512194830_adding_time_zone_field_to_user migration.sql 20220526192003_add_why_join_field migration.sql 20220526193014_add_more_user_fields migration.sql 20220526193624_lead_source migration.sql 20220526201001_referrer migration.sql 20220526204115_referrer_mainnet_account migration.sql 20220527172644_split_technical_strengths_into_frameworks_and_platforms_and_programming_languages migration.sql 20220614155723_scheduled_emails migration.sql 20220614175815_add_schedule_id_to_scheduled_email migration.sql 20220615190624_add_registration_id_to_scheduled_email migration.sql migration_lock.toml process.d.ts public img calendar-icon.svg clock-icon.svg line-arrow-right.svg logos icon_nm.svg triangularSphere.svg tsconfig.json
# Overview This project is a work in progress. The aim has been for this portal to replace this Airtable form: https://airtable.com/shrr8CbYRDHflkgI9 which saves to https://airtable.com/appncY8IjPHkOVapz/tblFBQY4popYmxfkh/viwgxFeJIGB50pkvj?blocks=hide ## Why? - to improve student experience - to clean up our data (normalize / deduplicate it rather than) having student profiles and program registrations merged together - to enable better tracking across a student's whole journey (once we link our new database to other systems) - to extricate ourselves from that Airtable table, which already has >20k rows and will max out at 50k. ## What further work is required - finish v1 development of the 3 main pages (logged-out index page, profile creation page, program enrollment page), making them responsive, and improving the emails - set up cron jobs for scheduled emails (see pages/api/send-scheduled-emails.ts and https://www.easycron.com/user or https://render.com/docs/cronjobs) - search this repo for all mentions of TODO and ONEDAY - migrate old data from Airtable to our database (including any cleanups / interpretations) - set up an Airtable-like interface to our DB, such as nocodb https://docs.google.com/spreadsheets/d/1sYDx-ifbQ3_YMAoA8Vx3fjRmTS3iXrkDuF1CAjU5ZMA/edit#gid=0 - create a way (via granular permissions) for certain partners (such as Chad O) to add/edit data (such as when reviewing submissions) - finish tasks/issues at https://github.com/NEAR-Edu/portal/issues - write automated tests - replace the existing Airtable form with a redirect to this new form ## Deployment There are 2 branches: `develop` and `main`. Commits pushed to `main` automatically get deployed to Render.com, which is a serverless environment. Our domain name is: https://my.near.university/ # Setup ``` cp .env.local.example .env.local npm install ``` Run these commands now and after any edits to `prisma/schema.prisma`: `npm run prismaDev` and `./node_modules/.bin/prisma generate`. # Start the application To run your site locally, use: ``` npm run dev ``` To run it in production mode, use: ``` npm run build npm run start ``` # Background info This project uses [next-auth.js.org](https://next-auth.js.org).
openwebbuild_near-contract-registry
README.md |
# NEAR Contract Registry ## Why Contract Registry? 1. **Improve contract metadata discoverability.** It's frequently asked by developers about where to find the mainnet/testnet contract accounts, DApp URLs and source code of the smart contracts on NEAR. To make the contract metadata more discoverable, we created this contract registry to make it easy to find all the necessary information about the contracts of the core projects on NEAR. 2. **Improve user security.** The contract registry can be leveraged by security infrastructure in the ecosystem such as wallet to verify the contract and dapps when user access them. For example, if the user is connecting the contract from a dapp URL that doesn't match with the contract address in the registry, the wallet will warn the user of potential risks. ## Contract Metadata In the table, we have listed some of the most frequently asked contracts and projects. If you think your project should be listed, please feel free to create pull requests or submit issues. The currently supported metadata includes 1. project name 2. contract source on GitHub 3. contract account on mainnet 4. app URL for mainnet 5. contract account on testnet 6. app URL for testnet The testnet contracts and app URLs are usually helpful when developers are building their new contracts / DApps. For CSV version of the table, check out [here](/near-contract-registry.csv) | Project | Contract Source | Mainnet Contract | Mainnet App | Testnet Contract | Testnet App | -------- | -------- | -------- | -------- | -------- | -------- | | [Aurora](https://awesomenear.com/aurora-dev) | [aurora-is-near/aurora-engine](https://github.com/aurora-is-near/aurora-engine) | [aurora](https://explorer.near.org/accounts/aurora) | https://aurora.dev/start | [aurora](https://explorer.testnet.near.org/accounts/aurora) | https://aurora.dev/start | | [Rainbow Bridge](https://awesomenear.com/rainbow-bridge) | [aurora-is-near/rainbow-bridge](https://github.com/aurora-is-near/rainbow-bridge) | [aurora](https://explorer.near.org/accounts/aurora) | https://rainbowbridge.app | [aurora](https://explorer.testnet.near.org/accounts/aurora) | https://testnet.rainbowbridge.app | | [Ref Finance](https://awesomenear.com/ref-finance) | [ref-finance/ref-contracts](https://github.com/ref-finance/ref-contracts) | [v2.ref-finance.near](https://explorer.near.org/accounts/v2.ref-finance.near) | https://app.ref.finance | [exchange.ref-dev.testnet](https://explorer.testnet.near.org/accounts/exchange.ref-dev.testnet) | https://testnet.ref.finance | | [Paras](https://awesomenear.com/paras) | [ParasHQ/paras-marketplace-contract](https://github.com/ParasHQ/paras-marketplace-contract) | [marketplace.paras.near](https://explorer.near.org/accounts/marketplace.paras.near) | https://paras.id | [paras-marketplace-v2.testnet](https://explorer.testnet.near.org/accounts/paras-marketplace-v2.testnet) | https://testnet.paras.id | | [Mintbase](https://awesomenear.com/mintbase) | [Mintbase/mintbase-core](https://github.com/Mintbase/mintbase-core) | [mintbase1.near](https://explorer.near.org/accounts/mintbase1.near) | https://mintbase.io | [mintspace2.testnet](https://explorer.testnet.near.org/accounts/mintspace2.testnet) | https://testnet.mintbase.io | | [AstroDAO](https://awesomenear.com/astrodao) | [near-daos/sputnik-dao-contract](https://github.com/near-daos/sputnik-dao-contract) | [sputnik-dao.near](https://explorer.near.org/accounts/sputnik-dao.near) | https://app.astrodao.com | [sputnikv2.testnet](https://explorer.testnet.near.org/accounts/sputnikv2.testnet) | https://testnet.app.astrodao.com | | [Skyward](https://awesomenear.com/skyward-finance) | [skyward-finance/contracts](https://github.com/skyward-finance/contracts) | [skyward.near](https://explorer.near.org/accounts/skyward.near) | https://app.skyward.finance | [skyward.testnet](https://explorer.testnet.near.org/accounts/skyward.testnet) | https://test.skyward.finance | | [Meta Pool](https://awesomenear.com/meta-pool) | [Narwallets/meta-pool](https://github.com/Narwallets/meta-pool) | [meta-pool.near](https://explorer.near.org/accounts/meta-pool.near) | https://metapool.app/dapp/mainnet/meta | [meta-v2.pool.testnet](https://explorer.testnet.near.org/accounts/meta-v2.pool.testnet) | https://metapool.app/dapp/testnet/meta | | [USN](https://awesomenear.com/decentral-bank) | [DecentralBankDAO/usn](https://github.com/DecentralBankDAO/usn) | [usn](https://explorer.near.org/accounts/usn) | https://decentral-bank.finance | [usdn.testnet](https://explorer.testnet.near.org/accounts/usdn.testnet) | https://decentral-bank.finance | ## How do you collect the metadata? We refer to [AwesomeNEAR](https://awesomenear.com/) for searching the basic descriptions of the projects. However, most contract metadata are not listed there. We found the open source repository location, dapp URLs, and contract accounts based on own knowledge about the projects if not found on AwesomeNEAR, and verified the contract IDs by interacting the apps with our NEAR accounts, and confirmed in NEAR Explorer. If you have any metadata that is incorrect, please report via issues or pull requests. ## What's Next This repo is only the initial version of the contract registry, and we'll add more enhancements later. - [ ] Add more contract metadata such as owners (single account or DAO), security auditors, etc. - [ ] For dapps that used multiple contracts, list all the contracts' metadata. Now we only include the core contracts for the dapps. - [ ] Create mainnet / testnet contract registry for storing the contract metadata that could be updated by the project DAOs or owners. - [ ] Turn the contract registry to be maintained by a developer DAO from NEAR developer community. - [ ] Follow [NEP-330](https://github.com/near/NEPs/blob/master/neps/nep-0330.md) for reading and managing the contract metadata. ## How to Contribute If you have any suggestions of improving the contract registry, or if you'd like to add your own projects, please feel free to create pull requests or submit issues.
itsdivgithub_ZDeFiSwap-Near
README.md zswap-contracts-main Cargo.toml README.md build.sh deploy.sh factory Cargo.toml src dev.rs error.rs ft_storage.rs lib.rs pool.rs integration-tests Cargo.toml tests burn.rs helper.rs mint.rs swap.rs library Cargo.toml src bit_math.rs fixed_point_128.rs fixed_point_96.rs full_math.rs lib.rs liquidity_math.rs num160.rs num24.rs num256.rs num512.rs num56.rs pool_account.rs position.rs sqrt_price_math.rs swap_math.rs tick.rs tick_bitmap.rs tick_math.rs utils.rs manager Cargo.toml deploy.sh src callback.rs error.rs factory.rs ft_receiver.rs ft_storage.rs internal.rs lib.rs nft.rs pool.rs utils.rs package.json pool Cargo.toml src callback.rs core_trait.rs error.rs ft_receiver.rs internal.rs lib.rs manager.rs utils.rs rust-toolchain.toml scripts update.sh update3.sh zswap-frontend-bos-main README.md package.json src ZSwap.metadata.json ZSwap Element Button.metadata.json CustomSelect.metadata.json Input.metadata.json TitleAndDescription.metadata.json Tooltip.metadata.json Layout Navigation.metadata.json Page NFTs NFTs.metadata.json Pools Pools.metadata.json Swap MainSwap.metadata.json Tokens Tokens.json
# ZSwap ## Step 0: Create a new account 0. Install near-cli ```sh $ npm install --global near-cli ``` 1. Create a new account on [MyNearWallet testnet](https://testnet.mynearwallet.com/) 2. Authorize NEAR CLI, following the commands it gives you: ```sh # login to zswap.testnet account $ near login --walletUrl https://testnet.mynearwallet.com ``` 3. Create a subaccount (optional): ```sh # create `sub.zswap.testnet` for `zswap.testnet` with 20 NEAR $ near create-account sub.zswap.testnet --masterAccount zswap.testnet --initialBalance 20 ``` ## Step 1: Mint tokens 1. Mint `ZNEAR` ```sh # mint 100000 ZNEAR for zswap.testnet $ near call znear.zswap.testnet mint '{"receiver_id":"zswap.testnet", "amount": "100000"}' --deposit 1 --accountId zswap.testnet ``` 2. Mint `ZUSD` ```sh # mint 20000 ZUSD for zswap.testnet $ near call zusd.zswap.testnet mint '{"receiver_id":"zswap.testnet", "amount": "200000"}' --deposit 1 --accountId zswap.testnet ``` ## Step 2: Create Pool with Factory If testing with `ZNEAR` and `ZUSD`, you can skip this step. 1. Create a new pool for ZNEAR - ZUSD. Factory only supports creating a new pool with 2 fee levels: 0.05% and 0.3%. ```sh $ ZSWAP_FACTORY=factory3.zswap.testnet $ ZSWAP_MANAGER=manager3.zswap.testnet # 1 ZNEAR = 100 ZUSD, tick ~ 46054 $ SQRT_PRICE_X96="792281625142643375935439503360" $ near call $ZSWAP_MANAGER create_pool \ '{"token_0":"znear.zswap.testnet","token_1":"zusd.zswap.testnet","fee":3000,"sqrt_price_x96":"'$SQRT_PRICE_X96'"}' \ --accountId zswap.testnet --gas 300000000000000 --deposit 25 # return pool address '2e4e39194a383739.factory3.zswap.testnet' $ ZSWAP_POOL="2e4e39194a383739.factory3.zswap.testnet" ``` - View pool state ```sh $ near view $ZSWAP_FACTORY get_pool '{"token_0":"zusd.zswap.testnet", "token_1":"znear.zswap.testnet","fee":3000}' { pool_id: '2e4e39194a383739.factory3.zswap.testnet', token_0: 'znear.zswap.testnet', token_1: 'zusd.zswap.testnet', fee: 3000, tick_spacing: 60 } # view current price $ near view $ZSWAP_POOL get_slot_0 '{}' { sqrt_price_x96: '792281625142643375935439503360', tick: 46054 } ``` 2 (**Optional**). Initialize `sqrt_price` (token0 / token1), calling when current_price is ZERO. ```sh # 1 ZNEAR = 100 ZUSD, tick ~ 46054 $ near call $ZSWAP_POOL initialize '{"sqrt_price_x96":"792281625142643375935439503360"}' --accountId zswap.testnet # view current price $ near view $ZSWAP_POOL get_slot_0 '{}' { sqrt_price_x96: '792281625142643375935439503360', tick: 46054 } ``` 3. Get list of existed tokens in ZSwap Manager ```sh $ near view $ZSWAP_MANAGER get_fungible_tokens [ "znear.zswap.test", "zusd.zswap.testnet" ] ``` ## Step 3: Mint Liquidity 1. Deposit ZNEAR into `ZswapPool` ```sh $ ZNEAR_AMOUNT=10000000 $ MSG='{\"approve\":{\"account_id\":\"'$ZSWAP_MANAGER'\"}}' $ near call $ZNEAR ft_transfer_call '{"receiver_id":"'$ZSWAP_POOL'", "amount":"'$ZNEAR_AMOUNT'", "msg":"'$MSG'"}' --depositYocto 1 --gas 300000000000000 --accountId zswap.testnet ``` 2. Deposit ZUSD into `ZswapPool` ```sh $ ZUSD_AMOUNT=100000000 $ MSG='{\"approve\":{\"account_id\":\"'$ZSWAP_MANAGER'\"}}' $ near call $ZUSD ft_transfer_call '{"receiver_id":"'$ZSWAP_POOL'", "amount":"'$ZUSD_AMOUNT'", "msg":"'$MSG'"}' --depositYocto 1 --gas 300000000000000 --accountId zswap.testnet ``` 3. Mint liquidity - JSON schema example: ```json { "params": { "token_0": "znear.zswap.testnet", "token_1": "zusd.zswap.testnet", "fee": 3000, "lower_tick": 42000, "upper_tick": 48000, "amount_0_desired": "10000000", "amount_1_desired": "100000000", "amount_0_min": "1", "amount_1_min": "100" } } ``` - View the corresponding amount with the other. ```sh $ SQRT_PRICE=792281625142643375935439503360 $ near view $ZSWAP_MANAGER calculate_amount_1_with_amount_0 '{"amount_0":"'$ZNEAR_AMOUNT'","sqrt_price_x96":"'$SQRT_PRICE'","lower_tick":42000,"upper_tick":48000}' '1978918829' # returns amount_1 $ near view $ZSWAP_MANAGER calculate_amount_0_with_amount_1 '{"amount_1":"'$ZUSD_AMOUNT'","sqrt_price_x96":"'$SQRT_PRICE'","lower_tick":42000,"upper_tick":48000}' '505327' # returns amount_0 ``` ```sh $ near call $ZSWAP_MANAGER mint '{"params":{"token_0":"'$ZNEAR'","token_1":"'$ZUSD'","fee":3000,"lower_tick":42000,"upper_tick":48000, "amount_0_desired":"'$ZNEAR_AMOUNT'","amount_1_desired":"'$ZUSD_AMOUNT'","amount_0_min":"100","amount_1_min":"100"}}' --gas 300000000000000 --accountId zswap.testnet --deposit 0.1 # Return amount_0 & amount_1 [ '505327', '100000000' ] ``` - After minting liquidity, you will get an NFT ## Step 4: Swap This example will swap `ZNEAR` to `ZUSD`. If you need `ZNEAR` to test, following command: ```sh $ TRADER=testz.testnet $ near call $ZNEAR mint '{"receiver_id":"'$TRADER'", "amount": "100000"}' --deposit 1 --accountId $TRADER ``` 1. Ensure register storage for trader account in FT contracts. ```sh near call $ZUSD storage_deposit '{"account_id":"'$TRADER'"}' --deposit 1 --accountId $TRADER ``` 2. Swap `ZNEAR` to `ZUSD` ```sh $ ZNEAR_AMOUNT=100 $ SWAP_MSG='{\"swap_single\":{\"token_out\":\"'$ZUSD'\",\"fee\":3000}}' $ near call $ZNEAR ft_transfer_call '{"receiver_id":"'$ZSWAP_MANAGER'", "amount":"'$ZNEAR_AMOUNT'", "msg":"'$SWAP_MSG'"}' --gas 300000000000000 --accountId $TRADER --depositYocto 1 ``` ## Step 5: Burn ```sh # View current NFTs $ near view $ZSWAP_MANAGER nft_tokens_for_owner '{"account_id":"zswap.testnet"}' $ near call $ZSWAP_MANAGER burn '{"nft_id":"0"}' --gas 300000000000000 --accountId zswap.testnet [ '505326', '99999999' ] ``` # ENCODE X NEAR HORIZON 2023 ## DEPLOYMENT NEAR ORG- test.near.org Introduction: ZSwap is a decentralized exchange (DEX) that has tackled two significant challenges in the DeFi space: concentrated liquidity and centralized frontends. By enabling liquidity providers to focus on specific price ranges and integrating BOS on NEAR, ZSwap has achieved a fully decentralized and efficient liquidity DEX. However, this journey hasn't been without its challenges, particularly in terms of BOS integration and navigating the intricacies of cross-contract calling on NEAR. Scaling with Near Protocol: Scaling ZSwap with Near Protocol is a strategic move aimed at addressing the challenges and seizing new opportunities for growth. Here are our plans for scaling the project: Leveraging Near's Infrastructure: Near Protocol offers a highly scalable and efficient blockchain infrastructure that can handle a large number of transactions with low latency. ZSwap intends to harness Near's capabilities to enhance the speed and scalability of the platform, ensuring that users can execute trades quickly and without delays. Expanding Liquidity Pools: Near Protocol's smart contract capabilities make it easier to manage and expand liquidity pools. ZSwap plans to introduce more liquidity pairs and incentivize liquidity providers through rewards, attracting a broader range of assets and liquidity to the platform. Ecosystem Integration: Near Protocol has a growing ecosystem of DeFi projects and developers. ZSwap will actively engage with this ecosystem to foster collaborations, cross-integrations, and shared liquidity, creating a more interconnected DeFi environment on Near. User-Friendly Interface: ZSwap's commitment to decentralization includes providing a user-friendly interface that is easily accessible to both experienced DeFi users and newcomers. The Near ecosystem supports the development of user-friendly dApps, and ZSwap plans to take advantage of this to improve the user experience. Security and Trustless Operations: Near Protocol's focus on security and trustless operations aligns well with ZSwap's objectives. As the platform grows, ZSwap will continue to prioritize security by conducting regular audits and enhancing smart contract security. Bridging to Other Networks: Near Protocol's bridge capabilities enable interoperability with other blockchain networks. ZSwap intends to explore the possibilities of bridging assets to and from Near, expanding its reach and liquidity sources. Conclusion: Scaling with Near Protocol presents an exciting opportunity for ZSwap to address liquidity challenges, enhance user experiences, and tap into a growing DeFi ecosystem. While there have been hurdles along the way, the unique features and potential of Near Protocol offer a promising future for ZSwap as a fully decentralized and efficient liquidity DEX. As we move forward, we remain committed to overcoming challenges and providing innovative solutions to our users within the Near ecosystem. # ZSwap BOS Frontend Components [ZSwap Protocol](https://ZSwapprotocol.org/) is a liquid staking solution built on the NEAR Protocol. ZSwap unlocks liquidity of the staked NEAR by creating a staking derivative to be engaged with various DeFi protocols on NEAR and Aurora, while also enjoying over 10% APY staking rewards of the underlying base tokens. ZSwap is the cornerstone piece of the NEAR-Aurora DeFi ecosystem. This repository holds [ZSwap BOS components](https://near.org/ZSwapprotocol.near/widget/ZSwap) hosted on NEAR BOS (Blockchain Operating System), to interact with [ZSwap smart contract](https://github.com/ZSwap-protocol/ZSwap). ## Setup Local Environment We use [BOS Loader](https://docs.near.org/bos/dev/bos-loader) to enable instant preview in local environment, so you don't have to deploy all your components to mainnet to preview and test your changes. 1. [Download and install BOS Loader](https://github.com/near/bos-loader/releases) - Linux / Mac: Install prebuilt binaries via shell script ```bash curl --proto '=https' --tlsv1.2 -LsSf https://github.com/mpeterdev/bos-loader/releases/download/v0.6.0/bos-loader-v0.6.0-installer.sh | sh ``` 2. Open https://test.near.org/flags, and set the loader URL to ```bash http://127.0.0.1:3030 ``` 3. Clone repository: ```bash git clone git@github.com:DV-Lab/zswap-frontend-bos.git ``` 4. Install and run ```bash yarn install ``` ```bash yarn dev ``` 5. Launch testnet [preview page](https://test.near.org/zswap.testnet/widget/ZSwap) 6. Modify ZSwap components code, and refresh preview page to view the latest change. Please notice that because **hot reload** is not ready in BOS loader, you need to refresh the preview page in browser after code change. 7. [`prettier`](https://prettier.io/) is configured in Git pre-commit hook with [husky](https://github.com/typicode/husky) and [lint-staged](https://github.com/okonet/lint-staged) to automatically format the modified components code. ## Folder Structure The source code of ZSwap components are available in the `src` folder, and organized by sub-folders. For example, the `ZSwapprotocol.near/widget/ZSwap.Element.Button` component is available in `src/ZSwap/Element/Button.jsx`. BOS Loader and BOS CLI both use `.` delimiter when converting local file path to component name, and vice versa. ## Continuous Integration & Delivery We use [BOS CLI](https://github.com/FroVolod/bos-cli-rs) and its [GitHub actions](https://github.com/FroVolod/bos-cli-rs/tree/master/.github/workflows) for continuous integration and delivery. 1. We have set up one [testnet GitHub action](https://github.com/DV-Lab/zswap-frontend-bos/blob/main/.github/workflows/testnet-preview.yml) to deploy latest commit in pull request to testnet for preview and testing once the PR is submitted. (However, since now we have only configured on `TESTNET_DEPLOY_ACCOUNT`, if you have multiple open PRs, they may conflict with each other. This will be fixed later.) 2. We have another [mainnet GitHub action](https://github.com/DV-Lab/zswap-frontend-bos/blob/main/.github/workflows/mainnet-release.yml) to deploy the latest `main branch` components code to mainnet. To make the CI workflow work, we need to create function call keys for testnet and mainnet deployment, following the instructions in [BOS CLI](https://github.com/FroVolod/bos-cli-rs), and set up below GitHub actions [variables and secrets](https://docs.github.com/en/actions/learn-github-actions/variables#creating-configuration-variables-for-a-repository). - `TESTNET_DEPLOY_ACCOUNT` / `TESTNET_SIGNER_PUBLIC_KEY` / `TESTNET_SIGNER_PRIVATE_KEY` - `MAINNET_DEPLOY_ACCOUNT` / `MAINNET_SIGNER_PUBLIC_KEY` / `MAINNET_SIGNER_PRIVATE_KEY` ## Testing 1. We recommend testing locally with BOS Loader first, before submit pull request for code review and testnet testing. 2. Once a PR is submitted, it will be automatically deployed to testnet, which makes it easy for others to test and provide feedback. 3. Only after a PR is well tested and reviewed, it will be merged and the latest `main branch` commit will be deployed to mainnet. ## License MIT License
guille-near_mintickt
.env README.md babel.config.js changelog.md package.json public index.html themes dark theme.css light theme.css webflow.js src Routes.js assets backgrounds border-gradient-btn-small.svg border-gradient-menu-small.svg border.svg fonts sf-pro-font demo.html stylesheet.css icons arrow-circle-left.svg arrow-circle-right.svg building.svg calendar.svg check-rose.svg copy.svg drag-img.svg link.svg log-out.svg lupa.svg marker-nearcon.svg marker.svg mdi-arrow-left.svg mdi-arrow-right.svg minus.svg plus.svg qr.svg scan.svg ticket.svg transaction.svg wallet.svg img DuneTicket.svg bg-ticket_events.svg ticket-events.svg ticket.svg ticket_flee.svg landing Logo-Mark-White.svg Logo_mintickt.svg Mintbase_logo.svg Professions-Man-Artist.svg Question.svg Social-media-logo.svg Ticket.svg Workflow-Teammate-Circle.svg astro.svg avatar.svg logo_mintick.svg near_logo_wht.svg rock.svg settings.svg logo Marker.svg logo-mobile.svg logo.svg logom.svg logonear.svg mintickt_beta.svg mintickt_beta_mobile.svg near-black.svg near.svg newLanding Logo.svg check.svg discord.svg facebook.svg faq-content-mobile.svg faq-content.svg faq-header-mobile.svg faq-header.svg instagram.svg linkedin.svg medium.svg memorable-bg.svg telegram.svg twitter.svg x-close.svg pass general-admision.svg profile burn.svg discord.svg ticket-test.svg transfer.svg user.svg ticket-selection ticket-cinema-upload.svg ticket-cinema.svg ticket-con-upload.svg ticket-con.svg ticket-custom-upload.svg ticket-event.svg components Layout i18n.js config.js main.js pages Landing webflow.css plugins i18n.js vuetify.js services api.js near-api.js ramper-api.js wallet.ts store index.js tsconfig.json vue.config.js
# Mintickt Front end for Mintickt
near-examples_NFT-Examples
NFT-example .github dependabot.yml scripts readme-quick-deploy.sh workflows readme-ci.yml tests.yml .gitpod.yml Cargo.toml README-Windows.md README.md integration-tests rs Cargo.toml src tests.rs ts package.json src main.ava.ts utils.ts nft Cargo.toml src lib.rs res README.md scripts build.bat build.sh flags.sh test-approval-receiver Cargo.toml src lib.rs test-token-receiver Cargo.toml src lib.rs README.md nft-tutorial-js .github workflows tests.yml README.md __tests__ test-template.ava.js babel.config.json commands.txt jsconfig.json neardev dev-account.env package.json src market-contract index.ts internal.ts nft_callbacks.ts sale.ts sale_views.ts nft-contract approval.ts enumeration.ts index.ts internal.ts metadata.ts mint.ts nft_core.ts royalty.ts tsconfig.json | | nft-tutorial .github workflows tests.yml README.md integration-tests rs Cargo.toml src helpers.rs tests.rs ts package.json src main.ava.ts utils.ts market-contract Cargo.toml README.md build.sh src external.rs internal.rs lib.rs nft_callbacks.rs sale.rs sale_views.rs tests.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 tests.rs nft-series Cargo.toml README.md build.sh src approval.rs enumeration.rs events.rs internal.rs lib.rs metadata.rs nft_core.rs owner.rs royalty.rs series.rs package.json
# TBD # TBD Non-fungible Token (NFT) =================== >**Note**: If you'd like to learn how to create an NFT contract from scratch that explores every aspect of the [NEP-171](https://github.com/near/NEPs/blob/master/neps/nep-0171.md) standard including an NFT marketplace, check out the NFT [Zero to Hero Tutorial](https://docs.near.org/tutorials/nfts/introduction). [![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 workspaces-js and -rs 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 ./scripts/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. *Unit Tests* ```bash cd nft cargo test -- --nocapture ``` *Integration Tests* *Rust* ```bash cd integration-tests/rs cargo run --example integration-tests ``` *TypeScript* ```bash cd integration-tests/ts yarn && yarn test ``` Using this contract =================== ### Quickest deploy You can build and deploy this smart contract to a development account. [Dev Accounts](https://docs.near.org/concepts/basics/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. # NFT Examples This repository contains an example of an NFT smart contract in Rust and tutorials on how to create them for both JavaScript and Rust. ## Repositories - [NFT Smart Contract in Rust](NFT-example) - [NFT Contract in Rust Tutorial](nft-tutorial) - [NFT Contract in JavaScript Tutorial](nft-tutorial-js) # Folder that contains wasm files # TBD # NEAR NFT-Tutorial [![](https://img.shields.io/github/workflow/status/near-examples/nft-tutorial/Tests/main?label=Tests)](https://github.com/near-examples/nft-tutorial/actions/workflows/tests.yml) Welcome to NEAR's NFT tutorial, where we will help you parse the details around NEAR's [NEP-171 standard](https://nomicon.io/Standards/NonFungibleToken/Core.html) (Non-Fungible Token Standard), and show you how to build your own NFT smart contract from the ground up, improving your understanding about the NFT standard along the way. ## Prerequisites * [NEAR Wallet Account](wallet.testnet.near.org) * [Rust Toolchain](https://docs.near.org/develop/prerequisites) * [NEAR-CLI](https://docs.near.org/tools/near-cli#setup) * [yarn](https://classic.yarnpkg.com/en/docs/install#mac-stable) ## Tutorial Stages Each branch you will find in this repo corresponds to various stages of this tutorial with a partially completed contract at each stage. You are welcome to start from any stage you want to learn the most about. | Branch | Docs Tutorial | Description | | ------------- | ------------------------------------------------------------------------------------------------ | ----------- | | 1.skeleton | [Contract Architecture](https://docs.near.org/docs/tutorials/contracts/nfts/rs/skeleton) | You'll learn the basic architecture of the NFT smart contract, and you'll compile this skeleton code with the Rust toolchain. | | 2.minting | [Minting](https://docs.near.org/docs/tutorials/contracts/nfts/rs/minting) |Here you'll flesh out the skeleton so the smart contract can mint a non-fungible token | | 3.enumeration | [Enumeration](https://docs.near.org/docs/tutorials/contracts/nfts/rs/enumeration) | Here you'll find different enumeration methods that can be used to return the smart contract's states. | | 4.core | [Core](https://docs.near.org/docs/tutorials/contracts/nfts/rs/core) | In this tutorial you'll extend the NFT contract using the core standard, which will allow you to transfer non-fungible tokens. | | 5.approval | [Approval](https://docs.near.org/docs/tutorials/contracts/nfts/rs/approvals) | Here you'll expand the contract allowing other accounts to transfer NFTs on your behalf. | | 6.royalty | [Royalty](https://docs.near.org/docs/tutorials/contracts/nfts/rs/royalty) |Here you'll add the ability for non-fungible tokens to have royalties. This will allow people to get a percentage of the purchase price when an NFT is purchased. | | 7.events | ----------- | This allows indexers to know what functions are being called and make it easier and more reliable to keep track of information that can be used to populate the collectibles tab in the wallet for example. (tutorial docs have yet to be implemented ) | | 8.marketplace | ----------- | ----------- | The tutorial series also contains a very helpful section on [**Upgrading Smart Contracts**](https://docs.near.org/docs/tutorials/contracts/nfts/rs/upgrade-contract). Definitely go and check it out as this is a common pain point. # Quick-Start If you want to see the full completed contract go ahead and clone and build this repo using ```=bash git clone https://github.com/near-examples/nft-tutorial.git cd nft-tutorial git switch 6.royalty yarn build ``` Now that you've cloned and built the contract we can try a few things. ## Mint An NFT Once you've created your near wallet go ahead and login to your wallet with your cli and follow the on-screen prompts ```=bash near login ``` Once your logged in you have to deploy the contract. Make a subaccount with the name of your choosing ```=bash near create-account nft-example.your-account.testnet --masterAccount your-account.testnet --initialBalance 10 ``` After you've created your sub account deploy the contract to that sub account, set this variable to your sub account name ```=bash NFT_CONTRACT_ID=nft-example.your-account.testnet MAIN_ACCOUNT=your-account.testnet ``` Verify your new variable has the correct value ```=bash echo $NFT_CONTRACT_ID echo $MAIN_ACCOUNT ``` ### Deploy Your Contract ```=bash near deploy --accountId $NFT_CONTRACT_ID --wasmFile out/main.wasm ``` ### Initialize Your Contract ```=bash near call $NFT_CONTRACT_ID new_default_meta '{"owner_id": "'$NFT_CONTRACT_ID'"}' --accountId $NFT_CONTRACT_ID ``` ### View Contracts Meta Data ```=bash near view $NFT_CONTRACT_ID nft_metadata ``` ### Minting Token ```bash= near call $NFT_CONTRACT_ID nft_mint '{"token_id": "token-1", "metadata": {"title": "My Non Fungible Team Token", "description": "The Team Most Certainly Goes :)", "media": "https://bafybeiftczwrtyr3k7a2k4vutd3amkwsmaqyhrdzlhvpt33dyjivufqusq.ipfs.dweb.link/goteam-gif.gif"}, "receiver_id": "'$MAIN_ACCOUNT'"}' --accountId $MAIN_ACCOUNT --amount 0.1 ``` After you've minted the token go to wallet.testnet.near.org to `your-account.testnet` and look in the collections tab and check out your new sample NFT! ## View NFT Information After you've minted your NFT you can make a view call to get a response containing the `token_id` `owner_id` and the `metadata` ```bash= near view $NFT_CONTRACT_ID nft_token '{"token_id": "token-1"}' ``` ## Transfering NFTs To transfer an NFT go ahead and make another [testnet wallet account](https://wallet.testnet.near.org). Then run the following ```bash= MAIN_ACCOUNT_2=your-second-wallet-account.testnet ``` Verify the correct variable names with this ```=bash echo $NFT_CONTRACT_ID echo $MAIN_ACCOUNT echo $MAIN_ACCOUNT_2 ``` To initiate the transfer.. ```bash= near call $NFT_CONTRACT_ID nft_transfer '{"receiver_id": "$MAIN_ACCOUNT_2", "token_id": "token-1", "memo": "Go Team :)"}' --accountId $MAIN_ACCOUNT --depositYocto 1 ``` In this call you are depositing 1 yoctoNEAR for security and so that the user will be redirected to the NEAR wallet. ## Errata Large Changes: * **2022-06-21**: updated the rust SDK to version 4.0.0. PR found [here](https://github.com/near-examples/nft-tutorial/pull/32) * **2022-02-12**: updated the enumeration methods `nft_tokens` and `nft_tokens_for_owner` to no longer use any `to_vector` operations to save GAS. In addition, the default limit was changed from 0 to 50. PR found [here](https://github.com/near-examples/nft-tutorial/pull/17). Small Changes: * **2022-02-22**: changed `token_id` parameter type in nft_payout from `String` to `TokenId` for consistency as per pythonicode's suggestion # NEAR NFT-Tutorial JavaScript Edition [![](https://img.shields.io/github/workflow/status/near-examples/nft-tutorial-js/Tests/master?label=Tests)](https://github.com/near-examples/nft-tutorial-js/actions/workflows/tests.yml) Welcome to NEAR's NFT tutorial, where we will help you parse the details around NEAR's [NEP-171 standard](https://nomicon.io/Standards/NonFungibleToken/Core.html) (Non-Fungible Token Standard), and show you how to build your own NFT smart contract from the ground up, improving your understanding about the NFT standard along the way. ## Prerequisites * [Node.js](/develop/prerequisites#nodejs) * [NEAR Wallet Account](wallet.testnet.near.org) * [NEAR-CLI](https://docs.near.org/tools/near-cli#setup) * [yarn](https://classic.yarnpkg.com/en/docs/install#mac-stable) ## Tutorial Stages Each branch you will find in this repo corresponds to various stages of this tutorial with a partially completed contract at each stage. You are welcome to start from any stage you want to learn the most about. | Branch | Docs Tutorial | Description | | ------------- | ------------------------------------------------------------------------------------------------ | ----------- | | 1.skeleton | [Contract Architecture](https://docs.near.org/docs/tutorials/contracts/nfts/js/skeleton) | You'll learn the basic architecture of the NFT smart contract. | | 2.minting | [Minting](https://docs.near.org/docs/tutorials/contracts/nfts/js/minting) |Here you'll flesh out the skeleton so the smart contract can mint a non-fungible token | | 3.enumeration | [Enumeration](https://docs.near.org/docs/tutorials/contracts/nfts/js/enumeration) | Here you'll find different enumeration methods that can be used to return the smart contract's states. | | 4.core | [Core](https://docs.near.org/docs/tutorials/contracts/nfts/js/core) | In this tutorial you'll extend the NFT contract using the core standard, which will allow you to transfer non-fungible tokens. | | 5.approval | [Approval](https://docs.near.org/docs/tutorials/contracts/nfts/js/approvals) | Here you'll expand the contract allowing other accounts to transfer NFTs on your behalf. | | 6.royalty | [Royalty](https://docs.near.org/docs/tutorials/contracts/nfts/js/royalty) |Here you'll add the ability for non-fungible tokens to have royalties. This will allow people to get a percentage of the purchase price when an NFT is purchased. | | 7.events | ----------- | This allows indexers to know what functions are being called and make it easier and more reliable to keep track of information that can be used to populate the collectibles tab in the wallet for example. (tutorial docs have yet to be implemented ) | | 8.marketplace | ----------- | ----------- | The tutorial series also contains a very helpful section on [**Upgrading Smart Contracts**](https://docs.near.org/docs/tutorials/contracts/nfts/js/upgrade-contract). Definitely go and check it out as this is a common pain point. # Quick-Start If you want to see the full completed contract go ahead and clone and build this repo using ```=bash git clone https://github.com/near-examples/nft-tutorial-js.git cd nft-tutorial-js yarn && yarn build ``` Now that you've cloned and built the contract we can try a few things. ## Mint An NFT Once you've created your near wallet go ahead and login to your wallet with your cli and follow the on-screen prompts ```=bash near login ``` Once your logged in you have to deploy the contract. Make a subaccount with the name of your choosing ```=bash near create-account nft-example.your-account.testnet --masterAccount your-account.testnet --initialBalance 10 ``` After you've created your sub account deploy the contract to that sub account, set this variable to your sub account name ```=bash NFT_CONTRACT_ID=nft-example.your-account.testnet MAIN_ACCOUNT=your-account.testnet ``` Verify your new variable has the correct value ```=bash echo $NFT_CONTRACT_ID echo $MAIN_ACCOUNT ``` ### Deploy Your Contract ```=bash near deploy --accountId $NFT_CONTRACT_ID --wasmFile build/nft.wasm ``` ### Initialize Your Contract ```=bash near call $NFT_CONTRACT_ID init '{"owner_id": "'$NFT_CONTRACT_ID'"}' --accountId $NFT_CONTRACT_ID ``` ### View Contracts Meta Data ```=bash near view $NFT_CONTRACT_ID nft_metadata ``` ### Minting Token ```bash= near call $NFT_CONTRACT_ID nft_mint '{"token_id": "token-1", "metadata": {"title": "My Non Fungible Team Token", "description": "The Team Most Certainly Goes :)", "media": "https://bafybeiftczwrtyr3k7a2k4vutd3amkwsmaqyhrdzlhvpt33dyjivufqusq.ipfs.dweb.link/goteam-gif.gif"}, "receiver_id": "'$MAIN_ACCOUNT'"}' --accountId $MAIN_ACCOUNT --amount 0.1 ``` After you've minted the token go to wallet.testnet.near.org to `your-account.testnet` and look in the collections tab and check out your new sample NFT! ## View NFT Information After you've minted your NFT you can make a view call to get a response containing the `token_id` `owner_id` and the `metadata` ```bash= near view $NFT_CONTRACT_ID nft_token '{"token_id": "token-1"}' ``` ## Transfering NFTs To transfer an NFT go ahead and make another [testnet wallet account](https://wallet.testnet.near.org). Then run the following ```bash= MAIN_ACCOUNT_2=your-second-wallet-account.testnet ``` Verify the correct variable names with this ```=bash echo $NFT_CONTRACT_ID echo $MAIN_ACCOUNT echo $MAIN_ACCOUNT_2 ``` To initiate the transfer.. ```bash= near call $NFT_CONTRACT_ID nft_transfer '{"receiver_id": "$MAIN_ACCOUNT_2", "token_id": "token-1", "memo": "Go Team :)"}' --accountId $MAIN_ACCOUNT --depositYocto 1 ``` In this call you are depositing 1 yoctoNEAR for security and so that the user will be redirected to the NEAR wallet.
near_boilerplate-template-keypom
.github ISSUE_TEMPLATE 01_BUG_REPORT.md 02_FEATURE_REQUEST.md 03_CODEBASE_IMPROVEMENT.md 04_SUPPORT_QUESTION.md BOUNTY.yml config.yml PULL_REQUEST_TEMPLATE.md labels.yml workflows codeql.yml deploy-to-console.yml labels.yml lint.yml lock.yml pr-labels.yml stale.yml README.md contracts check-deploy.sh dev-deploy.sh docs CODE_OF_CONDUCT.md CONTRIBUTING.md SECURITY.md frontend .env .eslintrc.json .prettierrc.json README.md constants.ts contracts contract.ts keypom-contract.ts nft-series-contract.ts types.ts keyStore.ts links.ts near-seed-phrase.types.d.ts next.config.js package-lock.json package.json postcss.config.js public next.svg thirteen.svg vercel.svg styles globals.css tailwind.config.js tsconfig.json web3storage.ts package-lock.json package.json
<h1 align="center"> <a href="https://github.com/near/boilerplate-template-keypom"> <picture> <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/near/boilerplate-template-keypom/main/docs/images/pagoda_logo_light.png"> <source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/near/boilerplate-template-keypom/main/docs/images/pagoda_logo_dark.png"> <img alt="" src="https://raw.githubusercontent.com/near/boilerplate-template-keypom/main/docs/images/pagoda_logo_dark.png"> </picture> </a> </h1> <div align="center"> Boilerplate Template React <br /> <br /> <a href="https://github.com/near/boilerplate-template-keypom/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-keypom/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-keypom/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-keypom/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> - [Getting Started](#getting-started) - [Prerequisites](#prerequisites) - [Installation](#installation) - [Usage](#usage) - [Exploring The Code](#exploring-the-code) - [Deploy](#deploy) - [Step 0: Install near-cli (optional)](#step-0-install-near-cli-optional) - [Step 1: Create an account for the contract](#step-1-create-an-account-for-the-contract) - [Step 2: deploy the contract](#step-2-deploy-the-contract) - [Troubleshooting](#troubleshooting) - [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 + IPFS 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. Optionally create an account on [web3.storage](https://web3.storage) in order to upload files directly to IPFS from the frontend. Generate an API token on web3.storage by following [this guide](https://web3.storage/docs/how-tos/generate-api-token/) and, finally, store the token in your `frontend/.env.local` as `NEXT_PUBLIC_WEB3_STORAGE_AUTH_TOKEN`. Note this means the API token will be available to anyone who has access to your website. This might not be ideal for a production application but works great for prototyping. ### Installation Install all dependencies: npm install Deploy your NFT contracts to TestNet with a temporary dev account: npm run deploy Initialize the NFT contract (customize this to your needs): near call <neardev-account> new '{"owner_id":"<YOUR_ACCOUNT>","metadata": {"spec":"nft-1.0.99","name":"<YOUR_NFT_NAME>","symbol":"<YOUR_UNIQUE_SYMBOL>","base_uri":"https://cloudflare-ipfs.com/ipfs/"}}' --accountId <YOUR_ACCOUNT> You also need to add keypom as an approved minter to mint NFTs on your behalf, add approved minters to NFT series contract: near call <neardev-account> add_approved_minter '{"account_id":"beta.keypom.testnet"}' --accountId <YOUR_ACCOUNT> By default, only the owner will be able to create NFT series on this contract. You can optionally add anyone else as an approved creator by running: near call <neardev-account> add_approved_creator '{"account_id":"<APPROVED_ACCOUNT>"}' --accountId <YOUR_ACCOUNT> Usage ===== Start your frontend in development mode: npm run dev Start your frontend in production mode: npm run start Exploring The Code ================== 1. The pre-built smart-contract code lives in the `/contracts` folder. This app is built from [Keypom's NFT tutorial series app](https://github.com/keypom/nft-tutorial-series). In blockchain apps the smart contract is the "backend" of your app. 2. The frontend code lives in the `/frontend` folder. `/frontend/pages/index.tsx` is a great place to start exploring. Note that it uses `/frontend/contracts/keypom-contract.ts`, this is your entrypoint to learn how the frontend connects to the NEAR blockchain. 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. near deploy --accountId near-blank-project.YOUR-NAME.testnet --wasmFile ./contracts/nft-series/nft-series.wasm 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-keypom/issues) for a list of proposed features (and known issues). - [Top Feature Requests](https://github.com/near/boilerplate-template-keypom/issues?q=label%3Aenhancement+is%3Aopen+sort%3Areactions-%2B1-desc) (Add your votes using the 👍 reaction) - [Top Bugs](https://github.com/near/boilerplate-template-keypom/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-keypom/issues?q=is%3Aopen+is%3Aissue+label%3Abug) ## Support Reach out to the maintainer: - [GitHub issues](https://github.com/near/boilerplate-template-keypom/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 Boilerplate Template React: - Add a [GitHub Star](https://github.com/near/boilerplate-template-keypom) to the project. - Tweet about the Boilerplate Template React. - Write interesting articles about the project on [Dev.to](https://dev.to/), [Medium](https://medium.com/) or your personal blog. Together, we can make Boilerplate Template React **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 [Jonathan Lewis](https://github.com/jon-lewis). For a full list of all authors and contributors, see [the contributors page](https://github.com/near/boilerplate-template-keypom/contributors). ## Security Boilerplate Template React follows good practices of security, but 100% security cannot be assured. Boilerplate Template React 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)._ This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) and [`tailwindcss`](https://tailwindcss.com/docs/guides/nextjs). ## Getting Started First, run the development server: ```bash npm run dev # or yarn dev ``` Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. You can start editing the page by modifying `pages/index.tsx`. The page auto-updates as you edit the file. [API routes](https://nextjs.org/docs/api-routes/introduction) can be accessed on [http://localhost:3000/api/hello](http://localhost:3000/api/hello). This endpoint can be edited in `pages/api/hello.ts`. The `pages/api` directory is mapped to `/api/*`. Files in this directory are treated as [API routes](https://nextjs.org/docs/api-routes/introduction) instead of React pages. This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font. ## Learn More To learn more about Next.js, take a look at the following resources: - [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. - [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome! ## Deploy on Vercel The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details. This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) and [`tailwindcss`](https://tailwindcss.com/docs/guides/nextjs). ## Getting Started First, run the development server: ```bash npm run dev # or yarn dev ``` Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. You can start editing the page by modifying `pages/index.tsx`. The page auto-updates as you edit the file. [API routes](https://nextjs.org/docs/api-routes/introduction) can be accessed on [http://localhost:3000/api/hello](http://localhost:3000/api/hello). This endpoint can be edited in `pages/api/hello.ts`. The `pages/api` directory is mapped to `/api/*`. Files in this directory are treated as [API routes](https://nextjs.org/docs/api-routes/introduction) instead of React pages. This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font. ## Learn More To learn more about Next.js, take a look at the following resources: - [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. - [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome! ## Deploy on Vercel The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details. <h1 align="center"> <a href="https://github.com/near/boilerplate-template-keypom"> <picture> <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/near/boilerplate-template-keypom/main/docs/images/pagoda_logo_light.png"> <source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/near/boilerplate-template-keypom/main/docs/images/pagoda_logo_dark.png"> <img alt="" src="https://raw.githubusercontent.com/near/boilerplate-template-keypom/main/docs/images/pagoda_logo_dark.png"> </picture> </a> </h1> <div align="center"> Boilerplate Template React <br /> <br /> <a href="https://github.com/near/boilerplate-template-keypom/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-keypom/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-keypom/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-keypom/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> - [Getting Started](#getting-started) - [Prerequisites](#prerequisites) - [Installation](#installation) - [Usage](#usage) - [Exploring The Code](#exploring-the-code) - [Deploy](#deploy) - [Step 0: Install near-cli (optional)](#step-0-install-near-cli-optional) - [Step 1: Create an account for the contract](#step-1-create-an-account-for-the-contract) - [Step 2: deploy the contract](#step-2-deploy-the-contract) - [Troubleshooting](#troubleshooting) - [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 + IPFS 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. Optionally create an account on [web3.storage](https://web3.storage) in order to upload files directly to IPFS from the frontend. Generate an API token on web3.storage by following [this guide](https://web3.storage/docs/how-tos/generate-api-token/) and, finally, store the token in your `frontend/.env.local` as `NEXT_PUBLIC_WEB3_STORAGE_AUTH_TOKEN`. Note this means the API token will be available to anyone who has access to your website. This might not be ideal for a production application but works great for prototyping. ### Installation Install all dependencies: npm install Deploy your NFT contracts to TestNet with a temporary dev account: npm run deploy Initialize the NFT contract (customize this to your needs): near call <neardev-account> new '{"owner_id":"<YOUR_ACCOUNT>","metadata": {"spec":"nft-1.0.99","name":"<YOUR_NFT_NAME>","symbol":"<YOUR_UNIQUE_SYMBOL>","base_uri":"https://cloudflare-ipfs.com/ipfs/"}}' --accountId <YOUR_ACCOUNT> You also need to add keypom as an approved minter to mint NFTs on your behalf, add approved minters to NFT series contract: near call <neardev-account> add_approved_minter '{"account_id":"beta.keypom.testnet"}' --accountId <YOUR_ACCOUNT> By default, only the owner will be able to create NFT series on this contract. You can optionally add anyone else as an approved creator by running: near call <neardev-account> add_approved_creator '{"account_id":"<APPROVED_ACCOUNT>"}' --accountId <YOUR_ACCOUNT> Usage ===== Start your frontend in development mode: npm run dev Start your frontend in production mode: npm run start Exploring The Code ================== 1. The pre-built smart-contract code lives in the `/contracts` folder. This app is built from [Keypom's NFT tutorial series app](https://github.com/keypom/nft-tutorial-series). In blockchain apps the smart contract is the "backend" of your app. 2. The frontend code lives in the `/frontend` folder. `/frontend/pages/index.tsx` is a great place to start exploring. Note that it uses `/frontend/contracts/keypom-contract.ts`, this is your entrypoint to learn how the frontend connects to the NEAR blockchain. 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. near deploy --accountId near-blank-project.YOUR-NAME.testnet --wasmFile ./contracts/nft-series/nft-series.wasm 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-keypom/issues) for a list of proposed features (and known issues). - [Top Feature Requests](https://github.com/near/boilerplate-template-keypom/issues?q=label%3Aenhancement+is%3Aopen+sort%3Areactions-%2B1-desc) (Add your votes using the 👍 reaction) - [Top Bugs](https://github.com/near/boilerplate-template-keypom/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-keypom/issues?q=is%3Aopen+is%3Aissue+label%3Abug) ## Support Reach out to the maintainer: - [GitHub issues](https://github.com/near/boilerplate-template-keypom/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 Boilerplate Template React: - Add a [GitHub Star](https://github.com/near/boilerplate-template-keypom) to the project. - Tweet about the Boilerplate Template React. - Write interesting articles about the project on [Dev.to](https://dev.to/), [Medium](https://medium.com/) or your personal blog. Together, we can make Boilerplate Template React **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 [Jonathan Lewis](https://github.com/jon-lewis). For a full list of all authors and contributors, see [the contributors page](https://github.com/near/boilerplate-template-keypom/contributors). ## Security Boilerplate Template React follows good practices of security, but 100% security cannot be assured. Boilerplate Template React 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)._
mrtlive_NCD-Bookshop-Example
README.md asconfig.json assembly as_typed.d.ts index.ts model.ts tsconfig.json index.html neardev dev-account.env node_modules .bin sha.js @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 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 binaryen README.md index.d.ts package-lock.json package.json wasm.d.ts 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 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 @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 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-node-hid-noevents README.md lib-es TransportNodeHid.d.ts TransportNodeHid.js lib TransportNodeHid.d.ts TransportNodeHid.js node_modules @ledgerhq devices README.md 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.js tsconfig.json errors README.md lib-es helpers.d.ts helpers.js index.d.ts index.js lib helpers.d.ts helpers.js index.d.ts index.js package.json src helpers.ts index.ts tsconfig.json hw-transport README.md lib-es Transport.d.ts Transport.js lib Transport.d.ts Transport.js package.json src Transport.ts tsconfig.json logs README.md lib-es index.d.ts index.js lib index.d.ts index.js package.json src index.ts tsconfig.json package.json src TransportNodeHid.ts tsconfig.json hw-transport-node-hid README.md lib-es TransportNodeHid.d.ts TransportNodeHid.js listenDevices.d.ts listenDevices.js lib TransportNodeHid.d.ts TransportNodeHid.js listenDevices.d.ts listenDevices.js node_modules @ledgerhq devices README.md 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.js tsconfig.json errors README.md lib-es helpers.d.ts helpers.js index.d.ts index.js lib helpers.d.ts helpers.js index.d.ts index.js package.json src helpers.ts index.ts tsconfig.json hw-transport README.md lib-es Transport.d.ts Transport.js lib Transport.d.ts Transport.js package.json src Transport.ts tsconfig.json logs README.md lib-es index.d.ts index.js lib index.d.ts index.js package.json src index.ts tsconfig.json package.json src TransportNodeHid.ts listenDevices.ts tsconfig.json hw-transport-u2f README.md lib-es TransportU2F.js lib TransportU2F.js package.json src TransportU2F.js hw-transport-webhid README.md flow webhid.js lib-es TransportWebHID.js lib TransportWebHID.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 package.json src TransportWebUSB.js webusb.js 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 @sindresorhus is dist index.d.ts index.js package.json readme.md @sinonjs commons CHANGES.md 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.js function.js index.js index.test.js map.js object.js set.js string.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.d.ts function.d.ts index.d.ts map.d.ts object.d.ts set.d.ts string.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 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 repl.d.ts stream.d.ts stream consumers.d.ts promises.d.ts web.d.ts string_decoder.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 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 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 agent-base README.md dist src index.d.ts index.js promisify.d.ts promisify.js package.json src index.ts promisify.ts 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-align CHANGELOG.md README.md index.js 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 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 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 @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 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 binaryen README.md index.d.ts package-lock.json package.json wasm.d.ts 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 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 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 bin asc.js asinit.js dist asc.d.ts asc.generated.d.ts asc.js assemblyscript.d.ts assemblyscript.generated.d.ts assemblyscript.js transform.d.ts transform.js web.html lib README.md binaryen.d.ts binaryen.js node_modules long README.md index.d.ts index.js package.json umd index.d.ts index.js package.json package.json std README.md assembly.json assembly array.ts arraybuffer.ts atomics.ts bindings asyncify.ts dom.ts node.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 performance.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 runtime.ts target.ts tsconfig.json typeinfo.ts staticarray.ts string.ts symbol.ts table.ts tsconfig.json typedarray.ts uri.ts util bytes.ts 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 util README.md browser fs.js module.js path.js process.js url.js cpu.d.ts cpu.js find.d.ts find.js node.d.ts node.js options.d.ts options.js terminal.d.ts terminal.js text.d.ts text.js tsconfig.json web.d.ts web.js 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 base64-js README.md base64js.min.js index.d.ts index.js package.json binary-install README.md example binary.js package.json run.js index.js package.json src binary.js binaryen README.md bin package.json index.d.ts 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 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 boxen index.d.ts index.js node_modules camelcase index.d.ts index.js package.json readme.md 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 callsites index.d.ts index.js package.json readme.md 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 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 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 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 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 node_modules .bin sha.js package.json test.js create-hmac README.md browser.js index.js legacy.js node_modules .bin sha.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-random-string index.d.ts index.js package.json readme.md 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 decompress-response 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 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 bin detect-libc.js lib detect-libc.js package.json 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 dot-prop index.d.ts index.js package.json readme.md duplexer3 LICENSE.md README.md index.js package.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 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 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 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 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-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 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.d.ts index.js package.json readme.md flagged-respawn README.md index.js lib is-v8flags.js remover.js reorder.js respawn.js package.json 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-constants README.md browser.js index.js 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 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-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 package.json readme.md globals globals.json index.d.ts index.js package.json readme.md got 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 hasurl 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 https-proxy-agent README.md dist agent.d.ts agent.js index.d.ts index.js parse-proxy-response.d.ts parse-proxy-response.js package.json ieee754 README.md index.d.ts 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 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-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-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-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-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.js package.json tests.js 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 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 node_modules @babel code-frame README.md lib index.js package.json 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 js-base64 LICENSE.md README.md base64.d.ts base64.js package.json 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 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 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 keyv README.md package.json src index.js latest-version index.d.ts index.js package.json readme.md 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 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 long README.md dist long.js index.js package.json src long.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 micromatch README.md index.js package.json mimic-response index.js package.json readme.md 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 mixpanel .travis.yml example.js history.md lib groups.js mixpanel-node.d.ts mixpanel-node.js people.js profile_helpers.js utils.js package.json readme.md test alias.js config.js groups.js import.js people.js send_request.js track.js utils.js mkdirp-classic README.md 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 mustache CHANGELOG.md README.md mustache.js mustache.min.js package.json napi-build-utils README.md index.js index.md package.json natural-compare README.md index.js 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 package.json near-cli CHANGELOG.md 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 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 deprecation-warning.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-mock-vm assembly __tests__ main.ts context.ts index.ts outcome.ts vm.ts bin bin.js node_modules @assemblyscript loader README.md index.d.ts index.js package.json umd index.d.ts index.js package.json 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 node_modules @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 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 binaryen README.md index.d.ts package-lock.json package.json wasm.d.ts 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-seed-phrase .eslintrc.yml .fossa.yml .travis.yml index.js package.json test index.test.js 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 node-abi .github workflows update-abi.yml .travis.yml CODE_OF_CONDUCT.md CONTRIBUTING.md README.md abi_registry.json index.js node_modules semver CHANGELOG.md README.md package.json semver.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 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 optionator CHANGELOG.md README.md lib help.js index.js util.js package.json p-cancelable 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-try 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 parent-module index.js package.json readme.md parse-passwd README.md index.js package.json 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 pbkdf2 README.md browser.js index.js lib async.js default-encoding.js precondition.js sync-browser.js sync.js to-buffer.js node_modules .bin sha.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 prelude-ls CHANGELOG.md README.md lib Func.js List.js Num.js Obj.js Str.js index.js package.json 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 progress CHANGELOG.md Readme.md index.js lib node-progress.js package.json pump .travis.yml README.md index.js package.json test-browser.js test-node.js punycode LICENSE-MIT.txt README.md package.json punycode.es6.js punycode.js pupa index.d.ts index.js package.json readme.md 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 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 node_modules ini README.md ini.js package.json strip-json-comments index.js package.json readme.md 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 regexpp README.md index.d.ts index.js package.json 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 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 responselike README.md package.json src index.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 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 shebang-command index.js package.json readme.md shebang-regex index.d.ts index.js package.json readme.md 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 README.md index.js node_modules decompress-response index.d.ts index.js package.json readme.md mimic-response index.d.ts index.js package.json readme.md package.json 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 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-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-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 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 tcp-port-used README.md index.js node_modules debug README.md package.json src browser.js common.js index.js node.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 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 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-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 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-check README.md lib check.js index.js parse-type.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 universal-url README.md browser.js index.js node_modules tr46 LICENSE.md README.md index.js lib mappingTable.json regexes.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 URLSearchParams-impl.js URLSearchParams.js infra.js public-api.js url-state-machine.js urlencoded.js utils.js package.json package.json update-notifier check.js index.js package.json readme.md 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 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 v8-compile-cache CHANGELOG.md README.md package.json v8-compile-cache.js v8flags README.md config-path.js index.js package.json 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 public-api.js url-state-machine.js utils.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 widest-line index.d.ts index.js package.json readme.md 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 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 | Inspector mode only ----------- features not yet implemented issues with the tests differences between PCRE and JS regex | | | | | nested-env-vars package.json scripts setup.sh tests index.js
# 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 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**. # <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/ 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. # 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. # 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. # 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. # 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. <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: 'joe.bloggs@example.com' } ``` `$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 ajv.validator@gmail.com - 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) # 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;julian@juliangruber.com&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-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. # 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 # 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. # 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' ``` 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/main?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 import binaryen from "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 main/latest. ### Command line The package includes Node.js builds of [wasm-opt](https://github.com/WebAssembly/binaryen#wasm-opt) and [wasm2js](https://github.com/WebAssembly/binaryen#wasm2js). 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/main/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-) - [Bulk memory operations 🦄](#bulk-memory-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[]`, 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/main/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#memory.**atomic.wait32**(ptr: `ExpressionRef`, expected: `ExpressionRef`, timeout: `ExpressionRef`): `ExpressionRef` * Module#memory.**atomic.wait64**(ptr: `ExpressionRef`, expected: `ExpressionRef`, timeout: `ExpressionRef`): `ExpressionRef` * Module#memory**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**(name: `string`, body: `ExpressionRef`, catchTags: `string[]`, catchBodies: `ExpressionRef[]`, delegateTarget: `string`): `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` #### [Bulk memory operations](https://github.com/WebAssembly/bulk-memory-operations/blob/master/proposals/bulk-memory-operations/Overview.md) 🦄 * Module#memory.**init**(segment: `number`, dest: `ExpressionRef`, offset: `ExpressionRef`, size: `ExpressionRef`): `ExpressionRef` * Module#memory.**copy**(dest: `ExpressionRef`, source: `ExpressionRef`, size: `ExpressionRef`): `ExpressionRef` * Module#memory.**fill**(dest: `ExpressionRef`, value: `ExpressionRef`, size: `ExpressionRef`): `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. # 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/become_a_patron_button@2x.png" 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._ # 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) <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 # 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 # 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 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://img.shields.io/github/workflow/status/dcodeIO/long.js/Test/main?label=test&logo=github)](https://github.com/dcodeIO/long.js/actions?query=workflow%3ATest) [![Publish Status](https://img.shields.io/github/workflow/status/dcodeIO/long.js/Publish/main?label=publish&logo=github)](https://github.com/dcodeIO/long.js/actions?query=workflow%3APublish) [![npm](https://img.shields.io/npm/v/long.svg?label=npm&color=007acc&logo=npm)](https://www.npmjs.com/package/long) 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 package exports an ECMAScript module with an UMD fallback. ``` $> npm install long ``` ```js import Long from "long"; var value = new Long(0xFFFFFFFF, 0x7FFFFFFF); console.log(value.toString()); ... ``` Note that mixing ESM and CommonJS is not recommended as it yields different classes, albeit with the same functionality. ### Usage with a CDN * From GitHub via [jsDelivr](https://www.jsdelivr.com):<br /> `https://cdn.jsdelivr.net/gh/dcodeIO/long.js@TAG/index.js` (ESM) * From npm via [jsDelivr](https://www.jsdelivr.com):<br /> `https://cdn.jsdelivr.net/npm/long@VERSION/index.js` (ESM)<br /> `https://cdn.jsdelivr.net/npm/long@VERSION/umd/index.js` (UMD) * From npm via [unpkg](https://unpkg.com):<br /> `https://unpkg.com/long@VERSION/index.js` (ESM)<br /> `https://unpkg.com/long@VERSION/umd/index.js` (UMD) Replace `TAG` respectively `VERSION` with a [specific version](https://github.com/dcodeIO/long.js/releases) or omit it (not recommended in production) to use main/latest. 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 or zero. * 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#**countLeadingZeros**/**clz**(): `number`<br /> Returns count leading zeros of this Long. * Long#**countTrailingZeros**/**ctz**(): `number`<br /> Returns count trailing zeros 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#**rotateLeft**/**rotl**(numBits: `Long | number | string`): `Long`<br /> Returns this Long with bits rotated to the left by the given amount. * Long#**rotateRight**/**rotr**(numBits: `Long | number | string`): `Long`<br /> Returns this Long with bits rotated 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. WebAssembly support ------------------- [WebAssembly](http://webassembly.org) supports 64-bit integer arithmetic out of the box, hence a [tiny WebAssembly module](./wasm.wat) is used to compute operations like multiplication, division and remainder more efficiently (slow operations like division are around twice as fast), falling back to floating point based computations in JavaScript where WebAssembly is not yet supported, e.g., in older versions of node. Building -------- Building the UMD fallback: ``` $> npm run build ``` Running the [tests](./tests): ``` $> npm test ``` 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 ``` # 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. ### 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. 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 // 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 # 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 # 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 # 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 # 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. # 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. # 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 # 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. Shims used when bundling asc for browser usage. ![](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) # 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/ # 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. # 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) 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) # 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. # 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)) ``` # 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;julian@juliangruber.com&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. # 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. # 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 tslib@1.6.1 ``` ## yarn ```sh # TypeScript 2.3.3 or later yarn add tslib # TypeScript 2.3.2 or earlier yarn add tslib@1.6.1 ``` ## bower ```sh # TypeScript 2.3.3 or later bower install tslib # TypeScript 2.3.2 or earlier bower install tslib@1.6.1 ``` ## JSPM ```sh # TypeScript 2.3.3 or later jspm install tslib # TypeScript 2.3.2 or earlier jspm install tslib@1.6.1 ``` # 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/) # 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 # 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. # 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 # <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 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)); ``` <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 ajv.validator@gmail.com - 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) 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`. Library ======= Additional packages provided by the main package. | Package | Description |------------------------------------|------------------------- | [@assemblyscript/loader](./loader) | Module loader utility | [@assemblyscript/rtrace](./rtrace) | Runtime tracing utility | binaryen | Binaryen proxy The Binaryen proxy herein is imported accross the code base and forwards the `binaryen` npm package by default. It can be modified to use a custom build, for example for testing purposes. # 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._ 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 <nathan@tootallnate.net> 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. [![SWUbanner](https://raw.githubusercontent.com/vshymanskyy/StandWithUkraine/main/banner2-direct.svg)](https://github.com/vshymanskyy/StandWithUkraine/blob/main/docs/README.md) <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/main?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/main?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 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 maintainers and 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> ## Development instructions A development environment can be set up by cloning the repository: ```sh git clone https://github.com/AssemblyScript/assemblyscript.git cd assemblyscript npm install npm link ``` The link step is optional and makes the development instance available globally. The full process is documented as part of the repository: * [Compiler instructions](./src) * [Runtime instructions](./std/assembly/rt) * [Test instructions](./tests) # 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) * [Keyboards and Mice](#keyboards-and-mice) * [Mac notes](#mac-notes) * [Windows notes](#windows-notes) * [Xbox 360 Controller on Windows 10](#xbox-360-controller-on-windows-10) * [Linux notes](#linux-notes) * [Selecting driver type](#selecting-driver-type) * [udev device permissions](#udev-device-permissions) * [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 v14 ### Supported Electron versions ### * Electron v3 to * Electron v11 #### Any newer version of Electron or Node MAY NOT WORK Native modules like `node-hid` require upstream dependencies to be updated to work with newer Node and Electron versions. Unless you need the features in the most recent Electron or Node, use a supported version. ## Installation For most "standard" use cases (node v4.x on mac, linux, windows on a x86 or x64 processor), `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. ### Keyboards and Mice 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. There are non-standard work-arounds for this, but in general you cannot use `node-hid` to access keyboard-like devices. ## 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 `node-hid@0.7.0`, the [hidraw](https://www.kernel.org/doc/Documentation/hid/hidraw.txt) driver is used to talk to HID devices. Before `node-hid@0.7.0`, 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 node-hid@0.5.7 ``` 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` * gcc-4.8+: `apt install gcc-4.8 g++-4.8 && export CXX=g++-4.8` * libusb-1.0-0 w/headers:`apt install libusb-1.0-0 libusb-1.0-0-dev` * libudev-dev: `apt install libudev-dev` (Debian/Ubuntu) / `yum install libusbx-devel` (Fedora) ### 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 * 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-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. # 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' ``` # `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/). # 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_BUILD` | 🚫 | | [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` | 🚫 | | [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` | ✅ | | [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` | ✅ | | [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` | 🚫 | ## 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) # 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 # 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) Shims used when bundling asc for browser usage. 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. # 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. # 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. # 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. # 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. # 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 # 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) # 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. # 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. # 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 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. # 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;calvin.metcalf@gmail.com&gt; - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 * **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) &lt;mathiasbuus@gmail.com&gt; * **Matteo Collina** ([@mcollina](https://github.com/mcollina)) &lt;matteo.collina@gmail.com&gt; - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E * **Irina Shestak** ([@lrlna](https://github.com/lrlna)) &lt;shestak.irina@gmail.com&gt; * **Yoshua Wyuts** ([@yoshuawuyts](https://github.com/yoshuawuyts)) &lt;yoshuawuyts@gmail.com&gt; [sauce]: https://saucelabs.com # 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. # 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 # 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. # 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 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. # 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) ``` [![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_ 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. # 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) ## 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 ``` # 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. # 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/ ## 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. 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. # 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 # 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 [![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 # NEAR CLI (command line interface) [![Build Status](https://travis-ci.com/near/near-cli.svg?branch=master)](https://travis-ci.com/near/near-cli) [![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 | | **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_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> --- ## 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. # 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 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) # 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 # 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 # 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 # 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) # 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;tj@vision-media.ca&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. # 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 # 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) 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. # 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. # 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) ## 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. # 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) # 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 # 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. # 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`. <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 # 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). ## 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). 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) [![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/js-base64@3.7.2/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/js-base64@3.7.2/base64.mjs'; </script> ``` ```html <script type="module"> // or if you prefer no Base64 namespace import { encode, decode } from 'https://cdn.jsdelivr.net/npm/js-base64@3.7.2/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) [![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). # 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). # 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 # 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 ``` 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 # 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). # 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 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. # 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' ``` [![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 # 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')` # 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). 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;nathan@tootallnate.net&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. 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 <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 # 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 `acorn-jsx@3.0`. 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). 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"`. 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 }); ``` [![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) # 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._ # 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 # 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. # simple-get [![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-get/master.svg [travis-url]: https://travis-ci.org/feross/simple-get [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) {}) ``` ### 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) 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` # 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) <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). # 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 # 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 <tannerntannern@gmail.com> * Website - [tannernielsen.com](http://tannernielsen.com) * Github - [tannerntannern](https://github.com/tannerntannern) # 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 # 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. # 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 [![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. # 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 tunnel-agent ============ HTTP proxy tunneling agent. Formerly part of mikeal/request, now a standalone module. # 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' ``` # 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://github.com/prebuild/prebuild-install/actions/workflows/test.yml/badge.svg)](https://github.com/prebuild/prebuild-install/actions/workflows/test.yml) [![david](https://david-dm.org/prebuild/prebuild-install.svg)](https://david-dm.org/prebuild/prebuild-install) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/) ## 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" } } ``` ### 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` and `--platform` 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` and `npm_config_runtime`. ### 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 `leveldown@1.2.3` 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` ## 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. 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 `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value components are invalid (`9999999999999999.4.7.4` is likely invalid). ### 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. 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`. 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` # NCD-Bookshop-Example > note: edited this repo for missing ncd project createria context,assert,scripting Here is my Book Shop project for NEAR Protocol create book find and deleting functions avaliable for now. Instructions ``` near-login ``` Repo Clone ``` git clone https://github.com/mrtlive/NCD-Bookshop-Example ``` if near-cli not installed ``` npm install --global near-cli cd NCD-Bookshop-Example yarn ``` easy setup ``` cd scripts bash setup.sh export CONTRACT=<YOUR_ACCOUNT_ID> ``` Functions user info ``` near call $CONTRACT userInfo --accountId <your_account>.testnet ``` get all books data ``` near call $CONTRACT getBooks --accountId <your_account>.testnet ``` createbook ``` near call $CONTRACT createBook '{"book_name":"<BookName>","author":"<Author>","price":<Price>,"quantity":<Quantity>}' --accountId <your_account>.testnet ``` view with id ``` near view $CONTRACT getById '{"id":<ID>}' --accountId <your_account>.testnet ``` delete with id ``` near call $CONTRACT del '{"id":<ID>}' --accountId <your_account>.testnet ``` this is my first project for patika.dev bootcamp thanks. # core-util-is The `util.is*` functions introduced in Node v0.12. # 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], } */ ``` # 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;tj@vision-media.ca&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-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._ # 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. # duplexer3 [![Build Status](https://travis-ci.org/floatdrop/duplexer3.svg?branch=master)](https://travis-ci.org/floatdrop/duplexer3) [![Coverage Status](https://coveralls.io/repos/floatdrop/duplexer3/badge.svg?branch=master&service=github)](https://coveralls.io/github/floatdrop/duplexer3?branch=master) Like [duplexer2](https://github.com/deoxxa/duplexer2) but using Streams3 without readable-stream dependency ```javascript var stream = require("stream"); var duplexer3 = require("duplexer3"); var writable = new stream.Writable({objectMode: true}), readable = new stream.Readable({objectMode: true}); writable._write = function _write(input, encoding, done) { if (readable.push(input)) { return done(); } else { readable.once("drain", done); } }; readable._read = function _read(n) { // no-op }; // simulate the readable thing closing after a bit writable.once("finish", function() { setTimeout(function() { readable.push(null); }, 500); }); var duplex = duplexer3(writable, readable); duplex.on("data", function(e) { console.log("got data", JSON.stringify(e)); }); duplex.on("finish", function() { console.log("got finish event"); }); duplex.on("end", function() { console.log("got end event"); }); duplex.write("oh, hi there", function() { console.log("finished writing"); }); duplex.end(function() { console.log("finished ending"); }); ``` ``` got data "oh, hi there" finished writing got finish event finished ending got end event ``` ## Overview This is a reimplementation of [duplexer](https://www.npmjs.com/package/duplexer) using the Streams3 API which is standard in Node as of v4. Everything largely works the same. ## Installation [Available via `npm`](https://docs.npmjs.com/cli/install): ``` $ npm i duplexer3 ``` ## API ### duplexer3 Creates a new `DuplexWrapper` object, which is the actual class that implements most of the fun stuff. All that fun stuff is hidden. DON'T LOOK. ```javascript duplexer3([options], writable, readable) ``` ```javascript const duplex = duplexer3(new stream.Writable(), new stream.Readable()); ``` Arguments * __options__ - an object specifying the regular `stream.Duplex` options, as well as the properties described below. * __writable__ - a writable stream * __readable__ - a readable stream Options * __bubbleErrors__ - a boolean value that specifies whether to bubble errors from the underlying readable/writable streams. Default is `true`. ## License 3-clause BSD. [A copy](./LICENSE) is included with the source. ## Contact * GitHub ([deoxxa](http://github.com/deoxxa)) * Twitter ([@deoxxa](http://twitter.com/deoxxa)) * Email ([deoxxa@fknsrs.biz](mailto:deoxxa@fknsrs.biz)) # 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;tj@vision-media.ca&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. 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. # 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) # 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. 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 (olalonde@gmail.com) - James Talmage (james@talmage.io) - [Ruben Verborgh](https://ruben.verborgh.org/) ## License [https://github.com/follow-redirects/follow-redirects/blob/master/LICENSE](MIT License) 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.) # 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/become_a_patron_button@2x.png" 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._ # `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) # 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. # 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 # 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 [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;lauri@rooden.ee&gt; [The MIT License](http://lauri.rooden.ee/mit-license.txt) # 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 # 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). # 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. # 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). # 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. 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) # 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._ # 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:pass@example.com: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:alpha@example.com,bravo@example.com?subject=SUBSCRIBE&body=Sign%20me%20up!"); //returns: //{ // scheme : "mailto", // to : ["alpha@example.com", "bravo@example.com"], // subject : "SUBSCRIBE", // body : "Sign me up!" //} URI.serialize({ scheme : "mailto", to : ["alpha@example.com"], subject : "REMOVE", body : "Please remove me", headers : { cc : "charlie@example.com" } }) === "mailto:alpha@example.com?cc=charlie@example.com&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. # 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._ # 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 (emn178@gmail.com) # 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() ``` 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')` # 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 # 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) ``` # 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 }); } ``` # 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`. # 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) # 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. 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;nathan@tootallnate.net&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. # 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 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. ### 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. 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` 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. 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` agent-base ========== ### Turn a function into an [`http.Agent`][http.Agent] instance [![Build Status](https://github.com/TooTallNate/node-agent-base/workflows/Node%20CI/badge.svg)](https://github.com/TooTallNate/node-agent-base/actions?workflow=Node+CI) This module provides an `http.Agent` generator. That is, you pass it an async callback function, and it returns a new `http.Agent` instance that will invoke the given callback function when sending outbound HTTP requests. #### Some subclasses: Here's some more interesting uses of `agent-base`. Send a pull request to list yours! * [`http-proxy-agent`][http-proxy-agent]: An HTTP(s) proxy `http.Agent` implementation for HTTP endpoints * [`https-proxy-agent`][https-proxy-agent]: An HTTP(s) proxy `http.Agent` implementation for HTTPS endpoints * [`pac-proxy-agent`][pac-proxy-agent]: A PAC file proxy `http.Agent` implementation for HTTP and HTTPS * [`socks-proxy-agent`][socks-proxy-agent]: A SOCKS proxy `http.Agent` implementation for HTTP and HTTPS Installation ------------ Install with `npm`: ``` bash $ npm install agent-base ``` Example ------- Here's a minimal example that creates a new `net.Socket` connection to the server for every HTTP request (i.e. the equivalent of `agent: false` option): ```js var net = require('net'); var tls = require('tls'); var url = require('url'); var http = require('http'); var agent = require('agent-base'); var endpoint = 'http://nodejs.org/api/'; var parsed = url.parse(endpoint); // This is the important part! parsed.agent = agent(function (req, opts) { var socket; // `secureEndpoint` is true when using the https module if (opts.secureEndpoint) { socket = tls.connect(opts); } else { socket = net.connect(opts); } return socket; }); // Everything else works just like normal... http.get(parsed, function (res) { console.log('"response" event!', res.headers); res.pipe(process.stdout); }); ``` Returning a Promise or using an `async` function is also supported: ```js agent(async function (req, opts) { await sleep(1000); // etc… }); ``` Return another `http.Agent` instance to "pass through" the responsibility for that HTTP request to that agent: ```js agent(function (req, opts) { return opts.secureEndpoint ? https.globalAgent : http.globalAgent; }); ``` API --- ## Agent(Function callback[, Object options]) → [http.Agent][] Creates a base `http.Agent` that will execute the callback function `callback` for every HTTP request that it is used as the `agent` for. The callback function is responsible for creating a `stream.Duplex` instance of some kind that will be used as the underlying socket in the HTTP request. The `options` object accepts the following properties: * `timeout` - Number - Timeout for the `callback()` function in milliseconds. Defaults to Infinity (optional). The callback function should have the following signature: ### callback(http.ClientRequest req, Object options, Function cb) → undefined The ClientRequest `req` can be accessed to read request headers and and the path, etc. The `options` object contains the options passed to the `http.request()`/`https.request()` function call, and is formatted to be directly passed to `net.connect()`/`tls.connect()`, or however else you want a Socket to be created. Pass the created socket to the callback function `cb` once created, and the HTTP request will continue to proceed. If the `https` module is used to invoke the HTTP request, then the `secureEndpoint` property on `options` _will be set to `true`_. License ------- (The MIT License) Copyright (c) 2013 Nathan Rajlich &lt;nathan@tootallnate.net&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. [http-proxy-agent]: https://github.com/TooTallNate/node-http-proxy-agent [https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent [pac-proxy-agent]: https://github.com/TooTallNate/node-pac-proxy-agent [socks-proxy-agent]: https://github.com/TooTallNate/node-socks-proxy-agent [http.Agent]: https://nodejs.org/api/http.html#http_class_http_agent # 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 <!-- -- 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 `uuid@3.x`?** Your code is probably okay, but check out [Upgrading From `uuid@3.x`](#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 `uuid@8.3` | | [`uuid.parse()`](#uuidparsestr) | Convert UUID string to array of bytes | New in `uuid@8.3` | | [`uuid.stringify()`](#uuidstringifyarr-offset) | Convert array of bytes to UUID string | New in `uuid@8.3` | | [`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 `uuid@8.3` | | [`uuid.version()`](#uuidversionstr) | Detect RFC version of a UUID | New in `uuid@8.3` | ## 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 `react-native-get-random-values@1.5.0` and `expo@39.0.0`. ### 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 `uuid@7.x` ### Only Named Exports Supported When Using with Node.js ESM `uuid@7.x` 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 `uuid@7.x`](#deep-requires-now-deprecated) are no longer supported. ## Upgrading From `uuid@3.x` "_Wait... what happened to `uuid@4.x` - `uuid@6.x`?!?_" 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 `uuid@3.x` 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 `uuid@7.x` 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 `uuid@3.x` was exporting the Version 4 UUID method as a default export: ```javascript const uuid = require('uuid'); // <== REMOVED! ``` This usage pattern was already discouraged in `uuid@3.x` and has been removed in `uuid@7.x`. ---- Markdown generated from [README_js.md](README_js.md) by [![RunMD Logo](http://i.imgur.com/h0FVyzU.png)](https://github.com/broofa/runmd) [![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). # 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;christopher.s.dickinson@gmail.com&gt; - Release GPG key: 9554F04D7259F04124DE6B476D5A82AC7E37093B * **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) &lt;calvin.metcalf@gmail.com&gt; - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 * **Rod Vagg** ([@rvagg](https://github.com/rvagg)) &lt;rod@vagg.org&gt; - Release GPG key: DD8F2338BAE7501E3DD5AC78C273792F7D83545D * **Sam Newman** ([@sonewman](https://github.com/sonewman)) &lt;newmansam@outlook.com&gt; * **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) &lt;mathiasbuus@gmail.com&gt; * **Domenic Denicola** ([@domenic](https://github.com/domenic)) &lt;d@domenic.me&gt; * **Matteo Collina** ([@mcollina](https://github.com/mcollina)) &lt;matteo.collina@gmail.com&gt; - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E * **Irina Shestak** ([@lrlna](https://github.com/lrlna)) &lt;shestak.irina@gmail.com&gt; <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 # <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/ # 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() } } ``` # 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). # 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. # 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._ # 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) # 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._ # 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). # 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. 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). # 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. https-proxy-agent ================ ### An HTTP(s) proxy `http.Agent` implementation for HTTPS [![Build Status](https://github.com/TooTallNate/node-https-proxy-agent/workflows/Node%20CI/badge.svg)](https://github.com/TooTallNate/node-https-proxy-agent/actions?workflow=Node+CI) This module provides an `http.Agent` implementation that connects to a specified HTTP or HTTPS proxy server, and can be used with the built-in `https` module. Specifically, this `Agent` implementation connects to an intermediary "proxy" server and issues the [CONNECT HTTP method][CONNECT], which tells the proxy to open a direct TCP connection to the destination server. Since this agent implements the CONNECT HTTP method, it also works with other protocols that use this method when connecting over proxies (i.e. WebSockets). See the "Examples" section below for more. Installation ------------ Install with `npm`: ``` bash $ npm install https-proxy-agent ``` Examples -------- #### `https` module example ``` js var url = require('url'); var https = require('https'); var HttpsProxyAgent = require('https-proxy-agent'); // HTTP/HTTPS proxy to connect to var proxy = process.env.http_proxy || 'http://168.63.76.32:3128'; console.log('using proxy server %j', proxy); // HTTPS endpoint for the proxy to connect to var endpoint = process.argv[2] || 'https://graph.facebook.com/tootallnate'; console.log('attempting to GET %j', endpoint); var options = url.parse(endpoint); // create an instance of the `HttpsProxyAgent` class with the proxy server information var agent = new HttpsProxyAgent(proxy); options.agent = agent; https.get(options, function (res) { console.log('"response" event!', res.headers); res.pipe(process.stdout); }); ``` #### `ws` WebSocket connection example ``` js var url = require('url'); var WebSocket = require('ws'); var HttpsProxyAgent = require('https-proxy-agent'); // HTTP/HTTPS proxy to connect to var proxy = process.env.http_proxy || 'http://168.63.76.32:3128'; console.log('using proxy server %j', proxy); // WebSocket endpoint for the proxy to connect to var endpoint = process.argv[2] || 'ws://echo.websocket.org'; var parsed = url.parse(endpoint); console.log('attempting to connect to WebSocket %j', endpoint); // create an instance of the `HttpsProxyAgent` class with the proxy server information var options = url.parse(proxy); var agent = new HttpsProxyAgent(options); // finally, initiate the WebSocket connection var socket = new WebSocket(endpoint, { agent: agent }); socket.on('open', function () { console.log('"open" event!'); socket.send('hello world'); }); socket.on('message', function (data, flags) { console.log('"message" event! %j %j', data, flags); socket.close(); }); ``` API --- ### new HttpsProxyAgent(Object options) The `HttpsProxyAgent` class implements an `http.Agent` subclass that connects to the specified "HTTP(s) proxy server" in order to proxy HTTPS and/or WebSocket requests. This is achieved by using the [HTTP `CONNECT` method][CONNECT]. The `options` argument may either be a string URI of the proxy server to use, or an "options" object with more specific properties: * `host` - String - Proxy host to connect to (may use `hostname` as well). Required. * `port` - Number - Proxy port to connect to. Required. * `protocol` - String - If `https:`, then use TLS to connect to the proxy. * `headers` - Object - Additional HTTP headers to be sent on the HTTP CONNECT method. * Any other options given are passed to the `net.connect()`/`tls.connect()` functions. License ------- (The MIT License) Copyright (c) 2013 Nathan Rajlich &lt;nathan@tootallnate.net&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. [CONNECT]: http://en.wikipedia.org/wiki/HTTP_tunnel#HTTP_CONNECT_Tunneling <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 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. # 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. # 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._ # 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 <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> 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) # 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 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. # 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. # 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** # 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. # 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. [![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) # 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://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> 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 # 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. ### 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. # <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/ 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. 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) # 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). # [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} } ``` # 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._ # 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). 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. [![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 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` # 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'); ``` <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 `ignore@2.x` 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* # 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._ # 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;julian@juliangruber.com&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 # 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 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 }); }); ... ``` # 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) 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`. # <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/ 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. # 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) # 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 # 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. # 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. 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 ``` # 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 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) <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 # 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) # 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`. # 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. <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 ``` # 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/yargs-parser@19.0.0/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 # 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. # 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. 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 # 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 <hdegoede@redhat.com> - Xiaofan Chen <xiaofanc@gmail.com> - Ludovic Rousseau <ludovic.rousseau@gmail.com> - Nathan Hjelm <hjelmn@cs.unm.edu> - Chris Dickens <christopher.a.dickens@gmail.com> (Please use the mailing list rather than mailing developers directly) 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 Utility ======= Various utility functions shared accross the codebase. | Utility | Description |----------|------------------------------------------- | cpu | Obtains information about the CPU | find | Provides support for finding files etc. | node | Minimal polyfills for Node.js builtins | options | Support for command line options parsing | terminal | Provides support for terminal colors | text | Utility for text processing | web | Minimal polyfills for browser builtins It is possible to reuse the utility in your own project like so: ```ts import { ... } from "assemblyscript/util/terminal.js"; ... ``` Keep in mind, however, that utility can change at any time. # 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.
farukulutas_NearDeployExample
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 ``` ## Transaction made with test deployment. Transaction Link: https://explorer.testnet.near.org/transactions/HF6xSra6WdpJQVXi2T8Qfs8RHxBptDzLeX4pseSfqAkn <img src="https://github.com/farukulutas/NearDeployExample/blob/main/near_deploy.PNG"/>
kiennguyensys_cherry-pub
Cargo.toml README.md cherry-pool Cargo.toml src internal.rs lib.rs test_utils.rs nft Cargo.toml build.sh src lib.rs simulation Cargo.toml src lib.rs local.rs remote.rs
# cherry-pub PoolTogether in Near
Amplify-Art_marketplace-frontend
.env README.md package.json public amplify-logo-beta.svg favicon_package browserconfig.xml safari-pinned-tab.svg fonts fa css all.css all.min.css brands.css brands.min.css duotone.css duotone.min.css fontawesome.css fontawesome.min.css light.css light.min.css regular.css regular.min.css sharp-solid.css sharp-solid.min.css solid.css solid.min.css svg-with-js.css svg-with-js.min.css thin.css thin.min.css v4-font-face.css v4-font-face.min.css v4-shims.css v4-shims.min.css v5-font-face.css v5-font-face.min.css index.html manifest.json netlify.toml robots.txt src Api Album.js Auth.js Follower.js MarketplaceSong.js Moonpay.js NFT.js Near.js Nomination.js NominationVote.js Playlist.js SearchRes.js Showcase.js Song.js SupporterPayoutLog.js TokenTransfer.js Transaction.js User.js index.js App.css App.js App.test.js Components Common AlbumModalContent index.js AlbumSingleSong AlbumSingleSongTable.js index.js ArtistHeader index.js Button index.js GeneralModal index.js MainSideNav index.js NewNFT index.js Player Parts AlbumInfo index.js Controls index.js ProgressBar index.js PlayerQueue.js index.js test.js ProfileHeader index.js SideSocialNav index.js SingleAlbum index.js shimmer.js SingleAlbumModal index.js SingleMargedAlbum index.js SongLength index.js SongModalcontent index.js UseDebounce index.js UserAvatar index.js shimmer.js Parts AboutUs index.js AddShowCase index.js ArtistRegistry index.js Banner index.js CreatePlayList index.js Header index.js HowItWorks index.js LatestReleases index.js NominateModal index.js Partners index.js PurchasedSongs index.js SearchResultCard index.js SongList index.js SupportArtists index.js ThankYou index.js TheTeam index.js TheTech index.js TransactionList index.js WeAreFor index.js WhatPeopleAreSaying index.js Constants actions Album.js Artist.js Follower.js Global.js MarketplaceSong.js NFT.js Nomination.js NominationVote.js Playlist.js Showcase.js Song.js SupporterPayoutLog.js TokenTransfer.js Transaction.js User.js default.js near.js Containers Albums index.js ArtistDashbord index.js ArtistProfile Rolling.svg index.js Artists index.js Auth.js Home index.js MyProfile index.js Nominate index.js PageNotFound index.js Sandbox index.js SearchResult index.js SecondaryMarketplace index.js Settings ImageUploader.js index.js SignIn index.js Songs index.js SupportCard index.js TransactionDetails index.js UserDashboard index.js Wallet Parts SendModal.js TransactionModal.js index.js WalletSignTransaction index.js Utils covert.js near.js assets images CalanderIcon.svg Down_arrow.svg RightIcon.svg RightIconDisable.svg Sort.svg Vector.svg Vote.svg account-icon.svg artist-icon-badge.svg artist-icon.svg artistprofile-icon.svg bell-icon.svg cd-icon.svg cd-icon_.svg close-icon.svg close.svg closeicon.svg confetti.svg default-profile.svg discover-icon.svg ethereum.svg highblack copy 1.svg image-upload.svg infoicon.svg left-arrow.svg leftarrow.svg logo.svg logo_.svg logo_open_beta.svg logo_primary.svg logomark.svg menu-icon-new.svg menu-icon.svg mintbase.svg near.svg near_icon.svg near_icon_white.svg next.svg no-follow-bg.svg no-follow-icon.svg no-releases-bg.svg no-releases-icon.svg noise.svg pause.svg pause_icon.svg pinata.svg play.svg play_btn.svg play_icon.svg play_progress.svg prev.svg quote.svg raygun.svg reblock.svg reffinance.svg remove-icon.svg search-icon.svg search-icon_old.svg share-icon.svg share-icon_old.svg store-icon.svg trash.svg twitter-icon.svg twitter-logo.svg upload.svg wallet-icon.svg wallet-icon_old.svg history.js index.css index.js logo.svg redux actions AlbumAction.js ArtistAction.js FollowerAction.js GlobalAction.js MarketplaceSongAction.js NFTAction.js NominationAction.js NominationVoteAction.js PlaylistAction.js SearchResAction.js ShowcaseAction.js SongAction.js SupporterPayoutLog.js TokenTransferAction.js TransactionAction.js UserAction.js reducers AlbumReducer.js ArtistReducer.js FollowerReducer.js Global.js MarketplaceSongReducer.js NFTReducer.js NominationReducer.js NominationVoteReducer.js PlaylistReducer.js SearchResReducer.js ShowcaseReducer.js SongReducer.js SupporterPayoutLog.js TokenTransferReducer.js TransactionReducer.js UserReducer.js index.js sagas AlbumSaga.js ArtistSaga.js FollowerSaga.js GlobalSaga.js MarketplaceSongSaga.js NFTSaga.js NearSaga.js NominationSaga.js NominationVoteSaga.js PlaylistSaga.js SearchResSaga.js ShowcaseSaga.js SongSaga.js SupporterPayoutLog.js TokenTransferSaga.js TransactionSaga.js UserSaga.js index.js storeConfig store.js reportWebVitals.js setupTests.js
`yarn install` `yarn start`
nft-never-sleep_nft-ns-web
README.md babel.config.js config index.js nft-ns-web.js package-lock.json package.json public index.html logo.svg near-api-js.js src assets icon delete.svg img detail Cryptovoxel.svg Near_Hub.svg Twitter_blue.svg delete.svg left.svg paras.svg right.svg youminter.svg public banner.svg logo.svg no-bids.svg config constants.js near.js i18n i18n.js index.js lang en.js zh.js main.js router index.js store actions.js getters.js index.js mutations.js state.js utils chainMixin.js vueNear.js vue.config.js webpack.prod.config.js
# nft-ns-web ## Project setup ``` yarn install ``` ### Compiles and hot-reloads for development ``` yarn start ``` ### Compiles and minifies for production ``` yarn build ``` ### Customize configuration See [Configuration Reference](https://cli.vuejs.org/config/).
evolution001_Near-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 ```
Peersyst_Landstead
.idea workspace.xml README.md build css bootstrap.min.css font-awesome.min.css fonts fontawesome-webfont.svg nano.css ngToast.min.css start.html tests start.html tests.js vendors FileSaver.min.js bitcoinjs-min.js crypto-min.js cryptoJS aes.js cipher-core-min.js core-min.js enc-base64-min.js evpkdf-min.js hmac-min.js md5-min.js pbkdf2-min.js ripemd160-min.js sha1-min.js sha256-min.js sha3-min.js x64-core-min.js jszip.min.js kjua.min.js qrcode.js sha256.js sockjs-0.3.4.js stomp.js gulpfile.js package.json src app app.js components appBackground.directive.js importApostilleFiles.directive.js importNtyFile.directive.js index.js readWalletFiles.directive.js show-authed.directive.js showAccountData.directive.js showBlockHeight.directive.js showNetworkStatus.directive.js tagLevy.directive.js tagTransaction.directive.js config app.config.js app.constants.js app.run.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 modules about about.config.js about.html index.js account account.config.js account.controller.js account.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 manage message apostilleMessage.config.js apostilleMessage.controller.js apostilleMessage.html transfer transferApostille.config.js transferApostille.controller.js transferApostille.html update updateApostille.config.js updateApostille.controller.js updateApostille.html changelly changelly.config.js changelly.controller.js changelly.html index.js dashboard dashboard.config.js dashboard.controller.js dashboard.html index.js 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 faq faq.config.js faq.controller.js faq.html index.js home home.config.js home.controller.js home.html index.js importanceTransfer index.js multisig importanceTransfer.config.js importanceTransfer.controller.js importanceTransfer.html normal importanceTransfer.config.js importanceTransfer.controller.js importanceTransfer.html landstead citizenRegister citizenRegister.config.js citizenRegister.controller.js citizenRegister.html citizenRevoke citizenRevoke.config.js citizenRevoke.controller.js citizenRevoke.html index.js propertyOwnershipRegister propertyOwnershipRegister.config.js propertyOwnershipRegister.controller.js propertyOwnershipRegister.html propertyRegister propertyRegister.config.js propertyRegister.controller.js propertyRegister.html languages cn.js en.js index.js jp.js pl.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 namespaces index.js namespaces.config.js namespaces.controller.js namespaces.html portal index.js portal.config.js portal.controller.js portal.html signup index.js signup.config.js signup.controller.js signup.html transactions index.js transactions.config.js transactions.controller.js transactions.html transferTransaction index.js transferTransaction.config.js transferTransaction.controller.js transferTransaction.html services alert.service.js connector.service.js dataBridge.service.js index.js networkRequests.service.js transactions.service.js wallet.service.js walletBuilder.service.js utils Address.js CryptoHelpers.js KeyPair.js Network.js Serialization.js TransactionTypes.js bip32.js convert.js helpers.js nacl-fast.js nodes.js nty.js sinks.js css bootstrap.min.css font-awesome.min.css fonts fontawesome-webfont.svg ngToast.min.css start.html vendors FileSaver.min.js bitcoinjs-min.js crypto-min.js cryptoJS aes.js cipher-core-min.js core-min.js enc-base64-min.js evpkdf-min.js hmac-min.js md5-min.js pbkdf2-min.js ripemd160-min.js sha1-min.js sha256-min.js sha3-min.js x64-core-min.js jszip.min.js kjua.min.js qrcode.js sha256.js sockjs-0.3.4.js stomp.js tests data accountData.js wallet.js specs ImportanceTransferModule.spec.js address.spec.js convert.spec.js createMosaicModule.spec.js cryptoHelpers.spec.js dataBridge.spec.js editMosaicModule.spec.js filters.spec.js keyPair.spec.js loginModule.spec.js namespaceModule.spec.js signupModule.spec.js signupModuleDelegated.spec.js transactions.spec.js transferTransactionModule.spec.js transferTransactionModuleDelegated.spec.js wallet.spec.js walletBuilder.spec.js start.html
# LANDSTEAD # ## Land And Immovable Property Ownership Register ## Implementation of a Proof of Concept (POC) of an ownership register or cadastral system to prove the viability and usability of blockchain technologym for such a system in real life situations. The system is based on unique identifications and immutable registrations on the blockchain. Whitepaper: https://docs.google.com/document/d/14Vqi-J9_mw1wWLmQKjCUEQBT31zdekQ9D_25aHNyXTA/edit Website: http://landstead.atraurablockchain.com NEM: https://www.nem.io/ ##Terminology ## * BW - Brain wallet * MS - Multi Signature * IDc - Citizen Identification Number or Code * IDp - Property Identification Number or Code * [G] - Government's account (Private Key) * [C] - Citizen's account (Private Key, in other examples NAAAAA), must have received a country:citizen Asset with IDc as message * [PC] - Pointer to Citizen and brainwallet from IDc@atlantis:citizen (in other examples NPOINT1) * [P] - Property Account and brainwallet from IDp@atlantis:parcel (in other examples NPOINT2, although it is not needed to use it as a pointer account with a pointer message). Must have received a country:parcel Asset (representing the Property Type) with IDp as message * [N] - Notary Account (one that has received a country:notary Asset) ##Assets## * atlantis:citizen * atlantis:notary * atlantis:parcel ##Use Cases Implemented ## ###1. Register a Citizen### * User creates [C] on it's own and submits his account [C] for validation and registration * Gov. creates [G] and all the Assets Civil Servant continues registration use case 1. Civil Servant logs in to [G], and accesses 'Validate an account'. 2. A form with 2 fields is presented: the IDc of the citizen and the Citizen’s Account number [C]. 2.1 Civil Servant inputs ID Firstname Lastname@country:citizen (We could use Firstname and Lastname so nobody else can guess upfront what the account numbers will be, and because the date of birth is already integrated in the ID. At least that’s the case in Belgium) 2.2 [PC] BW gets created 2.3 [PC] is set to be a MS acct from [G] 2.4 [G] inputs account number of [C] to send message (ID=C) to [PC] 2.5 [G] sends atlantis:citizen to [C] ###2. Register a Property### 1. Civil Servant logs in to [G] and accesses ‘Register a Property’ 2. A form is presented with the following fields 2.1 Selection of Property Type: (drop down, for the moment ‘parcel’ is the only one for Atlantis) 2.2 IDp, identification code of the property. 3. Civil Servant enters the following information 3.1 he selects Property Type ‘Parcel’ 3.2 he enters the Parcel identification as IDp 3.3 he confirms with Send 3.3.1 [P] gets created from IDp@country:parcel 3.3.2 [G] sends message <IDp> together with 1 country:parcel Asset to [P] 3.3.3 Convert [P] into MS with cosigner [G] for protection Optional: When cadastral documents are available they can be Apostilled using [P] ###3. Register a Property Ownership### Once the Civil Servant has proof of ownership, based on existing cadastral services or existing paper Notary Acts, the magic can happen ;-) 1. Civil Servant logs in to [G] and accesses ‘Register property ownership’ 2. Form is presented with fields for 2.1 Type of owner (must be a country Asset, default citizen) 2.2 IDc 2.3 Property type (must be a country Asset, default parcel) 2.4 IDp 3. After providing the info and confirmation, the following steps are performed 3.1 [P] is determined based on IDp@country:parcel, Asset presence of country:parcel is checked in [P]. 3.2 [PC] is determined based on IDc@country:citizen 3.3 In [PC], Incoming messages from [G] are read to find the last message starting with “<IDc>=” 3.4 If that last message has an account after the “=”, that is the actual Account of the Citizen: |C] 3.5 Asset presence of country:citizen is checked in [C] 3.6 [P] is converted to multisig with 1 cosigner: [C] This represents the Citizen’s ownership of the property! ###4. Verify an account### 1. Citizen logs in to [C] and accesses ‘Verify account’ 2. Citizen can see in his balance he has received 1 country:citizen Asset from the Country, confirming the country has validated his IDc 3. Citizen can see in his balance he has received 1 or more country:parcel Assets from the Country, confirming the country has validated him/her as owner of the properties. 4. Additional info about the Properties can be provided based on: 4.1 the IDp mentioned in the same message from the Country in which the country:parcel Asset was received 4.2 the multisig accounts (can be more than one for rich people ;-) of which [C] is cosigner: [P] in this example 4.3 Any optional Apostille Accounts created for Property documents. These can be found as outgoing messages from [P] (See Use case Register a Property) ##Developers## Build from source 1) Install gulp npm install -g gulp-cli 2) Open a console to the path of the NanoWallet folder and install all the needed dependencies npm install 3) Build: gulp ##Thanks## This project is based on: https://github.com/QuantumMechanics/NanoWallet https://github.com/saulgray/NanoWallet We'd like to thank QuantumMechanics, SaulGray and the rest of NEM's development team for they great effort.
kmiyachi_NearCertification
Cargo.toml README.md build.sh deploy.sh dev-deploy.sh init-args.js rustfmt.toml src contract.rs lib.rs utils.rs
# NEAR Smart Contract Rust Template Project structure for writing smart contracts in Rust for NEAR Protocol # Required Software - Rust 1.58 + cargo - Node.js - NEAR CLI 3.1 # Authors - Jacob Lindahl <jacob@near.foundation> [@sudo_build](https://twitter.com/sudo_build)
PotLock_sui-contracts
.github ISSUE_TEMPLATE BOUNTY.yml README.md
# sui-contracts PotLock on Sui, built on move smart contracts
oleksanderkorn_nearvember-challenge-6
.eslintrc.yml .gitpod.yml README.md babel.config.js 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
# nearvember-challenge-6 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 `nearvember-challenge-6.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `nearvember-challenge-6.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 nearvember-challenge-6.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 || 'nearvember-challenge-6.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
Kuro-Bryan_Biblioteca_Gamer
README.md contract README.md babel.config.json build.sh deploy.sh package-lock.json package.json src contract.ts model.ts tsconfig.json frontend App.js index.html index.js near-interface.js near-wallet.js package-lock.json package.json start.sh package-lock.json package.json
# Contrato Biblioteca gamer El contrato inteligente guarda datos de los juegos brindados por el usuario. <br /> # Inicio Rapido 1. Asegurate de tener instalado [node.js](https://nodejs.org/en/download/package-manager/) >= 16. 2. Installar [`NEAR CLI`](https://github.com/near/near-cli#setup) <br /> ## 1. Construir y desplegar el contrato puedes compilar y desplegar automaticamente el contrato en NEAR testnet ejecutando el siguiente comando: ```bash npm run deploy ``` Cuando finalice, busca el documento `neardev/dev-account` para encontrar la dirección en la cual se desplegó el contrato ```bash cat ./neardev/dev-account # Ejemplo: dev-1659899566943-21539992274971 ``` <br /> ## 2. Recuperar los juegos guardados `get_games` es un metodo de solo lectura (metodo `view`) que devuelve una parte del vector `games`. Los metodos `View` pueden ser llamados **gratuitamente** por cualquiera, incluso por personas sin una cuenta de NEAR ```bash near view <dev-account> get_games '{"from_index":0, "limit":10}' ``` <br /> ## 3. Agregar un juego `add_game` Agrega los datos al vector `games`. ```bash # Usar near-cli para agregar un juego near call <dev-account> add_game '{"text": "a juego"}' --accountId <account> ``` [![](https://img.shields.io/badge/Contract-JS-yellow)](https://docs.near.org/develop/contracts/anatomy) [![](https://img.shields.io/badge/Frontend-React-blue)](https://docs.near.org/develop/integrate/frontend) La Biblioteca gamer es una app que guarda datos de un juego en especifico y muestra los datos recabados. # Como usar Clona este repositorio localmente y sigue estos pasos: ### 1. Installar Dependencias ```bash npm install ``` ### 2. Contruir Construir el contrato y desplegarlo en una cuenta testnet ```bash npm run deploy ``` ### 3. Iniciar el Front-end Iniciar la aplicación web para interactuar con el contrato inteligente ```bash npm start ``` ---
amusnation_nearmint
.env README.md package.json public index.html manifest.json robots.txt src App.js index.js near-interface.js near-wallet.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)
Learn-NEAR_NCD.L1.sample--promises
.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 model.ts tsconfig.json compile.js package-lock.json package.json copy-dev-account.js jest.config.js package.json src assets logo-black.svg logo-white.svg logo.svg config.js global.css main.js plugins vuetify.js utils.js tests unit Notification.spec.js vue.config.js
promises 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 promises ================== This [Vue] 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/main.js` is a great place to start exploring. 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 `promises.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `promises.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 promises.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 || 'promises.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. [Vue]: https://vuejs.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
near-examples_indexer-tx-watcher-example-lake
Cargo.toml README.md src configs.rs main.rs
Indexer that catches txs for specific contract(s) ================================================= **This project is a copy of https://github.com/near-examples/indexer-tx-watcher-example but is migrated to [NEAR Lake Framework](https://github.com/near/near-lake-framework). We keep them both separately as they show different approaches to the same use case** The most common use case for indexers is to react on a transaction sent to a specific contract or a list of contracts. This project is trying to provide an example of the indexer described about. It's simple yet doing the necessary stuff. In this example we don't use any external storage (like database or files) to keep track for the transactions to keep the example as simple as possible. We've tried to put the explanatory comments in the code to help developers to extend this example according to their needs. > Please refer to [NEAR Indexer for Explorer](https://github.com/near/near-indexer-for-explorer) to find an inspiration for extending the indexer. ## How it works Assuming we want to watch for transactions where a receiver account id is one of the provided in a list. We pass the list of account ids (or contracts it is the same) via argument `--accounts`. We want to catch all *successfull* transactions sent to one of the accounts from the list. In the demo we'll just look for them and log them but it might and probably should be extended based on your needs. --- ## How to use Before you proceed, make sure you have the following software installed: * [rustup](https://rustup.rs/) or Rust version that is mentioned in `rust-toolchain` file in the root of [nearcore](https://github.com/nearprotocol/nearcore) project. Clone this repository and open the project folder ```bash $ git clone git@github.com:khorolets/indexer-tx-watcher-example.git $ cd indexer-tx-watcher-example ``` ### Run ```bash $ cargo build --release $ ./target/release/indexer-tx-watcher-example --accounts mycoolcontract.near,myanothercoolcontract.near --block-height 88088521 testnet ``` Provide your contracts list after `--accounts` key separated with comma (`,`) **avoid spaces**, pick a fresher block height on https://explorer.testnet.near.org/ --- Find more docs about indexers on https://near-indexers.io
kherld-hussein_near_ticket
.github workflows codeql-analysis.yml Cargo.toml README.md SECURITY.md | build.sh deploy.sh dev-deploy.sh init-args.js rustfmt.toml src lib.rs
# NEAR Smart Event RSVP Contract RSVP just got easy... Create or get ticket to any event Project structure for writing smart contracts in Rust for NEAR Protocol # Required Software - Rust 1.58 + cargo - Node.js - NEAR CLI 3.1 # Author - Khalid Hussein <kherld11@gmail.com> [@kherldhussein](https://twitter.com/kherldhussein)
Learn-NEAR_starter--vue-and-tailwind
.eslintrc.js README.md babel.config.js package.json postcss.config.js public index.html src main.js tailwind.config.js
# vue-3 + tailwindui ## 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/).
kimchi9199_blockchain-homework
.gitpod.yml README.md contract Cargo.toml README.md neardev dev-account.env src lib.rs target .rustc_info.json release .fingerprint Inflector-34b3ed2ea6d72e66 lib-inflector.json ahash-c6faee060863811c build-script-build-script-build.json borsh-derive-d8c855ffd7f93343 lib-borsh-derive.json borsh-derive-internal-49d1eff69d2e3272 lib-borsh-derive-internal.json borsh-schema-derive-internal-44d6bb28b8a41dd7 lib-borsh-schema-derive-internal.json crunchy-65d3b1c0a0e86220 build-script-build-script-build.json near-sdk-macros-152b5091fa8a968e lib-near-sdk-macros.json proc-macro-crate-20d1b892ce56e1ff lib-proc-macro-crate.json proc-macro2-4efd15ea6f194149 build-script-build-script-build.json proc-macro2-7c45c5f273f79f73 lib-proc-macro2.json proc-macro2-82c06534cac70032 run-build-script-build-script-build.json quote-b4f3a83d583cfcbf lib-quote.json quote-d84025bcaea3aac1 run-build-script-build-script-build.json quote-e1ffceccfc17b52a build-script-build-script-build.json serde-0a65bc5dd186ef9c build-script-build-script-build.json serde-4a56a6e108aaafef lib-serde.json serde-676d6cce90a81f9e build-script-build-script-build.json serde-a035cff5e6832800 run-build-script-build-script-build.json serde_derive-2b2e3cf4deed344b build-script-build-script-build.json serde_derive-c17ef56d118aa091 run-build-script-build-script-build.json serde_derive-eda52f6d61f6f6c1 lib-serde_derive.json serde_json-bde9ae0a4b07a63c build-script-build-script-build.json syn-07196c0d57be7d7e build-script-build-script-build.json syn-0f66d4066780122c lib-syn.json syn-6ddee39b83cb17b3 run-build-script-build-script-build.json toml-d5d57096483c3118 lib-toml.json unicode-ident-bf1a645bac15dc35 lib-unicode-ident.json version_check-af49dc8d387d5ba8 lib-version_check.json wee_alloc-38f0ffe950509f8f build-script-build-script-build.json wasm32-unknown-unknown release .fingerprint ahash-92604981850cf802 run-build-script-build-script-build.json ahash-c93ed3cc59949b25 lib-ahash.json base64-2602488d6de3eacf lib-base64.json borsh-a1c3528e94e97ea7 lib-borsh.json bs58-2b855d1adba00fd2 lib-bs58.json byteorder-c3dfc6c7eea94d0f lib-byteorder.json cfg-if-660d9e104deb4443 lib-cfg-if.json crunchy-13ae59a1d174703c lib-crunchy.json crunchy-4787d78e6c3aada5 run-build-script-build-script-build.json hashbrown-d73f284706233ed6 lib-hashbrown.json hello_near-00ca379cccdf6430 lib-hello_near.json hex-f0709e5d4ee69ad7 lib-hex.json itoa-0568bfa47efd16f2 lib-itoa.json memory_units-376ed0a383ba5c97 lib-memory_units.json near-sdk-36d85ab3e34332f3 lib-near-sdk.json near-sys-f42a345412602ae4 lib-near-sys.json once_cell-f9dfe8588decd5aa lib-once_cell.json ryu-eb6ead6bb2c420fc lib-ryu.json serde-e8d1600e59df04e1 lib-serde.json serde-fb30c304d97991c3 run-build-script-build-script-build.json serde_json-292e9b0645b4fa0d lib-serde_json.json serde_json-6d2cc67ce2831e60 run-build-script-build-script-build.json static_assertions-0952d6fc09f9abd8 lib-static_assertions.json uint-42fa0b589bb8343f lib-uint.json wee_alloc-9da2a0138dc0dd17 lib-wee_alloc.json wee_alloc-a1be3ffafd2ab100 run-build-script-build-script-build.json build crunchy-4787d78e6c3aada5 out lib.rs wee_alloc-a1be3ffafd2ab100 out wee_alloc_static_array_backend_size_bytes.txt frontend App.js assets global.css logo-black.svg logo-white.svg dist index.bc0daea6.css index.html logo-black.4514ed42.svg logo-white.a7716062.svg 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
# blockchain-homework 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
nhtera_near-simple-vote
.gitpod.yml .postcssrc.json Notes.txt README.md babel.config.json contract Cargo.toml README.md compile.js src lib.rs 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 tailwind.config.js
near-simple-vote ================== 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 `near-simple-vote.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `near-simple-vote.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-simple-vote.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-simple-vote.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. Run the Demo =============== 1. Deploy contract and run web app ```bash yarn dev ``` 2. Export $CONTRACT_NAME variable ```bash source neardev/dev-account.env echo $CONTRACT_NAME ``` 3. Login with near ```bash near login ``` 3. Create posts ```bash near call $CONTRACT_NAME create_post '{"title": "Day la tieu de 1", "body": "Day la noi dung 1"}' --accountId=nhtera.testnet near call $CONTRACT_NAME create_post '{"title": "Day la tieu de 2", "body": "Day la noi dung 2"}' --accountId=$CONTRACT_NAME near call $CONTRACT_NAME create_post '{"title": "Day la tieu de 3", "body": "Day la noi dung 3"}' --accountId=nhtera.testnet ``` 4. Get posts ```bash near view $CONTRACT_NAME get_posts ``` 5. Get the post by id ```bash near view $CONTRACT_NAME get_post '{"post_id": 1}' ``` 6. Upvote ```bash near call $CONTRACT_NAME up_vote '{"post_id": 1}' --accountId=nhtera.testnet near call $CONTRACT_NAME up_vote '{"post_id": 2}' --accountId=nhtera.testnet ``` 7. Remove upvote ```bash near call $CONTRACT_NAME remove_upvote '{"post_id": 2}' --accountId=nhtera.testnet ``` 8. Downvote ```bash near call $CONTRACT_NAME down_vote '{"post_id": 2}' --accountId=nhtera.testnet ``` 9. Remove downvote ```bash near call $CONTRACT_NAME remove_downvote '{"post_id": 2}' --accountId=nhtera.testnet ``` 10. Remove post ```bash near call $CONTRACT_NAME remove_post '{"post_id": 2}' --accountId=nhtera.testnet near call $CONTRACT_NAME remove_post '{"post_id": 2}' --accountId=$CONTRACT_NAME ``` 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 near-simple-vote 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
mattlockyer_dolla
.eslintrc.js README.md contract Cargo.toml build.sh src lib.rs deploy mainnet.js testnet.js package.json src App.js Bill.js Bills.js Capture.js HelloMessage.js Printer.js index.html index.js state app.js near.js utils state.js test api.test.js test-utils.js utils config.js near-utils.js patch-config.js patch-prod.js
# Dolla > Cash rules everything around me, C.R.E.A.M., get the money, dollar dollar bill, y'all NEAR Money Printer Go Brrr! Print YUUUGE amounts of "NEAR CASH" bills and drop that STIMI! Receivers can claim to an existing account or use funds to set up a brand new NEAR Account! # React 17, Parcel with useContext and useReducer - Bundled with Parcel 2.0.1 - *Minimal all-in-one state management with async/await support* ## Getting Started: State Store & useContext >The following steps are already done, but 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/
gescobar129_project_relik
.gitpod.yml License.md Project Relik Assets Input Controls Character Controls.cs Pixel UI Scripts CardProfile.cs Editor CreateBaseMenu.cs CreateExtrasMenu.cs CreateRoundedMenu.cs CreateSquareMenu.cs CreateTextMenu.cs Range.cs Rotator.cs Singleton.cs UICard.cs UIClock.cs UIDeck.cs UIDialogueWindow.cs UIExperienceBar.cs UIFader.cs UIRescaler.cs UIStatBar.cs UITabbedWindow.cs UITooltip.cs UITypewriter.cs Scripts Character Character Behaviors CharacterCutScene.cs CharacterInput.cs CharacterMovement.cs CharacterPatrolAI.cs Inventory.cs Combat Attack.cs CharacterCombat.cs Killable.cs MoveSet.cs SwordWielder.cs Weapon.cs Magic MagicUser.cs SonicBehavior.cs Spell.cs Shadow Of Storms ShadowOfStormsAI.cs Shot Gunner ShotGunnerAI.cs Storm Samurai StormSamuraiAI.cs The Guide TheGuideCutScene.cs Cinematics Cut Scenes CutScene.cs Dialogue DialogueController.cs DialogueScript.cs DialogueWriter.cs LevelLoader.cs Timeline Character CharacterAnimatorBehavior.cs CharacterAnimatorClip.cs CharacterControlAsset.cs CharacterControlBehaviour.cs CharacterControlTrack.cs Dialog DialogueClipAsset.cs DialogueClipBehavior.cs DialogueTrack.cs Menus GameMenu.cs Network GameController.cs Props ParalaxBackground.cs SwordMount.cs Support CollisionChild.cs EventTrigger.cs VFX LinearGradient.cs TextMesh Pro Fonts LiberationSans - OFL.txt Resources LineBreaking Following Characters.txt LineBreaking Leading Characters.txt Sprites EmojiOne Attribution.txt EmojiOne.json Packages manifest.json packages-lock.json ProjectSettings ProjectVersion.txt SceneTemplateSettings.json README.md backend firebase.json functions .eslintrc.js package-lock.json package.json src .near-credentials testnet poopypants.testnet.json relik.testnet.json somethingsomethng.testnet.json index.ts types.ts tsconfig.dev.json tsconfig.json contract README.md babel.config.json build.sh deploy.sh deploy_nft.js neardev dev-account.env nftData.js package.json src GameMaster.ts GoldToken.ts approval.ts contract.ts enumeration.ts ft-helper.ts ft-metadata.ts ft.ts internal.ts metadata.ts mint.ts nft.ts nft_core.ts royalty.ts tsconfig.json firebase.json firestore.indexes.json frontend App.js LoginModal.js NavBar.js NftPage.js assets global.css logo-black.svg logo-white.svg dist index.3880a100.css index.bc0daea6.css index.html index.html index.js near-interface.js near-wallet.js package-lock.json package.json start.sh ui-components.js functions .eslintrc.js package-lock.json package.json src index.ts tsconfig.dev.json tsconfig.json integration-tests package.json src main.ava.ts 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. ```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>`. 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 # project_relik
LanNhi1997_contact-card
.gitpod.yml README.md babel.config.js contract Cargo.toml src lib.rs 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
contact-card ================== 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 `contact-card.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `contact-card.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 contact-card.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 = 'samnguyen.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
metaseed-project_template-contracts
GameManager Cargo.toml Readme.md src lib.rs Readme.md Registry Cargo.toml README.md instruction.md src lib.rs SimpleFT Cargo.toml README.md build.bat build.sh ft Cargo.toml src lib.rs rustfmt.toml test-contract-defi Cargo.toml src lib.rs tests sim main.rs no_macros.rs utils.rs with_macros.rs SimpleNFT Cargo.toml README.md build.bat build.sh flags.sh nft 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 examples Add FT asset.md Add NFT asset.md Creating NFT throw game manager.md Deploying NFT and 2 FT manually.md Full workflow.md Transfrom Asset.md Withdraw Asset.md
# Folder that contains wasm files Fungible Token (FT) =================== Example implementation of a [Fungible Token] contract which uses [near-contract-standards] and [simulation] tests. This is a contract-only example. [Fungible Token]: https://nomicon.io/Standards/FungibleToken/Core.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. 1. Make sure Rust is installed per the prerequisites in [`near-sdk-rs`](https://github.com/near/near-sdk-rs#pre-requisites) 2. Ensure `near-cli` is installed by running `near --version`. If not installed, install with: `npm install -g near-cli` ## Building To build run: ```bash ./build.sh ``` 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/fungible_token.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 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 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 '{"owner_id": "'$CONTRACT_NAME'", "total_supply": "1000000000000000", "metadata": { "spec": "ft-1.0.0", "name": "Example Token Name", "symbol": "EXLT", "decimals": 8 }}' --accountId $CONTRACT_NAME ``` To get the fungible token metadata: ```bash near view $CONTRACT_NAME ft_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 on [NEAR Wallet](https://wallet.near.org/). Switch to `mainnet`. You can skip this step to use `testnet` as a default network. export NEAR_ENV=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 your account id. In the below command, replace `MY_ACCOUNT_NAME` with the account name you just logged in with, including the `.near`: ID=MY_ACCOUNT_NAME You can tell if the environment variable is set correctly if your 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/fungible_token.wasm --accountId $ID FT contract should be initialized before usage. You can read more about metadata at ['nomicon.io'](https://nomicon.io/Standards/FungibleToken/Metadata.html#reference-level-explanation). Modify the parameters and create a token: near call $ID new '{"owner_id": "'$ID'", "total_supply": "1000000000000000", "metadata": { "spec": "ft-1.0.0", "name": "Example Token Name", "symbol": "EXLT", "decimals": 8 }}' --accountId $ID Get metadata: near view $ID ft_metadata Transfer Example --------------- Let's set up an account to transfer some tokens to. These account will be a sub-account of the NEAR account you logged in with. near create-account bob.$ID --masterAccount $ID --initialBalance 1 Add storage deposit for Bob's account: near call $ID storage_deposit '' --accountId bob.$ID --amount 0.00125 Check balance of Bob's account, it should be `0` for now: near view $ID ft_balance_of '{"account_id": "'bob.$ID'"}' Transfer tokens to Bob from the contract that minted these fungible tokens, exactly 1 yoctoNEAR of deposit should be attached: near call $ID ft_transfer '{"receiver_id": "'bob.$ID'", "amount": "19"}' --accountId $ID --amount 0.000000000000000000000001 Check the balance of Bob again with the command from before and it will now return `19`. ## Testing As with many Rust libraries and contracts, there are tests in the main fungible token implementation at `ft/src/lib.rs`. Additionally, this project has [simulation] tests in `tests/sim`. Simulation tests allow testing cross-contract calls, which is crucial to ensuring that the `ft_transfer_call` function works properly. These simulation tests are the reason this project has the file structure it does. Note that the root project has a `Cargo.toml` which sets it up as a workspace. `ft` and `test-contract-defi` are both small & focused contract projects, the latter only existing for simulation tests. The root project imports `near-sdk-sim` and tests interaction between these contracts. You can run all these tests with one command: ```bash cargo test ``` If you want to run only simulation tests, you can use `cargo test simulate`, since all the simulation tests include "simulate" in their names. ## 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. ## No AssemblyScript? [near-contract-standards] is currently Rust-only. We strongly suggest using this library to create your own Fungible Token contract to ensure it works as expected. Someday NEAR core or community contributors may provide a similar library for AssemblyScript, at which point this example will be updated to include both a Rust and AssemblyScript version. ## Contributing When making changes to the files in `ft` or `test-contract-defi`, remember to use `./build.sh` to compile all contracts and copy the output to the `res` folder. If you forget this, **the simulation tests will not use the latest versions**. Note that if the `rust-toolchain` file in this repository changes, please make sure to update the `.gitpod.Dockerfile` to explicitly specify using that as default as well. # Non-fungible Token (NFT) # Building this contract ```bash ./build.sh ``` # Testing this contract ```bash cargo test -- --nocapture ``` ### Quickest deploy Last deploy: dev-1640027402102-97310025672932 ```bash near dev-deploy --wasmFile res/non_fungible_token.wasm ``` ```bash source neardev/dev-account.env ``` ```bash echo $CONTRACT_NAME ``` ```bash near call $CONTRACT_NAME new_default_meta '{"owner_id": "'$CONTRACT_NAME'"}' --accountId $CONTRACT_NAME ``` ```bash near view $CONTRACT_NAME nft_metadata ``` ### Standard deploy near login ID=MY_ACCOUNT_NAME echo $ID near deploy --wasmFile res/non_fungible_token.wasm --accountId $ID 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 ### Mint near call $ID nft_mint '{"token_id": "0", "receiver_id": "'$ID'", "token_metadata": { "title": "1", "description": "2", "media": "3", "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. # Registry contract ## build RUSTFLAGS='-C link-arg=-s' cargo build --target wasm32-unknown-unknown --release
near_near-account-id-rs
.github workflows ci.yml dep-reqs.yml release-plz.yml CHANGELOG.md Cargo.toml README.md fuzz Cargo.toml README.md fuzz_targets borsh.rs serde.rs src account_id.rs account_id_ref.rs borsh.rs errors.rs lib.rs serde.rs test_data.rs validation.rs
## Fuzzing `near-account-id` ### Setup First, ensure [`cargo-fuzz`](https://github.com/rust-fuzz/cargo-fuzz) is installed: ```console cargo install cargo-fuzz ``` ### Execution Finally, there are two fuzzing targets available: one for [`serde`](https://github.com/serde-rs/serde) and another for [`borsh`](https://github.com/near/borsh-rs). You can run both tests with: ```console cd core/account-id/fuzz RUSTC_BOOTSTRAP=1 cargo fuzz run serde RUSTC_BOOTSTRAP=1 cargo fuzz run borsh ``` By default each fuzz test runs infinitely. To specify how many runs each test is allowed, you can use this: ```console RUSTC_BOOTSTRAP=1 cargo fuzz run serde -runs=1000000000 RUSTC_BOOTSTRAP=1 cargo fuzz run borsh -runs=1000000000 ``` # near-account-id This crate provides a type for representing a syntactically valid, unique account identifier on the [NEAR](https://near.org) network, according to the [NEAR Account ID](https://docs.near.org/concepts/basics/account#account-id-rules) rules. [![crates.io](https://img.shields.io/crates/v/near-account-id?label=latest)](https://crates.io/crates/near-account-id) [![Documentation](https://docs.rs/near-account-id/badge.svg)](https://docs.rs/near-account-id) ![MIT or Apache 2.0 licensed](https://img.shields.io/crates/l/near-account-id.svg) ## Usage ```rust use near_account_id::AccountId; let alice: AccountId = "alice.near".parse()?; assert!("ƒelicia.near".parse::<AccountId>().is_err()); // (ƒ is not f) ``` See the [docs](https://docs.rs/near-account-id) for more information. ## License Licensed under either of - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>) - MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>) at your option. ## Minimum Supported Rust Version (MSRV) 1.65 ## Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.
humanman_tic-tac-toe-contract
README.md as-pect.config.js asconfig.json assembly __tests__ as-pect.d.ts main.spec.ts as_types.d.ts main.ts model.ts tsconfig.json package.json script.sh src index.js
# Tic-Tac-Toe as a NEAR contract Video demo: [here](https://drive.google.com/file/d/1L0licLk5sSTQ21iwIp3QHHPRhX8hhfC3/view) Figma wireframes: [here](https://www.figma.com/file/reMNlA1lKaM1hFthWbwvrP/Untitled?node-id=3%3A117) ## Install dependencies ``` yarn ``` ## Build and Deploy the contract ``` npx asb near dev-deploy ./out/main.wasm # save the contract id in your clipboard and send it to player 2 ``` ## How to Play 1. Player one call function `createGame` passing the attached value, and send gameId to player 2 2. Player two call function `joinGame(gameId)` passing gameId that player one sent, also passing the attached value 3. Player one is the first to play, calling function `play(gameId, lin, col)` with gameId, lin, and col as argument 4. Player two continues the game 5. The plays continue until someone win, or the game gets draw 6. Players can view the board during the game, or after it end using function `viewBoard(gameId)` that gets gameId as parameter 7. When someone win, the attached deposit will be transfered to the wallet of the winner. ## Run the game **Create a game** ``` near call <contract-id> createGame --account_id <account-id> --amount 5 # save the game id in your clipboard and send it to your friend ``` **Join a game (player 2)** ``` near call <contract-id> joinGame '{"gameId": <game-id>}' --account_id <account-id> --amount 5 ``` **Play the game** ``` near call <contract-id> play '{"gameId": <game-id>, "lin": 2}' --account_id <account-id> ``` **View board** ``` near call <contract-id> viewBoard '{"gameId": <game-id>}' --account_id <account-id> ```
gacarg_ttt
Cargo.toml README.md build.sh neardev dev-account.env src lib.rs target .rustc_info.json debug .fingerprint Inflector-ddc8cd320e9ecbdc lib-inflector.json ahash-4793548205fc6e16 lib-ahash.json aho-corasick-c7bf49af5eeff1e0 lib-aho_corasick.json autocfg-78659797e16bd0af lib-autocfg.json base64-532e1d4e3f8b3bca lib-base64.json block-buffer-ced1f868af6cff16 lib-block-buffer.json block-padding-8c655c98abd14036 lib-block-padding.json borsh-d9c708aa57de67dd lib-borsh.json borsh-derive-ed210111c0859c69 lib-borsh-derive.json borsh-derive-internal-e8b6bc5242ab0601 lib-borsh-derive-internal.json borsh-schema-derive-internal-6c26b89c881ad178 lib-borsh-schema-derive-internal.json bs58-d00f0a21e99b7542 lib-bs58.json byteorder-96fecbe9838b7cbf lib-byteorder.json cfg-if-a492a4a4770a3c96 lib-cfg-if.json cfg-if-e583aedb5cd2095a lib-cfg-if.json convert_case-d2073549e3e391cf lib-convert_case.json cpufeatures-302687318f0f086c lib-cpufeatures.json derive_more-90f654eb39d79ec3 lib-derive_more.json digest-79e9babec06ca9d3 lib-digest.json game-232eff498445976d lib-game.json game-67fc8de1c405579d bin-game.json game-a6aed85a9e97995c lib-game.json game-cacda59c7f442def bin-game.json generic-array-7f58126a4b2e9a2d run-build-script-build-script-build.json generic-array-dd87576a1272026f lib-generic_array.json generic-array-f1fc724f78edcd7b build-script-build-script-build.json hashbrown-936cc4f7869537de lib-hashbrown.json hashbrown-a652fe8c935dd656 lib-hashbrown.json hex-76fd1105dc63d4b1 lib-hex.json indexmap-28f775141a10af4c run-build-script-build-script-build.json indexmap-47a411610c3c4813 build-script-build-script-build.json indexmap-c8d8e4704e496786 lib-indexmap.json itoa-da45ffbc6cd6998a lib-itoa.json keccak-a3cd35c88b4c9a55 lib-keccak.json lazy_static-58877db5eb397361 lib-lazy_static.json libc-1df5ae57be1d55be run-build-script-build-script-build.json libc-38670b58e0ed2787 lib-libc.json libc-87f12ec4821d8d8f build-script-build-script-build.json memchr-222126457eed97d2 lib-memchr.json memchr-42c08a071e449c9b run-build-script-build-script-build.json memchr-6d8d5416f812019c build-script-build-script-build.json memory_units-b386b75edc6a2eda lib-memory_units.json near-contract-standards-c7272bfe5eb5d9e8 lib-near-contract-standards.json near-primitives-core-b2d32d0491f7cf13 lib-near-primitives-core.json near-rpc-error-core-4b1746b7e270a4df lib-near-rpc-error-core.json near-rpc-error-macro-50fd7cec639a9ea9 lib-near-rpc-error-macro.json near-runtime-utils-09af150b83297da4 lib-near-runtime-utils.json near-sdk-5b4eb1c612da910d lib-near-sdk.json near-sdk-core-182fff99380a49b5 lib-near-sdk-core.json near-sdk-macros-52d3f7685a02bfd9 lib-near-sdk-macros.json near-vm-errors-ecb156c365fc783b lib-near-vm-errors.json near-vm-logic-3a7cb6e0b7541f60 lib-near-vm-logic.json num-bigint-1077da9f19ee12b7 lib-num-bigint.json num-bigint-56be1af92f9f03bc run-build-script-build-script-build.json num-bigint-831f735ebaa494b6 build-script-build-script-build.json num-integer-11b14cf76b016a17 build-script-build-script-build.json num-integer-4c04aa26b74955cc run-build-script-build-script-build.json num-integer-84f243de305ec654 lib-num-integer.json num-rational-3cb6426ea5fbff90 lib-num-rational.json num-rational-b129df133dabdd5a build-script-build-script-build.json num-rational-d795cf35c35ec469 run-build-script-build-script-build.json num-traits-1574c86f5679f9d2 build-script-build-script-build.json num-traits-c61f3abc1b34cf77 lib-num-traits.json num-traits-e6d3a9df4d61b06a run-build-script-build-script-build.json opaque-debug-6a72597e9d040162 lib-opaque-debug.json proc-macro-crate-b6c7f9f83bd43beb lib-proc-macro-crate.json proc-macro2-093f4200bea41105 run-build-script-build-script-build.json proc-macro2-315532268b359da3 lib-proc-macro2.json proc-macro2-cdac077fa61119b5 build-script-build-script-build.json quote-544508a8ac1b2e41 lib-quote.json regex-aeb8f9c212baced9 lib-regex.json regex-syntax-0c0b1523f348c60a lib-regex-syntax.json ryu-1455c2385bec766e lib-ryu.json serde-3cd456c00599f4d1 build-script-build-script-build.json serde-46bddd4e82bd2e7c run-build-script-build-script-build.json serde-caf71cd8c72e0f8c lib-serde.json serde_derive-3ffe6f480c514684 lib-serde_derive.json serde_derive-4aa0910215e7cb37 run-build-script-build-script-build.json serde_derive-b9d2e99038bdb354 build-script-build-script-build.json serde_json-3d1421fe4d9efd2e lib-serde_json.json serde_json-de467883e0b9d9a6 run-build-script-build-script-build.json serde_json-e8d37e37dacbb4ab build-script-build-script-build.json sha2-0b7e46e6eb5a5f90 lib-sha2.json sha3-f54c3c3fe6760c18 lib-sha3.json syn-2906b9a6e47be84d build-script-build-script-build.json syn-64a9420e74493a8e lib-syn.json syn-b0e32d381c30ca80 run-build-script-build-script-build.json toml-0bef4812852d8f1f lib-toml.json typenum-0e415f9d8657c3ff build-script-build-script-main.json typenum-2558951e7fbb9c06 run-build-script-build-script-main.json typenum-297756bdf33f8cfa lib-typenum.json unicode-xid-77f0f1add555399f lib-unicode-xid.json version_check-2508d31d21732147 lib-version_check.json wee_alloc-0c177cb749019d1e lib-wee_alloc.json wee_alloc-10aacd75df9a05fd run-build-script-build-script-build.json wee_alloc-5a7bd123bb190947 build-script-build-script-build.json build num-bigint-56be1af92f9f03bc out radix_bases.rs typenum-2558951e7fbb9c06 out consts.rs op.rs tests.rs wee_alloc-10aacd75df9a05fd out wee_alloc_static_array_backend_size_bytes.txt release .fingerprint Inflector-30be0246bde7531d lib-inflector.json Inflector-6fcfd294fc9080ca lib-inflector.json ahash-87643d0f6ecbe883 lib-ahash.json aho-corasick-2c3dc7d7a204598f lib-aho_corasick.json autocfg-7f6c46953752a0bf lib-autocfg.json autocfg-ac3344e7dcbbaebb lib-autocfg.json base64-66682f37c95084b0 lib-base64.json block-buffer-ab65ed25a1025907 lib-block-buffer.json block-padding-b8ec1fe70ba38527 lib-block-padding.json borsh-6ec714b4036d4bae lib-borsh.json borsh-derive-3a488ddd1b57e01e lib-borsh-derive.json borsh-derive-622646d22a2b0812 lib-borsh-derive.json borsh-derive-internal-a8339f82dee40018 lib-borsh-derive-internal.json borsh-derive-internal-bbd2f977a5221e8d lib-borsh-derive-internal.json borsh-schema-derive-internal-330ba6c5426d788a lib-borsh-schema-derive-internal.json borsh-schema-derive-internal-b5602246469cbbe8 lib-borsh-schema-derive-internal.json bs58-367973df18965e19 lib-bs58.json byteorder-72c11af8560f4479 lib-byteorder.json cfg-if-31b67991e9c2af6f lib-cfg-if.json cfg-if-84e662c384ea69ca lib-cfg-if.json convert_case-5775a092bd43a28b lib-convert_case.json convert_case-a758ffec73bdc4a1 lib-convert_case.json cpufeatures-208a24a12f4464e2 lib-cpufeatures.json derive_more-4363627bc4c77ce2 lib-derive_more.json derive_more-e3087b125d72eba3 lib-derive_more.json digest-49dc433f1a41b691 lib-digest.json game-a959d4ddf98a8e76 lib-game.json generic-array-866bf18ed090cc1e run-build-script-build-script-build.json generic-array-92d12a14acdcc40b lib-generic_array.json generic-array-ddb69644793aa5c9 build-script-build-script-build.json generic-array-e5dc4f0f0dfac50a build-script-build-script-build.json hashbrown-0b276666a310be10 lib-hashbrown.json hashbrown-2913f5ad32995a5a lib-hashbrown.json hashbrown-4cdb1a6d77e5624c lib-hashbrown.json hashbrown-62ba2ed3075e4202 lib-hashbrown.json hex-68fe1781c8984545 lib-hex.json indexmap-089d7dfc6c0d0a7b run-build-script-build-script-build.json indexmap-2ee8424bc23928b6 build-script-build-script-build.json indexmap-44026377b3b703e9 lib-indexmap.json indexmap-5d7e0742ae5a02b9 build-script-build-script-build.json indexmap-9752d2f5d582e754 run-build-script-build-script-build.json indexmap-b9242b16e0ec70ab lib-indexmap.json indexmap-cbb8e484a20f8504 run-build-script-build-script-build.json indexmap-ff3ce6e34a3a77f9 lib-indexmap.json itoa-5bd564414a58e619 lib-itoa.json itoa-953b67634e08cf6f lib-itoa.json itoa-d232153ba8022e96 lib-itoa.json keccak-cde2100a2c5a0370 lib-keccak.json lazy_static-a93e65d543d02ade lib-lazy_static.json libc-54b666d8cbf7495d run-build-script-build-script-build.json libc-7cd633030dd154f6 build-script-build-script-build.json libc-ede666bcc3cab912 lib-libc.json memchr-2e866541258b7e23 run-build-script-build-script-build.json memchr-4e9c0be85e785fae build-script-build-script-build.json memchr-caa8eff4609473c1 lib-memchr.json memchr-ec7f2f0b612ffdf2 build-script-build-script-build.json memory_units-99ab9fb5963aec6b lib-memory_units.json near-primitives-core-55f6dcdb318aa7cd lib-near-primitives-core.json near-rpc-error-core-39e81a6c47b27ede lib-near-rpc-error-core.json near-rpc-error-core-4b67620636dcf2b7 lib-near-rpc-error-core.json near-rpc-error-macro-abb6eeee12d59afd lib-near-rpc-error-macro.json near-rpc-error-macro-c6d2784cf243ff36 lib-near-rpc-error-macro.json near-runtime-utils-1dd4a6fe902b2f40 lib-near-runtime-utils.json near-sdk-54c62d9940d9f45b lib-near-sdk.json near-sdk-core-0af30b1fbc16dcb8 lib-near-sdk-core.json near-sdk-core-394a1d9b306e947e lib-near-sdk-core.json near-sdk-macros-15ea9a42a00928e4 lib-near-sdk-macros.json near-sdk-macros-c5457524d6545602 lib-near-sdk-macros.json near-vm-errors-ef276ca3b5fc39eb lib-near-vm-errors.json near-vm-logic-54b8237d6a0d8115 lib-near-vm-logic.json num-bigint-3d586c36d4eaa2ac run-build-script-build-script-build.json num-bigint-88c74052a35740e9 build-script-build-script-build.json num-bigint-b39267b1f22ca749 lib-num-bigint.json num-bigint-c0afe39b45421275 build-script-build-script-build.json num-integer-1972d87fc97a7cfe build-script-build-script-build.json num-integer-4a339753208ee3d4 build-script-build-script-build.json num-integer-582a1d5783a6ebf8 run-build-script-build-script-build.json num-integer-c28c9e6e758e7c87 lib-num-integer.json num-rational-2c6681cdc5399613 lib-num-rational.json num-rational-8e80099f16659f37 build-script-build-script-build.json num-rational-a24f4818ea462682 run-build-script-build-script-build.json num-rational-a3c2d5496d1f301d build-script-build-script-build.json num-traits-a5d7e89ba311193e build-script-build-script-build.json num-traits-c4f0d300c45cf592 lib-num-traits.json num-traits-d52a07563a8f71c9 build-script-build-script-build.json num-traits-f78c43d749068aec run-build-script-build-script-build.json opaque-debug-1bd225529302b1f0 lib-opaque-debug.json proc-macro-crate-84586395d4962a7b lib-proc-macro-crate.json proc-macro-crate-bbee82d427af5929 lib-proc-macro-crate.json proc-macro2-04c896e3fe1ed9a0 lib-proc-macro2.json proc-macro2-1b8555845a07684c build-script-build-script-build.json proc-macro2-94192444f4cd6da4 build-script-build-script-build.json proc-macro2-c0f318a13da6a941 lib-proc-macro2.json proc-macro2-d650d0e4d549e212 run-build-script-build-script-build.json proc-macro2-e08c29d1fa4b8269 run-build-script-build-script-build.json quote-07a95b0c1d6e3788 lib-quote.json quote-e1281520883914c9 lib-quote.json regex-2d43836086f4d8f1 lib-regex.json regex-syntax-fa358f41e2acf7f2 lib-regex-syntax.json ryu-35fa4a364cc9aa49 lib-ryu.json ryu-4da923d0ac4e1b95 lib-ryu.json ryu-5e29dee970cd65aa lib-ryu.json serde-1b586ccd88a25c4a lib-serde.json serde-44cc2d7e89ba1d24 build-script-build-script-build.json serde-6d9b3902faa0ed34 build-script-build-script-build.json serde-70a1d36c0baa1d7d run-build-script-build-script-build.json serde-7911892043e36ef9 lib-serde.json serde-8bea8ef82e773582 run-build-script-build-script-build.json serde-903ad42642da12dd lib-serde.json serde-b3be1ae4e3fd27f6 run-build-script-build-script-build.json serde_derive-3bcf175dffd38be2 build-script-build-script-build.json serde_derive-6d51620d55e5fedf lib-serde_derive.json serde_derive-7aeba97ded136725 build-script-build-script-build.json serde_derive-96eb023784520a6e run-build-script-build-script-build.json serde_derive-cf2e9b4aa075989b run-build-script-build-script-build.json serde_derive-ee396ae35859d6de lib-serde_derive.json serde_json-0d2d8201049b9a6d build-script-build-script-build.json serde_json-23494b77a359f301 lib-serde_json.json serde_json-6967a991dd550dac lib-serde_json.json serde_json-a500ab8cc6b6cb3b run-build-script-build-script-build.json serde_json-a95fa2c249e49f10 run-build-script-build-script-build.json serde_json-acf92eab5dfba5e9 run-build-script-build-script-build.json serde_json-b60fdfd467df6255 lib-serde_json.json serde_json-ead415fb750b24fa build-script-build-script-build.json sha2-9d3238d0326af67b lib-sha2.json sha3-402f167e0562033b lib-sha3.json syn-41767ba61613ed24 build-script-build-script-build.json syn-7c28458a167e305e build-script-build-script-build.json syn-995caf2970706bdf lib-syn.json syn-b9d01351c70b4bd3 run-build-script-build-script-build.json syn-d972d274d79c7cbb lib-syn.json syn-f0f3fb11e27c9a29 run-build-script-build-script-build.json toml-0f81d21df707f625 lib-toml.json toml-1fa6bf35ead8ab69 lib-toml.json typenum-26e06e553c9b6c0d build-script-build-script-main.json typenum-8f5df93c2c37da71 build-script-build-script-main.json typenum-c11c6a0b13821c10 lib-typenum.json typenum-c8cfa9ce228ab8a0 run-build-script-build-script-main.json unicode-xid-1b07bb0d45ef7ee8 lib-unicode-xid.json unicode-xid-c4fbaf8ae18bfb44 lib-unicode-xid.json version_check-0b64899a709c8065 lib-version_check.json version_check-91aa0c3279b236b7 lib-version_check.json wee_alloc-36902ac9acf7bcca build-script-build-script-build.json wee_alloc-60b883309d20fabb build-script-build-script-build.json wee_alloc-a6130cb79f885ebd lib-wee_alloc.json wee_alloc-dede7b12ad6c411a run-build-script-build-script-build.json build num-bigint-3d586c36d4eaa2ac out radix_bases.rs typenum-c8cfa9ce228ab8a0 out consts.rs op.rs tests.rs wee_alloc-dede7b12ad6c411a out wee_alloc_static_array_backend_size_bytes.txt wasm32-unknown-unknown release .fingerprint ahash-5578102e25df41d4 lib-ahash.json ahash-71b6e0a781083774 lib-ahash.json aho-corasick-374f4c0479d72d48 lib-aho_corasick.json aho-corasick-4a117c2d4a75b17e lib-aho_corasick.json base64-72c7b3a52647c1af lib-base64.json base64-8e6cb4e91336ee84 lib-base64.json block-buffer-1d0a196efc1a22c1 lib-block-buffer.json block-buffer-ddf29ce737c1e1dd lib-block-buffer.json block-padding-2d79e2c830e313f0 lib-block-padding.json block-padding-d11c809f941d6886 lib-block-padding.json borsh-83b18616dadc92b5 lib-borsh.json borsh-b4497be3f3086c21 lib-borsh.json bs58-cca7a1d66803629b lib-bs58.json bs58-f55bcb5c365ffe58 lib-bs58.json byteorder-627d418bde4aa5b4 lib-byteorder.json byteorder-69f62818be606a8c lib-byteorder.json cfg-if-19e8f69d54e8f7d5 lib-cfg-if.json cfg-if-627757f02a83993b lib-cfg-if.json cfg-if-8a589cdea88272df lib-cfg-if.json cfg-if-b45b261c0388868c lib-cfg-if.json digest-0579c846f94f71a5 lib-digest.json digest-9abb83fd80251e41 lib-digest.json game-1287409cdf53331b lib-game.json game-1cb7bf40fc742b18 bin-game.json game-5bd00385cc1336a4 bin-game.json game-fb245183650036e5 lib-game.json generic-array-178061648738fbec lib-generic_array.json generic-array-75307170e24b8ed1 lib-generic_array.json generic-array-a382b2f6b9a6e194 run-build-script-build-script-build.json generic-array-b7c60b3dab16d1b9 run-build-script-build-script-build.json hashbrown-2e42789d73ad2a67 lib-hashbrown.json hashbrown-aafe2bbdaf3681d6 lib-hashbrown.json hashbrown-ce3a84256582d418 lib-hashbrown.json hashbrown-d84522516646c8e9 lib-hashbrown.json hex-8d3a2fa5fbacb1cd lib-hex.json hex-f0b7d9945e3314b4 lib-hex.json indexmap-31f80ce3f0e31357 lib-indexmap.json indexmap-37cddf9037715b8c run-build-script-build-script-build.json indexmap-aa5a00d192ddfae8 lib-indexmap.json indexmap-f7fa917a9b95e429 run-build-script-build-script-build.json itoa-2745ba28eeb183ea lib-itoa.json itoa-78ca0ec3360b4ec5 lib-itoa.json keccak-8539910cd8f0b9ea lib-keccak.json keccak-fee3dfd94bcdb646 lib-keccak.json lazy_static-634cb55e0005e795 lib-lazy_static.json lazy_static-8f08e62ce8ded302 lib-lazy_static.json memchr-3c16d0e13b407993 lib-memchr.json memchr-3d69fcd5fe1a03dc run-build-script-build-script-build.json memchr-44f476e18cbb7b98 run-build-script-build-script-build.json memchr-bf437bc82855b9e5 lib-memchr.json memory_units-8d158d08f3ffd683 lib-memory_units.json memory_units-f55d3cf4643cc49e lib-memory_units.json near-contract-standards-53a0af943cabb0af lib-near-contract-standards.json near-primitives-core-89790c06f0ab88b9 lib-near-primitives-core.json near-primitives-core-a65699b77ed5ef72 lib-near-primitives-core.json near-runtime-utils-0a881fb4baa0ad2a lib-near-runtime-utils.json near-runtime-utils-9a85d51c35049c72 lib-near-runtime-utils.json near-sdk-60d1175d1b6232f2 lib-near-sdk.json near-sdk-e2d30a993e84ee12 lib-near-sdk.json near-vm-errors-0431e2a1d68ef530 lib-near-vm-errors.json near-vm-errors-f87580300522cff7 lib-near-vm-errors.json near-vm-logic-a5af5a8da9f6c43a lib-near-vm-logic.json near-vm-logic-dda649d8b8513483 lib-near-vm-logic.json num-bigint-1e6a7bfadcc60af6 run-build-script-build-script-build.json num-bigint-40fd6e9bae23a35c run-build-script-build-script-build.json num-bigint-78ce528169846341 lib-num-bigint.json num-bigint-b23ad81978fe6ac1 lib-num-bigint.json num-integer-337a48a57abbf3ad run-build-script-build-script-build.json num-integer-3ea626d6fffe6692 lib-num-integer.json num-integer-94fdfc605093ef8a run-build-script-build-script-build.json num-integer-aef2d8559caa63ef lib-num-integer.json num-rational-1a69bcf77a29204e lib-num-rational.json num-rational-23be065877b31e05 lib-num-rational.json num-rational-49bcbfb9708f98a3 run-build-script-build-script-build.json num-rational-d13923650dd7e6f1 run-build-script-build-script-build.json num-traits-31211be3646f7f86 run-build-script-build-script-build.json num-traits-b501e6f49b15d109 lib-num-traits.json num-traits-bad65f4744173462 lib-num-traits.json num-traits-d72a9286772aef32 run-build-script-build-script-build.json opaque-debug-4909b5692f251494 lib-opaque-debug.json opaque-debug-5187edc3a08589ea lib-opaque-debug.json regex-92f18b0e59f9b772 lib-regex.json regex-dc147b3ae749b5cd lib-regex.json regex-syntax-90d8b521db702817 lib-regex-syntax.json regex-syntax-e56b765992052ed6 lib-regex-syntax.json ryu-aaf7593ccd271162 lib-ryu.json ryu-c83d1a0a76ea3327 lib-ryu.json serde-a1ae861aee622cf9 lib-serde.json serde-d8e6b5535f65f6f0 run-build-script-build-script-build.json serde-daa64ff9439f2b3b lib-serde.json serde-e95e36156cd771b8 run-build-script-build-script-build.json serde_json-2c25d9d2f1851c1d lib-serde_json.json serde_json-2f9dab3c2f36aa11 run-build-script-build-script-build.json serde_json-3a44feae76ccb170 lib-serde_json.json serde_json-a72efc6872b53f8a run-build-script-build-script-build.json sha2-62b0abdaaa25a867 lib-sha2.json sha2-90ce3ea54ac39b21 lib-sha2.json sha3-443171575fc07ae4 lib-sha3.json sha3-ed57755adbd86190 lib-sha3.json typenum-25025e4c8bf00c91 run-build-script-build-script-main.json typenum-3e8d5c072f867553 lib-typenum.json typenum-43177383c0ccdbf4 lib-typenum.json typenum-8863d1a56df1f073 run-build-script-build-script-main.json wee_alloc-0c1839b957405eff run-build-script-build-script-build.json wee_alloc-24fdd5f51675a352 run-build-script-build-script-build.json wee_alloc-2fb7c58d376e09ac lib-wee_alloc.json wee_alloc-6971820eb4ff5aa1 lib-wee_alloc.json build num-bigint-1e6a7bfadcc60af6 out radix_bases.rs num-bigint-40fd6e9bae23a35c out radix_bases.rs typenum-25025e4c8bf00c91 out consts.rs op.rs tests.rs typenum-8863d1a56df1f073 out consts.rs op.rs tests.rs wee_alloc-0c1839b957405eff out wee_alloc_static_array_backend_size_bytes.txt wee_alloc-24fdd5f51675a352 out wee_alloc_static_array_backend_size_bytes.txt tictactoe.rs target .rustc_info.json debug .fingerprint Inflector-ddc8cd320e9ecbdc lib-inflector.json ahash-4793548205fc6e16 lib-ahash.json ahash-b2ece663896286cd lib-ahash.json aho-corasick-8e00a682cf7e7a79 lib-aho_corasick.json aho-corasick-c7bf49af5eeff1e0 lib-aho_corasick.json autocfg-78659797e16bd0af lib-autocfg.json base64-532e1d4e3f8b3bca lib-base64.json base64-9ca735639fb88adc lib-base64.json block-buffer-3e75433065307328 lib-block-buffer.json block-buffer-ced1f868af6cff16 lib-block-buffer.json block-padding-8c655c98abd14036 lib-block-padding.json block-padding-f6bc54d2c929d982 lib-block-padding.json borsh-16d0a73912b82b66 lib-borsh.json borsh-d9c708aa57de67dd lib-borsh.json borsh-derive-ed210111c0859c69 lib-borsh-derive.json borsh-derive-internal-e8b6bc5242ab0601 lib-borsh-derive-internal.json borsh-schema-derive-internal-6c26b89c881ad178 lib-borsh-schema-derive-internal.json bs58-cee8dc4be4ebae45 lib-bs58.json bs58-d00f0a21e99b7542 lib-bs58.json byteorder-96fecbe9838b7cbf lib-byteorder.json byteorder-d017619092b1f519 lib-byteorder.json cfg-if-5d8c8081598c8a37 lib-cfg-if.json cfg-if-973d0ba0190a5742 lib-cfg-if.json cfg-if-a492a4a4770a3c96 lib-cfg-if.json cfg-if-e583aedb5cd2095a lib-cfg-if.json convert_case-d2073549e3e391cf lib-convert_case.json cpufeatures-1737ad460561c86a lib-cpufeatures.json cpufeatures-302687318f0f086c lib-cpufeatures.json derive_more-90f654eb39d79ec3 lib-derive_more.json digest-48ff9c8decc6df3e lib-digest.json digest-79e9babec06ca9d3 lib-digest.json game-111ab4a271e9ad03 lib-game.json game-1b80ca89219fdcd7 test-bin-game.json game-5e63844b31cf4dae test-lib-game.json game-8264eb078c5a7f1c test-bin-game.json game-9b9d5a1365753bd1 test-lib-game.json game-a6aed85a9e97995c lib-game.json game-cacda59c7f442def bin-game.json game-fffbb3b90a9064fc bin-game.json generic-array-7f58126a4b2e9a2d run-build-script-build-script-build.json generic-array-b744d1335697e3ba lib-generic_array.json generic-array-dd87576a1272026f lib-generic_array.json generic-array-f1fc724f78edcd7b build-script-build-script-build.json hashbrown-46f4261a99f25687 lib-hashbrown.json hashbrown-542467afaac898b7 lib-hashbrown.json hashbrown-936cc4f7869537de lib-hashbrown.json hashbrown-a652fe8c935dd656 lib-hashbrown.json hex-76fd1105dc63d4b1 lib-hex.json hex-cbb982913a87ca4e lib-hex.json indexmap-28f775141a10af4c run-build-script-build-script-build.json indexmap-47a411610c3c4813 build-script-build-script-build.json indexmap-c8d8e4704e496786 lib-indexmap.json indexmap-d52474728c17e64e lib-indexmap.json itoa-da45ffbc6cd6998a lib-itoa.json itoa-fc98bdcf20621911 lib-itoa.json keccak-3457b02d1b50b15d lib-keccak.json keccak-a3cd35c88b4c9a55 lib-keccak.json lazy_static-58877db5eb397361 lib-lazy_static.json lazy_static-ee05c660a6e514a7 lib-lazy_static.json libc-1df5ae57be1d55be run-build-script-build-script-build.json libc-38670b58e0ed2787 lib-libc.json libc-67619badfe333025 lib-libc.json libc-87f12ec4821d8d8f build-script-build-script-build.json memchr-222126457eed97d2 lib-memchr.json memchr-42c08a071e449c9b run-build-script-build-script-build.json memchr-6d8d5416f812019c build-script-build-script-build.json memchr-7e5c4d99887e89d1 lib-memchr.json memory_units-b386b75edc6a2eda lib-memory_units.json memory_units-d27ac2eb6df8fbe6 lib-memory_units.json near-contract-standards-66833b9d98847edf lib-near-contract-standards.json near-contract-standards-c7272bfe5eb5d9e8 lib-near-contract-standards.json near-primitives-core-b2d32d0491f7cf13 lib-near-primitives-core.json near-primitives-core-e1ee738d71de3722 lib-near-primitives-core.json near-rpc-error-core-4b1746b7e270a4df lib-near-rpc-error-core.json near-rpc-error-macro-50fd7cec639a9ea9 lib-near-rpc-error-macro.json near-runtime-utils-09af150b83297da4 lib-near-runtime-utils.json near-runtime-utils-8be915aa5f87353c lib-near-runtime-utils.json near-sdk-5b4eb1c612da910d lib-near-sdk.json near-sdk-c9cc17846d760e74 lib-near-sdk.json near-sdk-core-182fff99380a49b5 lib-near-sdk-core.json near-sdk-macros-52d3f7685a02bfd9 lib-near-sdk-macros.json near-vm-errors-8abc2e8bb82098dc lib-near-vm-errors.json near-vm-errors-ecb156c365fc783b lib-near-vm-errors.json near-vm-logic-17bc511167968d09 lib-near-vm-logic.json near-vm-logic-3a7cb6e0b7541f60 lib-near-vm-logic.json num-bigint-1077da9f19ee12b7 lib-num-bigint.json num-bigint-56be1af92f9f03bc run-build-script-build-script-build.json num-bigint-831f735ebaa494b6 build-script-build-script-build.json num-bigint-ed4b5f8166a9ad15 lib-num-bigint.json num-integer-11b14cf76b016a17 build-script-build-script-build.json num-integer-2bc6fc0467eaff6f lib-num-integer.json num-integer-4c04aa26b74955cc run-build-script-build-script-build.json num-integer-84f243de305ec654 lib-num-integer.json num-rational-3cb6426ea5fbff90 lib-num-rational.json num-rational-b129df133dabdd5a build-script-build-script-build.json num-rational-c40c2765a0ddc934 lib-num-rational.json num-rational-d795cf35c35ec469 run-build-script-build-script-build.json num-traits-1574c86f5679f9d2 build-script-build-script-build.json num-traits-6b11cd03700f3c64 lib-num-traits.json num-traits-c61f3abc1b34cf77 lib-num-traits.json num-traits-e6d3a9df4d61b06a run-build-script-build-script-build.json opaque-debug-6a72597e9d040162 lib-opaque-debug.json opaque-debug-6cfa0f61d3dc752f lib-opaque-debug.json proc-macro-crate-b6c7f9f83bd43beb lib-proc-macro-crate.json proc-macro2-093f4200bea41105 run-build-script-build-script-build.json proc-macro2-315532268b359da3 lib-proc-macro2.json proc-macro2-cdac077fa61119b5 build-script-build-script-build.json quote-544508a8ac1b2e41 lib-quote.json regex-913d40f619daa49e lib-regex.json regex-aeb8f9c212baced9 lib-regex.json regex-syntax-0c0b1523f348c60a lib-regex-syntax.json regex-syntax-44670c716cfdde58 lib-regex-syntax.json ryu-1455c2385bec766e lib-ryu.json ryu-c0e50fa5b38a6d23 lib-ryu.json serde-3cd456c00599f4d1 build-script-build-script-build.json serde-46bddd4e82bd2e7c run-build-script-build-script-build.json serde-476b89b190d709f2 lib-serde.json serde-caf71cd8c72e0f8c lib-serde.json serde_derive-3ffe6f480c514684 lib-serde_derive.json serde_derive-4aa0910215e7cb37 run-build-script-build-script-build.json serde_derive-b9d2e99038bdb354 build-script-build-script-build.json serde_json-3d1421fe4d9efd2e lib-serde_json.json serde_json-47df357f123e975e lib-serde_json.json serde_json-de467883e0b9d9a6 run-build-script-build-script-build.json serde_json-e8d37e37dacbb4ab build-script-build-script-build.json sha2-0b7e46e6eb5a5f90 lib-sha2.json sha2-aac7692170772a08 lib-sha2.json sha3-3c4c09fdee4c4e78 lib-sha3.json sha3-f54c3c3fe6760c18 lib-sha3.json syn-2906b9a6e47be84d build-script-build-script-build.json syn-64a9420e74493a8e lib-syn.json syn-b0e32d381c30ca80 run-build-script-build-script-build.json toml-0bef4812852d8f1f lib-toml.json typenum-0e415f9d8657c3ff build-script-build-script-main.json typenum-2558951e7fbb9c06 run-build-script-build-script-main.json typenum-297756bdf33f8cfa lib-typenum.json typenum-c06131d78650e07c lib-typenum.json unicode-xid-77f0f1add555399f lib-unicode-xid.json version_check-2508d31d21732147 lib-version_check.json wee_alloc-0c177cb749019d1e lib-wee_alloc.json wee_alloc-10aacd75df9a05fd run-build-script-build-script-build.json wee_alloc-5a7bd123bb190947 build-script-build-script-build.json wee_alloc-f66c17208170ffdb lib-wee_alloc.json build num-bigint-56be1af92f9f03bc out radix_bases.rs typenum-2558951e7fbb9c06 out consts.rs op.rs tests.rs wee_alloc-10aacd75df9a05fd out wee_alloc_static_array_backend_size_bytes.txt
# ttt Unfinished Tic tac toe with save in Near
idea404_xcc-view-test
.github workflows tests.yml README.md contract index.js package-lock.json package.json test main.ava.js
# NEAR Cross Contract Calls with View or Change Methods This repo shows how cross contract calls behave when placed within view or change methods. Specifically, with the current syntax for [NEAR SDK JS](https://github.com/near/near-sdk-js), every cross contract call becomes a function call. Function calls can not be called from within view methods, so by extension, we may not perform cross contract calls from within view methods. ### Requirements - [Node.js](https://nodejs.org/en/download/) >= 16.0.0 ### Running the tests 1. Clone this repo 2. Run `npm install` 3. Run `npm run build` 4. Run `npm test`
microchipgnu_bonsai
.devcontainer devcontainer.json .eslintrc.json .github workflows promote-develop-to-main.yml .idea jsLibraryMappings.xml modules.xml prettier.xml vcs.xml README.md next.config.js package.json 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 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
# NEAR Discovery (BOS) ## 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 git@github.com: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-examples_collection-examples-rs
.eslintrc.yml README.md getData.js package.json results example-results get-data get_lookup_map_results.js get_tree_map_results.js get_unordered_map_results.js index.html set-data add_lookup_map_results.js add_tree_map_results.js add_unordered_map_results.js index.html user-results get-data index.html set-data index.html services data.js getData-example-charts.js getData-user-charts.js setData-example-charts.js setData-user-charts.js utils.js setData.js smart-contract lib.rs
# NEAR Rust Collection Examples using `near-sdk-rs` This repository serves to demonstrate differences in gas consumption when storing or retrieving data from the NEAR blockchain using [Rust](https://www.rust-lang.org/) collection methods found in [`near-sdk-rs`](https://github.com/near/near-sdk-rs). After running `setData.js` or `getData.js`, results will be populated in a chart and automatically displayed upon completion. ![example chart screenshot](assets/example_results_screenshot.png) ## Prerequisites - Current version of [Node.js](https://nodejs.org/). >=v14.0.0 - [NEAR `testnet` account](https://wallet.testnet.near.org/) - [`near-cli`](https://docs.near.org/tools/near-cli#setup) - _(command line interface to interact with the NEAR blockchain)_ - [yarn](https://classic.yarnpkg.com/en/docs/install) - _(dependency management tool)_ ## Setup 1. Install dependencies by running: ```bash yarn ``` 2. Store your access keys locally If you do not already have keys stored locally, run: ```bash near login ``` You will be redirected to [NEAR `testnet` wallet](https://wallet.testnet.near.org/) to authorize `near cli`. Once permission is granted, you will have a full access key stored as a `.json` file in `~/.near-credentials`. For non macOS / Linux users, this "hidden" folder is located in the root of your HOME directory. 3. Set an environment variable for `NEAR_ACCOUNT` Set your account name as environment variable to use in these examples. Create one in your `bash` or `zsh` profile (recommended) or run the following in your terminal. _(replacing `example.testnet` with your account that you have full access keys stored locally)_ ```bash export NEAR_ACCOUNT=example.testnet ``` If you choose to run this command in your terminal rather than adding it to your `bash` or `zsh` profile **Windows users:** Please look into using `set` instead of `export`, surrounding the environment variable in `%` instead of beginning with `$`. 4. Create a subaccount to deploy a smart contract to For this example you will deploy a smart contract to a [subaccount](https://docs.near.org/concepts/basics/account#subaccounts). We will do this so we can easily delete and recreate an account to reset _all_ of the data stored in the contract. To create this subaccount run: ```bash yarn create-account ``` 5. Deploy your smart contract A `.wasm` file is already compiled for you and ready to deploy. To do so, simply run: ```bash yarn deploy ``` You can view the source code of this deployed contract by navigating to `smart-contract/lib.rs` ### Storing Data Open `setData.js` in your local IDE and select the number of records you would like to add to the three collection examples. You can do so by changing the number passed to `getDataSet()` at the bottom of this file. To run the script, type the following in your terminal: ```bash node setData.js ``` The Node script will start to run and console log the `gas_burnt`, `responseTime`, and current key of the data being stored. Once complete, a chart will automatically launch showing you your results. At anytime you can view the chart progress by manually running: ```bash yarn setCharts ``` ### Retrieving Data Open `getData.js` and make sure the number passed to `getData()` is the same number of values you just added. Once verified, run: ```bash node getData.js ``` Again, the script will start running returning `gas_burnt`, `responseTime` and the current key of the data retrieved. Once complete, a chart will automatically launch showing you your results. At anytime you can view the chart progress by manually running: ```bash yarn getCharts ``` ### View Example Results This process can take some time depending on the amount of records you decide to add. If you would like to see what some example results look like right away, run the following to see example `setData()` results: ```bash yarn exSetCharts ``` For example `getData()` results, run: ```bash yarn exGetCharts ``` ### Clearing Results Once you run `setData.js` or `getData.js` your results will automatically clear and begin re-writing. If you would like to manually reset the user results data run: ```bash yarn clear ``` **Note:** that this is just to clear the results from your contract calls, not the data stored in the contract itself. To clear the data in the contract, you can delete & recreate the account then redeploy the contract by running: ```bash yarn rebuild ``` ### Using Your Own data You can use your own dataset with `setData.js` and `getData.js`. Just pass these functions an array of objects in the same format as `services/data.js` _(`key` and `value` must be strings)_ ```js [ { key: "YOUR_KEY", value: "YOUR_VALUE", }, ]; ``` ### Advisory Sometimes, with large data amounts you may run into `BadGateway` or `Transaction has expired`. If this happens try lowering the number of values you are entering or simply try re-running the script. You may need to reset the data already stored by rebuilding the contract which can be performed by running: ```bash yarn rebuild ``` Please let us know if you continue to run into this issue on [Discord](http://near.chat) or [Telegram](https://t.me/cryptonear) :) Happy coding! 🚀
letangphuquy_ltpq-hi-near
Cargo.toml Makefile.toml rust-toolchain.toml rustfmt.toml src lib.rs
near-x_near-developers
README.md
# near-developers Welcome to the NEAR Developer Community
Laser420_DAO_Managed_Vault
.github workflows test.yml README.md broadcast DeployGnosisChiado.s.sol 100 run-1687707807.json run-1687707814.json run-latest.json 10200 run-1687676494.json run-1687676751.json run-1687678043.json run-1687696538.json run-latest.json DeployLinea.s.sol 59140 run-1687676020.json run-1687679969.json run-1687681121.json run-latest.json DeployZkevm.s.sol 1101 run-1687677984.json run-1687679080.json run-latest.json DeployZkevmTestnet.s.sol 1442 run-1687676875.json run-1687679384.json run-1687681432.json run-1687681439.json run-1687682057.json run-1687682063.json run-1687686324.json run-1687686330.json run-1687686331.json run-latest.json council-kit .vscode settings.json CONTRIBUTORS.md README.md apps council-sdk-starter .prettierrc.js README.md package.json src addresses ElementMainnetAddressList.json elementAddresses.ts index.ts provider.ts scripts createProposal.ts executeProposal.ts getGSCMembers.ts getProposalResults.ts tsconfig.json council-ui .eslintrc.js .prettierrc.js README.md next-env.d.ts next.config.js package.json postcss.config.js src @types @metamask jazzicon.d.ts clients council.ts reactQuery.ts wagmi.ts config CouncilConfig.ts council.config.ts goerli.ts localhost.ts mainnet.ts dates formatTimeLeft.ts ens getBulkEnsRecords.ts etherscan makeEtherscanAddressURL.ts makeEtherscanTransactionURL.ts proposals getProposalStatus.ts provider.ts routes.ts styles globals.css ui base formatting formatAddress.ts formatBalance.ts useDisplayName.ts imgSrc.ts sorting types.ts utils asyncFilter.ts council CouncilClientContext.ts useCouncil.ts ens useBulkEnsRecords.ts network useChainId.ts proposals hooks useFilterVotesByGSCOnlyEffect.ts useVoteResults.ts tooltips.ts types.ts vaults gscVault useGSCMemberAddresses.ts useGSCStatus.ts useIsGSCMember.ts useJoinGSC.ts useKickGSCMember.ts hooks useDelegatesByVault.ts useVaultVotingPower.ts useVotingPower.ts useVotingPowerByVault.ts lockingVault hooks useApprove.ts useChangeDelegate.ts useDelegate.ts useDeposit.ts useWithdraw.ts tooltips.ts vestingVault hooks useChangeDelegate.ts useDelegate.ts useGrantClaim.ts voters hooks useVoterStats.ts useVotersSearch.ts types.ts voting hooks useGSCVote.ts useVote.ts vaults gscVault getGSCMembers.ts getGSCStatus.ts getIsGSCEligible.ts types.ts vaults.ts wallet connectors.ts tailwind.config.js tsconfig.json landing-page index.html package.json src assets corner-lines-left.svg corner-lines-right.svg council-logo.svg discord-icon.svg element-logo.svg twitter-icon.svg youtube-icon.svg index.css ui types.ts vite-env.d.ts tsconfig.json tsconfig.node.json vite.config.ts package.json packages contract-stub .prettierrc.js jest.config.js package.json src index.ts stubContract.test.ts stubContract.ts testing abis ERC20.json mockProvider.ts types ERC20.ts common.ts factories ERC20__factory.ts index.ts index.ts tsconfig.json council-cli .prettierrc.js README.md package.json src @types cfonts index.d.ts commands config.ts config delete.ts get.ts inspect.ts reset.ts set.ts deploy.ts deploy airdrop.ts core-voting.ts default.ts gsc-vault.ts locking-vault.ts mock-erc20.ts optimistic-grants.ts optimistic-rewards.ts simple-proxy.ts simple.ts spender.ts timelock.ts treasury.ts utils deploymentStore.ts vesting-vault.ts encode.ts encode airdrop.ts airdrop authorize.ts claim-and-delegate.ts claim.ts deauthorize.ts reclaim.ts set-owner.ts core-voting.ts core-voting authorize.ts change-extra-voting-time.ts change-vault-status.ts deauthorize.ts set-custom-quorum.ts set-default-quorum.ts set-lock-duration.ts set-min-proposal-power.ts set-owner.ts gsc-vault.ts gsc-vault authorize.ts deauthorize.ts set-core-voting.ts set-idle-duration.ts set-owner.ts set-vote-power-bound.ts libraries authorizable authorize.ts deauthorize.ts set-owner.ts merkle-rewards claim-and-delegate.ts claim.ts locking-vault.ts locking-vault change-delegation.ts deposit.ts withdraw.ts optimistic-grants.ts optimistic-grants claim.ts configure-grant.ts deposit.ts withdraw.ts optimistic-rewards.ts optimistic-rewards authorize.ts challenge-rewards.ts claim-and-delegate.ts claim.ts deauthorize.ts propose-rewards.ts set-challenge-period.ts set-owner.ts set-proposer.ts spender.ts spender authorize.ts deauthorize.ts high-spend.ts medium-spend.ts remove-token.ts set-limits.ts set-owner.ts small-spend.ts timelock.ts timelock authorize.ts deauthorize.ts execute.ts increase-time.ts register-call.ts set-owner.ts set-wait-time.ts stop-call.ts treasury.ts treasury approve.ts authorize.ts deauthorize.ts generic-call.ts send-funds.ts set-owner.ts vesting-vault.ts vesting-vault accept-grant.ts add-grant-and-delegate.ts change-delegation.ts change-unvested-multiplier.ts delegate.ts deposit.ts initialize.ts remove-grant.ts set-manager.ts set-timelock.ts update-voting-power.ts withdraw.ts mock-token.ts mock-token mint.ts set-allowance.ts set-balance.ts proposal.ts proposal create.ts execute.ts server.ts config.ts council.ts options chain.ts rpc-url.ts utils requiredArray.ts requiredBoolean.ts requiredCallHash.ts requiredNumber.ts requiredNumberString.ts requiredOption.ts requiredSecret.ts requiredString.ts types.ts wallet-key.ts utils JSONStore.ts bigint formatBigInt.ts parseBigInt.ts stringifyBigInts.ts chains.ts constants.ts createCallHash.ts createCommandModule.ts deployContract.ts fetchPolyfill.ts getOSConfigDir.ts mine.ts selectCommandHandler.ts types.ts validation isNotEmptyList.ts isNumberString.ts tsconfig.json tsup.config.ts typedoc.json council-deploy .prettierrc.js README.md hardhat.config.ts package.json scripts load-contracts.sh solhint.json src airdrop accounts accounts.json index.ts leavesWithProofs.json types.ts deployAirdrop.ts promptDeployAirdrop.ts base contractFactory.ts prompts promptNumber.ts promptString.ts promptYesNo.ts time.ts writeFile.ts coreVoting deployCoreVoting.ts deployGSCCoreVoting.ts proposals createCallHash.ts createProposalRemoveVestingVault.ts createProposalSetWaitTime.ts deployCouncil.ts deployments deployments.schema.json getDeployments.ts goerli.deployments.json index.ts mainnet.deployments.json types.ts etherscan urls.ts verifyContract.ts index.ts promptDeploy.ts timelock deployTimelock.ts treasury deployTreasury.ts vaults deployGSCVault.ts deployVestingVault.ts lockingVault deployLockingVault.ts getLockingVaults.ts promptChooseLockingVaultAndDepositTokens.ts votingToken deployVotingToken.ts getVotingTokens.ts promptMint.ts promptMintFromListOfVotingTokens.ts tsconfig.json council-sdk .prettierrc.js README.md jest.config.js package.json src context context.test.ts context.ts datasources airdrop AirdropContractDataSource.ts AirdropDataSource.ts base DataSource.ts cached CachedDataSource.test.ts CachedDataSource.ts contract ContractDataSource.test.ts ContractDataSource.ts http HTTPDataSource.ts mocks MockDataSource.ts token ERC20ContractDataSource.ts MockERC20ContractDataSource.ts TokenDataSource.ts votingContract CoreVotingContractDataSource.ts VotingContractDataSource.ts votingVault GSCVaultContractDataSource.ts LockingVaultContractDataSource.ts VestingVaultContractDataSource.test.ts VestingVaultContractDataSource.ts VotingVaultContractDataSource.test.ts VotingVaultContractDataSource.ts VotingVaultDataSource.ts example ElementGoerliAddressList.json ElementMainnetAddressList.json index.ts index.ts models Airdrop.ts Model.ts Proposal.ts Vote.ts Voter.ts token MockToken.ts Token.ts votingContract GSCVotingContract.ts VotingContract.ts votingVault GSCVault.ts LockingVault.ts VestingVault.ts VotingVault.ts types.ts testing mockBlock.ts mockEvent.ts mockProvider.ts mockSigner.ts mockTransaction.ts mockTransactionReceipt.ts utils cached.ts getBlockDate.ts getVaultsWithPower.ts sumStrings.ts tsconfig.json tsconfig.test.json typedoc.json council-typechain .prettierrc.js hardhat.config.ts package.json scripts load-contracts.sh src @openzeppelin contracts index.ts token ERC20 IERC20.ts extensions draft-IERC20Permit.sol IERC20Permit.ts index.ts index.ts index.ts index.ts index.ts common.ts contracts CoreVoting.ts features Airdrop.ts OptimisticGrants.ts Spender.ts Timelock.ts Treasury.ts index.ts index.ts interfaces ICoreVoting.ts IERC20.ts IERC20Permit.ts ILockingVault.ts IVotingVault.ts index.ts libraries Authorizable.ts ERC20Permit.ts ERC20PermitWithMint.ts MerkleRewards.sol AbstractMerkleRewards.ts MerkleRewards.ts index.ts Storage.ts index.ts mocks MockCoreVoting.ts MockDoubleSpender.ts MockERC20.ts MockHistoryTracker.ts MockLockingVault.ts MockTokenLogic.ts MockVotingVault.ts Reverter.ts StorageRead.sol ReadAndWriteAnyStorage.ts index.ts TestCoreVoting.ts TestTreasury.ts TestVestingVault.ts index.ts simpleProxy.sol SimpleProxy.ts index.ts vaults FrozenLockingVault.ts FrozenVestingVault.ts GSCVault.ts LockingVault.sol AbstractLockingVault.ts LockingVault.ts index.ts NonvotingVault.sol NonVotingVault.ts index.ts OptimisticRewards.ts VestingVault.sol AbstractVestingVault.ts VestingVault.ts index.ts index.ts factories @openzeppelin contracts index.ts token ERC20 IERC20__factory.ts extensions draft-IERC20Permit.sol IERC20Permit__factory.ts index.ts index.ts index.ts index.ts index.ts contracts CoreVoting__factory.ts features Airdrop__factory.ts OptimisticGrants__factory.ts Spender__factory.ts Timelock__factory.ts Treasury__factory.ts index.ts index.ts interfaces ICoreVoting__factory.ts IERC20Permit__factory.ts IERC20__factory.ts ILockingVault__factory.ts IVotingVault__factory.ts index.ts libraries Authorizable__factory.ts ERC20PermitWithMint__factory.ts ERC20Permit__factory.ts MerkleRewards.sol AbstractMerkleRewards__factory.ts MerkleRewards__factory.ts index.ts Storage__factory.ts index.ts mocks MockCoreVoting__factory.ts MockDoubleSpender__factory.ts MockERC20__factory.ts MockHistoryTracker__factory.ts MockLockingVault__factory.ts MockTokenLogic__factory.ts MockVotingVault__factory.ts Reverter__factory.ts StorageRead.sol ReadAndWriteAnyStorage__factory.ts index.ts TestCoreVoting__factory.ts TestTreasury__factory.ts TestVestingVault__factory.ts index.ts simpleProxy.sol SimpleProxy__factory.ts index.ts vaults FrozenLockingVault__factory.ts FrozenVestingVault__factory.ts GSCVault__factory.ts LockingVault.sol AbstractLockingVault__factory.ts LockingVault__factory.ts index.ts NonvotingVault.sol NonVotingVault__factory.ts index.ts OptimisticRewards__factory.ts VestingVault.sol AbstractVestingVault__factory.ts VestingVault__factory.ts index.ts index.ts index.ts hardhat.d.ts index.ts tsconfig.build.json tsconfig.json eslint-config .eslintrc.js package.json prettier-config .prettierrc.js index.js package.json tsconfig README.md base.json nextjs.json package.json react-library.json turbo.json | deploy deployAnvil.sh deployGnosis.sh deployGnosisChiado.sh deployLinea.sh deployzkevm.sh deployzkevmTestnet.sh foundry.toml sismo-connect-onchain-tutorial .eslintrc.json README.md abi Airdrop.json foundry.toml front .eslintrc.json README.md next.config.js package-lock.json package.json script generate-abi-from-front.sh generate-abi.sh log.sh src app globals.css page.module.css utils misc.ts tsconfig.json lib forge-std .github workflows ci.yml sync.yml README.md foundry.toml lib ds-test .github workflows build.yml package.json package.json test fixtures broadcast.log.json openzeppelin-contracts .changeset beige-buses-drop.md config.json curvy-shrimps-enjoy.md curvy-suns-sort.md early-oranges-raise.md famous-rules-burn.md five-ducks-develop.md five-poets-mix.md flat-deers-end.md four-bats-sniff.md funny-rockets-compete.md gold-chicken-clean.md happy-socks-travel.md healthy-squids-stare.md lemon-dogs-kiss.md little-kiwis-ring.md loud-wolves-promise.md lovely-dragons-appear.md modern-games-exist.md new-ways-own.md ninety-hornets-kick.md perfect-insects-listen.md pretty-hornets-play.md proud-comics-deliver.md short-roses-judge.md silent-dancers-type.md slimy-knives-hug.md small-cars-appear.md small-terms-sleep.md strong-bulldogs-buy.md tame-ladybugs-sit.md tender-needles-dance.md thin-dragons-report.md thirty-swans-exercise.md violet-frogs-hide.md warm-masks-obey.md yellow-swans-cover.md .codecov.yml .github ISSUE_TEMPLATE bug_report.md config.yml feature_request.md PULL_REQUEST_TEMPLATE.md actions gas-compare action.yml setup action.yml storage-layout action.yml workflows actionlint.yml changeset.yml checks.yml docs.yml formal-verification.yml release-cycle.yml upgradeable.yml .mocharc.js .solcover.js .solhint.json CHANGELOG.md CODE_OF_CONDUCT.md CONTRIBUTING.md GUIDELINES.md README.md RELEASING.md SECURITY.md audits 2017-03.md README.md certora README.md run.js specs.json contracts package.json token ERC1155 presets README.md ERC20 presets README.md ERC721 presets README.md foundry.toml hardhat.config.js hardhat env-artifacts.js env-contract.js ignore-unreachable-warnings.js skip-foundry-tests.js task-test-get-files.js lib erc4626-tests README.md forge-std .github workflows ci.yml README.md foundry.toml lib ds-test .github workflows build.yml package.json package.json test fixtures broadcast.log.json logo.svg netlify.toml package.json remappings.txt renovate.json requirements.txt scripts checks compare-layout.js compareGasReports.js extract-layout.js generation.sh inheritance-ordering.js gen-nav.js generate format-lines.js run.js templates Checkpoints.js Checkpoints.opts.js Checkpoints.t.js EnumerableMap.js EnumerableSet.js SafeCast.js StorageSlot.js conversion.js git-user-config.sh helpers.js migrate-imports.js prepack.sh prepare-contracts-package.sh prepare-docs.sh prepare.sh release format-changelog.js synchronize-versions.js update-comment.js version.sh workflow exit-prerelease.sh github-release.js integrity-check.sh pack.sh prepare-release-merge.sh publish.sh rerun.js set-changesets-pr-title.js start.sh state.js remove-ignored-artifacts.js update-docs-branch.js upgradeable README.md patch-apply.sh patch-save.sh transpile-onto.sh transpile.sh slither.config.json test TESTING.md access AccessControl.behavior.js AccessControl.test.js AccessControlCrossChain.test.js AccessControlDefaultAdminRules.test.js AccessControlEnumerable.test.js Ownable.test.js Ownable2Step.test.js crosschain CrossChainEnabled.test.js finance PaymentSplitter.test.js VestingWallet.behavior.js VestingWallet.test.js governance Governor.test.js TimelockController.test.js compatibility GovernorCompatibilityBravo.test.js extensions GovernorComp.test.js GovernorERC721.test.js GovernorPreventLateQuorum.test.js GovernorTimelockCompound.test.js GovernorTimelockControl.test.js GovernorVotesQuorumFraction.test.js GovernorWithParams.test.js utils EIP6372.behavior.js Votes.behavior.js Votes.test.js helpers chainid.js create2.js crosschain.js customError.js eip712.js enums.js erc1967.js governance.js map-values.js sign.js time.js txpool.js metatx ERC2771Context.test.js MinimalForwarder.test.js migrate-imports.test.js proxy Clones.behaviour.js Clones.test.js ERC1967 ERC1967Proxy.test.js Proxy.behaviour.js beacon BeaconProxy.test.js UpgradeableBeacon.test.js transparent ProxyAdmin.test.js TransparentUpgradeableProxy.behaviour.js TransparentUpgradeableProxy.test.js utils Initializable.test.js UUPSUpgradeable.test.js security Pausable.test.js PullPayment.test.js ReentrancyGuard.test.js token ERC1155 ERC1155.behavior.js ERC1155.test.js extensions ERC1155Burnable.test.js ERC1155Pausable.test.js ERC1155Supply.test.js ERC1155URIStorage.test.js presets ERC1155PresetMinterPauser.test.js utils ERC1155Holder.test.js ERC20 ERC20.behavior.js ERC20.test.js extensions ERC20Burnable.behavior.js ERC20Burnable.test.js ERC20Capped.behavior.js ERC20Capped.test.js ERC20FlashMint.test.js ERC20Pausable.test.js ERC20Snapshot.test.js ERC20Votes.test.js ERC20VotesComp.test.js ERC20Wrapper.test.js ERC4626.test.js draft-ERC20Permit.test.js presets ERC20PresetFixedSupply.test.js ERC20PresetMinterPauser.test.js utils SafeERC20.test.js TokenTimelock.test.js ERC721 ERC721.behavior.js ERC721.test.js ERC721Enumerable.test.js extensions ERC721Burnable.test.js ERC721Consecutive.test.js ERC721Pausable.test.js ERC721Royalty.test.js ERC721URIStorage.test.js ERC721Votes.test.js ERC721Wrapper.test.js presets ERC721PresetMinterPauserAutoId.test.js utils ERC721Holder.test.js ERC777 ERC777.behavior.js ERC777.test.js presets ERC777PresetFixedSupply.test.js common ERC2981.behavior.js utils Address.test.js Arrays.test.js Base64.test.js Checkpoints.test.js Context.behavior.js Context.test.js Counters.test.js Create2.test.js Multicall.test.js ShortStrings.test.js StorageSlot.test.js Strings.test.js TimersBlockNumberImpl.test.js TimersTimestamp.test.js cryptography ECDSA.test.js EIP712.test.js MerkleProof.test.js SignatureChecker.test.js escrow ConditionalEscrow.test.js Escrow.behavior.js Escrow.test.js RefundEscrow.test.js introspection ERC165.test.js ERC165Checker.test.js ERC165Storage.test.js ERC1820Implementer.test.js SupportsInterface.behavior.js math Math.test.js SafeCast.test.js SafeMath.test.js SignedMath.test.js SignedSafeMath.test.js structs BitMap.test.js DoubleEndedQueue.test.js EnumerableMap.behavior.js EnumerableMap.test.js EnumerableSet.behavior.js EnumerableSet.test.js sismo-connect-packages .github workflows ci.yml README.md foundry.toml package.json packages common types.ts sismo-connect-client README.md jest.config.ts package.json rollup.config.js src abi index.ts sismo-connect.ts api api-fetcher.ts index.ts types.ts common-types.ts constants.ts index.ts sdk index.ts queries.ts sdk.ts types.ts sismo-connect.ts types.ts utils toSismoResponseBytes.ts unCompressResponse.ts tests request-builder.test.ts sismo-connect.test.ts tsconfig.json sismo-connect-react README.md package.json rollup.config.js src components Loader Loader.css index.ts Logo index.ts SismoConnectButton SismoConnectButton.css index.ts hooks useSismoConnect.ts index.ts zk-connect-logo.svg tsconfig.json sismo-connect-server README.md jest.config.ts jest.setup.ts package.json rollup.config.js src common-types.ts constants.ts index.ts sismo-connect.ts types.ts verifier hydra-verifiers hydra-verifier.ts hydras3-verifier.ts index.ts index.ts libs contracts available-roots-registry index.ts commitment-mapper-registry dev.ts index.ts commons abis AvailableRootsRegistry.json CommitmentMapperRegistry.json typechain AvailableRootsRegistry.ts CommitmentMapperRegistry.ts common.ts index.ts onchain-provider index.ts utils encodeAccountsTreeValue.ts encodeRequestIdentifier.ts encodeServiceId.ts isHexlify.ts proofData.ts verifier.ts tests hydras3-verifier-mocked.ts hydras3-verifier.test.ts mocks.ts sismo-connect-e2e.test.ts utils updateProofDataInput.ts tsconfig.json sismo-connect-solidity LICENSE.md README.md foundry.toml lib sismo-connect-onchain-verifier .github workflows forge.yml .hardhat README.md package.json LICENSE.md README.md foundry.toml package.json remappings.txt script bash setup-fork.sh package.json remappings.txt remappings.txt tsconfig.json package-lock.json package.json remappings.txt src VaultAbi.json waterloo.txt world-id-onchain .eslintrc.json .prettierrc.js README.md contracts foundry.toml next.config.js package-lock.json package.json postcss.config.js public next.svg vercel.svg src abi Contract.abi.ts lib consts.ts wld.ts pages api hello.ts styles globals.css tailwind.config.js tsconfig.json
<br /> <div align="center"> <img src="https://static.sismo.io/readme/top-main.png" alt="Logo" width="150" height="150" style="borderRadius: 20px"> <h3 align="center"> Sismo Connect </h3> <p align="center"> Made by <a href="https://docs.sismo.io/" target="_blank">Sismo</a> </p> <p align="center"> <a href="https://twitter.com/sismo_eth" target="_blank"> <img src="https://img.shields.io/badge/Twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white"/> </a> <a href="https://discord.gg/sismo" target="_blank"> <img src="https://img.shields.io/badge/Discord-7289DA?style=for-the-badge&logo=discord&logoColor=white"/> </a> <a href="https://builders.sismo.io" target="_blank"> <img src="https://img.shields.io/badge/Telegram-2CA5E0?style=for-the-badge&logo=telegram&logoColor=white"/> </a> </p> </div> Sismo Connect is a crypto-native single sign-on method for applications. Once integrated, applications can request private, granular data from users, while users can authenticate and selectively reveal their data thanks to zero-knowledge proofs (ZKPs). Here is the link to the full documentation in our GitBook: [Sismo Connect Packages](https://docs.sismo.io/sismo-docs/build-with-sismo-connect/technical-documentation) You can learn more on Sismo Connect [here](https://docs.sismo.io/discover-sismo-connect/empower-your-app). ## License Distributed under the MIT License. ## Contribute Please, feel free to open issues, PRs or simply provide feedback! ## Contact Send us a message in [Telegram](https://builders.sismo.io/) or [Discord](https://discord.gg/sismo) <br/> <img src="https://static.sismo.io/readme/bottom-main.png" alt="bottom" width="100%" > # Running the certora verification tool These instructions detail the process for running Certora Verification Tool on OpenZeppelin Contracts. Documentation for CVT and the specification language are available [here](https://certora.atlassian.net/wiki/spaces/CPD/overview). ## Prerequisites Follow the [Certora installation guide](https://docs.certora.com/en/latest/docs/user-guide/getting-started/install.html) in order to get the Certora Prover Package and the `solc` executable folder in your path. > **Note** > An API Key is required for local testing. Although the prover will run on a Github Actions' CI environment on selected Pull Requests. ## Running the verification The Certora Verification Tool proves specs for contracts, which are defined by the `./specs.json` file along with their pre-configured options. The verification script `./run.js` is used to submit verification jobs to the Certora Verification service. You can run it from the root of the repository with the following command: ```bash node certora/run.js [[CONTRACT_NAME:]SPEC_NAME] [OPTIONS...] ``` Where: - `CONTRACT_NAME` matches the `contract` key in the `./spec.json` file and may be empty. It will run all matching contracts if not provided. - `SPEC_NAME` refers to a `spec` key from the `./specs.json` file. It will run every spec if not provided. - `OPTIONS` extend the [Certora Prover CLI options](https://docs.certora.com/en/latest/docs/prover/cli/options.html#certora-prover-cli-options) and will respect the preconfigured options in the `specs.json` file. > **Note** > A single spec may be configured to run for multiple contracts, whereas a single contract may run multiple specs. Example usage: ```bash node certora/run.js AccessControl # Run the AccessControl spec against every contract implementing it ``` ## Adapting to changes in the contracts Some of our rules require the code to be simplified in various ways. Our primary tool for performing these simplifications is to run verification on a contract that extends the original contracts and overrides some of the methods. These "harness" contracts can be found in the `certora/harness` directory. This pattern does require some modifications to the original code: some methods need to be made virtual or public, for example. These changes are handled by applying a patch to the code before verification by running: ```bash make -C certora apply ``` Before running the `certora/run.js` script, it's required to apply the corresponding patches to the `contracts` directory, placing the output in the `certora/patched` directory. Then, the contracts are verified by running the verification for the `certora/patched` directory. If the original contracts change, it is possible to create a conflict with the patch. In this case, the verify scripts will report an error message and output rejected changes in the `patched` directory. After merging the changes, run `make record` in the `certora` directory; this will regenerate the patch file, which can then be checked into git. For more information about the `make` scripts available, run: ```bash make -C certora help ``` <br /> <div align="center"> <img src="https://static.sismo.io/readme/top-main.png" alt="Logo" width="150" height="150" style="borderRadius: 20px"> <h3 align="center"> Sismo Connect React </h3> <p align="center"> Made by <a href="https://docs.sismo.io/" target="_blank">Sismo</a> </p> <p align="center"> <a href="https://twitter.com/sismo_eth" target="_blank"> <img src="https://img.shields.io/badge/Twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white"/> </a> <a href="https://discord.gg/sismo" target="_blank"> <img src="https://img.shields.io/badge/Discord-7289DA?style=for-the-badge&logo=discord&logoColor=white"/> </a> <a href="https://builders.sismo.io" target="_blank"> <img src="https://img.shields.io/badge/Telegram-2CA5E0?style=for-the-badge&logo=telegram&logoColor=white"/> </a> </p> </div> The Sismo Connect React package is a wrapper of the Sismo Connect Client package which allows to easily request data from the Sismo Data Vault app. Here is the link to the full documentation of the package: [Sismo Connect React package](https://docs.sismo.io/build-with-sismo-connect/technical-documentation/react). You can learn more on Sismo Connect [here](https://docs.sismo.io/discover-sismo-connect/empower-your-app). ### Prerequisites - [Node.js](https://nodejs.org/en/download/) >= 18.15.0 (Latest LTS version) ## Usage ### Installation Install the Sismo Connect React package in your frontend with npm or yarn: ```bash # with npm npm install @sismo-core/sismo-connect-react # with yarn yarn add @sismo-core/sismo-connect-react ``` ### Import Import the Sismo Connect React package in your frontend: ```typescript import { SismoConnectClientConfig } from "@sismo-core/sismo-connect-react"; export const sismoConnectConfig: SismoConnectClientConfig = { appId: "0x8f347ca31790557391cec39b06f02dc2", }; ``` See the full documentation [here](https://docs.sismo.io/build-with-sismo-connect/technical-documentation/react). ## License Distributed under the MIT License. ## Contribute Please, feel free to open issues, PRs or simply provide feedback! ## Contact Send us a message in [Telegram](https://builders.sismo.io/) or [Discord](https://discord.gg/sismo) <br/> <img src="https://static.sismo.io/readme/bottom-main.png" alt="bottom" width="100%" > Contract presets are now deprecated in favor of [Contracts Wizard](https://wizard.openzeppelin.com/) as a more powerful alternative. # council-ui Council UI is a reference user interface for the Council protocol. This project utilizes the Council SDK for read and write calls to the blockchain. A NextJS based project. ## What's inside? | Name | Description | | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | | [NextJS](https://github.com/vercel/next.js/) | React framework enabling applications with server-side rendering and generating static websites. | | [Tailwind CSS](https://github.com/tailwindlabs/tailwindcss) | Open source CSS framework for inline component styling. | | [DaisyUI](https://github.com/saadeghi/daisyui) | Popular Tailwind CSS component library. | | [wagmi](https://github.com/wagmi-dev/wagmi) | React Hooks for Ethereum. | | [ENS.js](https://github.com/ensdomains/ensjs-v3) | ENS JavaScript library. | ## Getting started This guide is under the assumption of being in the `council-kit `monorepo. ### Install dependencies ```bash yarn ``` ### Run the development server ```bash yarn workspace council-ui dev ``` ### Run the development server ```bash yarn workspace council-ui dev ``` Open [http://localhost:3000](http://localhost:3000) with your browser to see the application. ### Linting ```bash yarn workspace council-ui lint:check yarn workspace council-ui lint # writes fixes to file ``` ### Formatting ```bash yarn workspace council-ui format:check yarn workspace council-ui format # write to files ``` ## Production This project is configured to be deployed using GitHub pages using a [custom action](https://github.com/delvtech/council-kit/blob/main/.github/workflows/gh-pages-council.yml). Furthermore, we've included some additional actions for CI code [linting](https://github.com/delvtech/council-kit/blob/main/.github/workflows/lint.yml) and [formatting](https://github.com/delvtech/council-kit/blob/main/.github/workflows/format.yml). If you need a custom deployment you can build the bundle using the following commands. ### Build and export the bundle ```bash yarn workspace council-ui build # build the project yarn workspace council-ui export # export the static site bundle ``` The production output can be viewed at `/out`. ## Council Config Configuration files for this project reside in `/src/config`. This project is pre-configured for Goerli and Mainnet networks. This configuration can be expanded to include additional static data if needed. As one of our guiding principles for this project was to not rely on centralized servers. Some important data for proposals and voting vaults do not exist on chain and must be configured manually such as the list of approved vaults and proposal metadata (title, description, etc). Each supported network has it's own configuration file. Each configuration file is an object that is keyed by the voting contract name. In the provided configuration example there are two voting contracts: `core voting` and `gsc voting`. ### Adding new proposal data When a new proposal is added on chain the metadata for the proposal needs to be added to the `proposals` value in the respective voting contract object. This is an object that is keyed by the proposal id (assigned on-chain). ```ts { // other proposals here... 5: { descriptionURL: "https://moreinfo.com", targets: [], // not used for now calldatas: [], // not used for now title: "EGP-69: Proposal to do the new cool thing!", sentenceSummary: "We like to be cutting edge so here is the next big thing.", paragraphSummary: "As of today, it is the best interested in the DAO to become cool. This proposal will achieve making is cool again...", }, } ``` ### Adding new voting vault When a new voting vault is approved by a voting contract it must be added to the configuration file. In the `vaults` value of a voting contract object, append the following information: ```ts vaults: [ // other vaults here... { name: "New Vault", paragraphSummary: "A New Vault that does the approved thing...", address: "0x...", type: "NewVault", abi: {}, descriptionURL: "https://moreinfo.com", } ], ``` ## Optimization This project strives to provide a solid reference user interface for developers. Since this project is designed to be **forked**, we did not integrate any indexers and solely rely on reading data from RPCs or from the configuration file(s). Many queries can be optimized for reduced RPC load and shorter latency by using an indexer or expanding the static data pipeline. # Forge Standard Library • [![CI status](https://github.com/foundry-rs/forge-std/actions/workflows/ci.yml/badge.svg)](https://github.com/foundry-rs/forge-std/actions/workflows/ci.yml) Forge Standard Library is a collection of helpful contracts and libraries for use with [Forge and Foundry](https://github.com/foundry-rs/foundry). It leverages Forge's cheatcodes to make writing tests easier and faster, while improving the UX of cheatcodes. **Learn how to use Forge-Std with the [📖 Foundry Book (Forge-Std Guide)](https://book.getfoundry.sh/forge/forge-std.html).** ## Install ```bash forge install foundry-rs/forge-std ``` ## Contracts ### stdError This is a helper contract for errors and reverts. In Forge, this contract is particularly helpful for the `expectRevert` cheatcode, as it provides all compiler builtin errors. See the contract itself for all error codes. #### Example usage ```solidity import "forge-std/Test.sol"; contract TestContract is Test { ErrorsTest test; function setUp() public { test = new ErrorsTest(); } function testExpectArithmetic() public { vm.expectRevert(stdError.arithmeticError); test.arithmeticError(10); } } contract ErrorsTest { function arithmeticError(uint256 a) public { uint256 a = a - 100; } } ``` ### stdStorage This is a rather large contract due to all of the overloading to make the UX decent. Primarily, it is a wrapper around the `record` and `accesses` cheatcodes. It can *always* find and write the storage slot(s) associated with a particular variable without knowing the storage layout. The one _major_ caveat to this is while a slot can be found for packed storage variables, we can't write to that variable safely. If a user tries to write to a packed slot, the execution throws an error, unless it is uninitialized (`bytes32(0)`). This works by recording all `SLOAD`s and `SSTORE`s during a function call. If there is a single slot read or written to, it immediately returns the slot. Otherwise, behind the scenes, we iterate through and check each one (assuming the user passed in a `depth` parameter). If the variable is a struct, you can pass in a `depth` parameter which is basically the field depth. I.e.: ```solidity struct T { // depth 0 uint256 a; // depth 1 uint256 b; } ``` #### Example usage ```solidity import "forge-std/Test.sol"; contract TestContract is Test { using stdStorage for StdStorage; Storage test; function setUp() public { test = new Storage(); } function testFindExists() public { // Lets say we want to find the slot for the public // variable `exists`. We just pass in the function selector // to the `find` command uint256 slot = stdstore.target(address(test)).sig("exists()").find(); assertEq(slot, 0); } function testWriteExists() public { // Lets say we want to write to the slot for the public // variable `exists`. We just pass in the function selector // to the `checked_write` command stdstore.target(address(test)).sig("exists()").checked_write(100); assertEq(test.exists(), 100); } // It supports arbitrary storage layouts, like assembly based storage locations function testFindHidden() public { // `hidden` is a random hash of a bytes, iteration through slots would // not find it. Our mechanism does // Also, you can use the selector instead of a string uint256 slot = stdstore.target(address(test)).sig(test.hidden.selector).find(); assertEq(slot, uint256(keccak256("my.random.var"))); } // If targeting a mapping, you have to pass in the keys necessary to perform the find // i.e.: function testFindMapping() public { uint256 slot = stdstore .target(address(test)) .sig(test.map_addr.selector) .with_key(address(this)) .find(); // in the `Storage` constructor, we wrote that this address' value was 1 in the map // so when we load the slot, we expect it to be 1 assertEq(uint(vm.load(address(test), bytes32(slot))), 1); } // If the target is a struct, you can specify the field depth: function testFindStruct() public { // NOTE: see the depth parameter - 0 means 0th field, 1 means 1st field, etc. uint256 slot_for_a_field = stdstore .target(address(test)) .sig(test.basicStruct.selector) .depth(0) .find(); uint256 slot_for_b_field = stdstore .target(address(test)) .sig(test.basicStruct.selector) .depth(1) .find(); assertEq(uint(vm.load(address(test), bytes32(slot_for_a_field))), 1); assertEq(uint(vm.load(address(test), bytes32(slot_for_b_field))), 2); } } // A complex storage contract contract Storage { struct UnpackedStruct { uint256 a; uint256 b; } constructor() { map_addr[msg.sender] = 1; } uint256 public exists = 1; mapping(address => uint256) public map_addr; // mapping(address => Packed) public map_packed; mapping(address => UnpackedStruct) public map_struct; mapping(address => mapping(address => uint256)) public deep_map; mapping(address => mapping(address => UnpackedStruct)) public deep_map_struct; UnpackedStruct public basicStruct = UnpackedStruct({ a: 1, b: 2 }); function hidden() public view returns (bytes32 t) { // an extremely hidden storage slot bytes32 slot = keccak256("my.random.var"); assembly { t := sload(slot) } } } ``` ### stdCheats This is a wrapper over miscellaneous cheatcodes that need wrappers to be more dev friendly. Currently there are only functions related to `prank`. In general, users may expect ETH to be put into an address on `prank`, but this is not the case for safety reasons. Explicitly this `hoax` function should only be used for address that have expected balances as it will get overwritten. If an address already has ETH, you should just use `prank`. If you want to change that balance explicitly, just use `deal`. If you want to do both, `hoax` is also right for you. #### Example usage: ```solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "forge-std/Test.sol"; // Inherit the stdCheats contract StdCheatsTest is Test { Bar test; function setUp() public { test = new Bar(); } function testHoax() public { // we call `hoax`, which gives the target address // eth and then calls `prank` hoax(address(1337)); test.bar{value: 100}(address(1337)); // overloaded to allow you to specify how much eth to // initialize the address with hoax(address(1337), 1); test.bar{value: 1}(address(1337)); } function testStartHoax() public { // we call `startHoax`, which gives the target address // eth and then calls `startPrank` // // it is also overloaded so that you can specify an eth amount startHoax(address(1337)); test.bar{value: 100}(address(1337)); test.bar{value: 100}(address(1337)); vm.stopPrank(); test.bar(address(this)); } } contract Bar { function bar(address expectedSender) public payable { require(msg.sender == expectedSender, "!prank"); } } ``` ### Std Assertions Expand upon the assertion functions from the `DSTest` library. ### `console.log` Usage follows the same format as [Hardhat](https://hardhat.org/hardhat-network/reference/#console-log). It's recommended to use `console2.sol` as shown below, as this will show the decoded logs in Forge traces. ```solidity // import it indirectly via Test.sol import "forge-std/Test.sol"; // or directly import it import "forge-std/console2.sol"; ... console2.log(someValue); ``` If you need compatibility with Hardhat, you must use the standard `console.sol` instead. Due to a bug in `console.sol`, logs that use `uint256` or `int256` types will not be properly decoded in Forge traces. ```solidity // import it indirectly via Test.sol import "forge-std/Test.sol"; // or directly import it import "forge-std/console.sol"; ... console.log(someValue); ``` ## License Forge Standard Library is offered under either [MIT](LICENSE-MIT) or [Apache 2.0](LICENSE-APACHE) license. <br /> <div align="center"> <img src="https://static.sismo.io/readme/top-main.png" alt="Logo" width="150" height="150" style="borderRadius: 20px"> <h3 align="center"> Sismo Connect Solidity </h3> <p align="center"> Made by <a href="https://docs.sismo.io/" target="_blank">Sismo</a> </p> <p align="center"> <a href="https://twitter.com/sismo_eth" target="_blank"> <img src="https://img.shields.io/badge/Twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white"/> </a> <a href="https://discord.gg/sismo" target="_blank"> <img src="https://img.shields.io/badge/Discord-7289DA?style=for-the-badge&logo=discord&logoColor=white"/> </a> <a href="https://builders.sismo.io" target="_blank"> <img src="https://img.shields.io/badge/Telegram-2CA5E0?style=for-the-badge&logo=telegram&logoColor=white"/> </a> </p> </div> Sismo Connect Solidity is a Solidity library that allows you to verify the zk-proofs of your Sismo Connect Application onchain and simplify the use of the [sismo-connect-onchain-verifier](https://github.com/sismo-core/sismo-connect-onchain-verifier). Here is the link to the full documentation of the library: [Sismo Connect Solidity Library](https://docs.sismo.io/build-with-sismo-connect/technical-documentation/solidity) You can learn more on Sismo Connect [here](https://docs.sismo.io/discover-sismo-connect/empower-your-app). ### Prerequisites - [Node.js](https://nodejs.org/en/download/) >= 18.15.0 (Latest LTS version) - [Yarn](https://classic.yarnpkg.com/en/docs/install) - [Foundry](https://book.getfoundry.sh/) ## Usage ### Installation ```bash # update foundry foundryup # install the package forge install sismo-core/sismo-connect-packages --no-commit # add the remapping in remappings.txt echo $'sismo-connect-solidity/=lib/sismo-connect-packages/packages/sismo-connect-solidity/src/' >> remappings.txt ``` ### Import the library In your solidity file: ```solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.17; import "sismo-connect-solidity/SismoLib.sol"; // import the library ``` ## License Distributed under the MIT License. ## Contribute Please, feel free to open issues, PRs or simply provide feedback! ## Contact Send us a message in [Telegram](https://builders.sismo.io/) or [Discord](https://discord.gg/sismo) <br/> <img src="https://static.sismo.io/readme/bottom-main.png" alt="bottom" width="100%" > The upgradeable variant of OpenZeppelin Contracts is automatically generated from the original Solidity code. We call this process "transpilation" and it is implemented by our [Upgradeability Transpiler](https://github.com/OpenZeppelin/openzeppelin-transpiler/). When the `master` branch or `release-v*` branches are updated, the code is transpiled and pushed to [OpenZeppelin/openzeppelin-contracts-upgradeable](https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable) by the `upgradeable.yml` workflow. ## `transpile.sh` Applies patches and invokes the transpiler with the command line flags we need for our requirements (for example, excluding certain files). ## `transpile-onto.sh` ``` bash scripts/upgradeable/transpile-onto.sh <target> [<base>] ``` Transpiles the contents of the current git branch and commits the result as a new commit on branch `<target>`. If branch `<target>` doesn't exist, it will copy the commit history of `[<base>]` (this is used in GitHub Actions, but is usually not necessary locally). ## `patch-apply.sh` & `patch-save.sh` Some of the upgradeable contract variants require ad-hoc changes that are not implemented by the transpiler. These changes are implemented by patches stored in `upgradeable.patch` in this directory. `patch-apply.sh` applies these patches. If the patches fail to apply due to changes in the repo, the conflicts have to be resolved manually. Once fixed, `patch-save.sh` will take the changes staged in Git and update `upgradeable.patch` to match. This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app). ## Getting Started First, run the development server: ```bash npm run dev # or yarn dev # or pnpm dev ``` Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file. This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font. ## Learn More To learn more about Next.js, take a look at the following resources: - [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. - [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome! ## Deploy on Vercel The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details. <br /> <div align="center"> <img src="https://static.sismo.io/readme/top-main.png" alt="Logo" width="150" height="150" style="borderRadius: 20px"> <h3 align="center"> Sismo Connect Server </h3> <p align="center"> Made by <a href="https://docs.sismo.io/" target="_blank">Sismo</a> </p> <p align="center"> <a href="https://twitter.com/sismo_eth" target="_blank"> <img src="https://img.shields.io/badge/Twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white"/> </a> <a href="https://discord.gg/sismo" target="_blank"> <img src="https://img.shields.io/badge/Discord-7289DA?style=for-the-badge&logo=discord&logoColor=white"/> </a> <a href="https://builders.sismo.io" target="_blank"> <img src="https://img.shields.io/badge/Telegram-2CA5E0?style=for-the-badge&logo=telegram&logoColor=white"/> </a> </p> </div> Sismo Connect is single sign-on method for applications enabling aggregated data requests to users thanks to privacy. Once integrated, applications can request private, granular data from users, while users can authenticate and selectively reveal their data thanks to zero-knowledge proofs (ZKPs). The Sismo Connect Server is a backend package built on top of the Hydra-S2 Verifier to easily verify proofs from your users off-chain. Here is the link to the full documentation of the package: [Sismo Connect Server package](https://docs.sismo.io/build-with-sismo-connect/technical-documentation/server). You can learn more on Sismo Connect [here](https://docs.sismo.io/discover-sismo-connect/empower-your-app). ### Prerequisites - [Node.js](https://nodejs.org/en/download/) >= 18.15.0 (Latest LTS version) ## Usage ### Installation Install Sismo Connect server package in your backend with npm or yarn: ```bash # with npm npm i @sismo-core/sismo-connect-server # with yarn yarn add @sismo-core/sismo-connect-server ``` ### Import Import the package in your backend: ```typescript import { SismoConnect, SismoConnectServerConfig } from "@sismo-core/sismo-connect-server"; const config: SismoConnectServerConfig = { // you will need to register an appId in the Sismo Factory appId: "0x8f347ca31790557391cec39b06f02dc2", } // create a new Sismo Connect instance with the server configuration const sismoConnect = SismoConnect(config); ``` See the full documentation [here](https://docs.sismo.io/build-with-sismo-connect/technical-documentation/server). ## License Distributed under the MIT License. ## Contribute Please, feel free to open issues, PRs or simply provide feedback! ## Contact Send us a message in [Telegram](https://builders.sismo.io/) or [Discord](https://discord.gg/sismo) <br/> <img src="https://static.sismo.io/readme/bottom-main.png" alt="bottom" width="100%" > <br /> <div align="center"> <img src="https://static.sismo.io/readme/top-main.png" alt="Logo" width="150" height="150" style="borderRadius: 20px"> <h3 align="center"> Sismo Connect Client </h3> <p align="center"> Made by <a href="https://docs.sismo.io/" target="_blank">Sismo</a> </p> <p align="center"> <a href="https://twitter.com/sismo_eth" target="_blank"> <img src="https://img.shields.io/badge/Twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white"/> </a> <a href="https://discord.gg/sismo" target="_blank"> <img src="https://img.shields.io/badge/Discord-7289DA?style=for-the-badge&logo=discord&logoColor=white"/> </a> <a href="https://builders.sismo.io" target="_blank"> <img src="https://img.shields.io/badge/Telegram-2CA5E0?style=for-the-badge&logo=telegram&logoColor=white"/> </a> </p> </div> Sismo Connect is single sign-on method for applications enabling aggregated data requests to users thanks to privacy. Once integrated, applications can request private, granular data from users, while users can authenticate and selectively reveal their data thanks to zero-knowledge proofs (ZKPs). The Sismo Connect Client is a frontend package that allows to easily request data from the Sismo Data Vault app. Here is the link to the full documentation of the package: [Sismo Connect Client package](https://docs.sismo.io/build-with-sismo-connect/technical-documentation/client). You can learn more on Sismo Connect [here](https://docs.sismo.io/discover-sismo-connect/empower-your-app). ### Prerequisites - [Node.js](https://nodejs.org/en/download/) >= 18.15.0 (Latest LTS version) ## Usage ### Installation Install Sismo Connect Client package in your frontend with npm or yarn: ```bash # with npm npm install @sismo-core/sismo-connect-client # with yarn yarn add @sismo-core/sismo-connect-client ``` ### Import Import the package in your frontend: ```typescript import { SismoConnect, SismoConnectClientConfig } from "@sismo-core/sismo-connect-client"; const config: SismoConnectClientConfig = { // you will need to register an appId in the Factory appId: "0x8f347ca31790557391cec39b06f02dc2", } // create a new SismoConnect instance with the client configuration const sismoConnect = SismoConnect(config); ``` See the full documentation [here](https://docs.sismo.io/build-with-sismo-connect/technical-documentation/client). ## License Distributed under the MIT License. ## Contribute Please, feel free to open issues, PRs or simply provide feedback! ## Contact Send us a message in [Telegram](https://builders.sismo.io/) or [Discord](https://discord.gg/sismo) <br/> <img src="https://static.sismo.io/readme/bottom-main.png" alt="bottom" width="100%" > <br /> <div align="center"> <img src="https://static.sismo.io/readme/top-main.png" alt="Logo" width="150" height="150" style="borderRadius: 20px"> <h3 align="center"> Sismo Connect Solidity </h3> <p align="center"> Made by <a href="https://docs.sismo.io/" target="_blank">Sismo</a> </p> <p align="center"> <a href="https://twitter.com/sismo_eth" target="_blank"> <img src="https://img.shields.io/badge/Twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white"/> </a> <a href="https://discord.gg/sismo" target="_blank"> <img src="https://img.shields.io/badge/Discord-7289DA?style=for-the-badge&logo=discord&logoColor=white"/> </a> <a href="https://builders.sismo.io" target="_blank"> <img src="https://img.shields.io/badge/Telegram-2CA5E0?style=for-the-badge&logo=telegram&logoColor=white"/> </a> </p> </div> Sismo Connect Solidity is a Solidity library that allows you to verify the zk-proofs of your Sismo Connect Application onchain and simplify the use of the [sismo-connect-onchain-verifier](https://github.com/sismo-core/sismo-connect-onchain-verifier). Here is the link to the full documentation of the library: [Sismo Connect Solidity Library](https://docs.sismo.io/build-with-sismo-connect/technical-documentation/solidity) You can learn more on Sismo Connect [here](https://docs.sismo.io/discover-sismo-connect/empower-your-app). ### Prerequisites - [Node.js](https://nodejs.org/en/download/) >= 18.15.0 (Latest LTS version) - [Yarn](https://classic.yarnpkg.com/en/docs/install) ## Usage ### Installation ```bash # install the package yarn add @sismo-core/sismo-connect-solidity ``` ### Import the library In your solidity file: ```solidity import {SismoConnect} from "@sismo-core/sismo-connect-solidity/contracts/libs/SismoLib.sol"; ``` You will find here how to use the library: [Sismo Connect Solidity Library](https://docs.sismo.io/build-with-sismo-connect/technical-documentation/solidity) ## License Distributed under the MIT License. ## Contribute Please, feel free to open issues, PRs or simply provide feedback! ## Contact Send us a message in [Telegram](https://builders.sismo.io/) or [Discord](https://discord.gg/sismo) <br/> <img src="https://static.sismo.io/readme/bottom-main.png" alt="bottom" width="100%" > # Audits | Date | Version | Commit | Auditor | Scope | Links | | ------------ | ------- | --------- | ------------ | -------------------- | ----------------------------------------------------------- | | May 2023 | v4.9.0 | `91df66c` | OpenZeppelin | v4.9 Changes | [🔗](./2023-05-v4.9.pdf) | | October 2022 | v4.8.0 | `14f98db` | OpenZeppelin | ERC4626, Checkpoints | [🔗](./2022-10-ERC4626.pdf) [🔗](./2022-10-Checkpoints.pdf) | | October 2018 | v2.0.0 | `dac5bcc` | LevelK | Everything | [🔗](./2018-10.pdf) | | March 2017 | v1.0.4 | `9c5975a` | New Alchemy | Everything | [🔗](./2017-03.md) | # Formal Verification | Date | Version | Commit | Tool | Scope | Links | | ------------ | ------- | --------- | ------- | -------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------ | | May 2022 | v4.7.0 | `109778c` | Certora | Initializable, GovernorPreventLateQuorum, ERC1155Burnable, ERC1155Pausable, ERC1155Supply, ERC1155Holder, ERC1155Receiver | [🔗](../certora/reports/2022-05.pdf) | | March 2022 | v4.4.0 | `4088540` | Certora | ERC20Votes, ERC20FlashMint, ERC20Wrapper, TimelockController, ERC721Votes, Votes, AccessControl, ERC1155 | [🔗](../certora/reports/2022-03.pdf) | | October 2021 | v4.4.0 | `4088540` | Certora | Governor, GovernorCountingSimple, GovernorProposalThreshold, GovernorTimelockControl, GovernorVotes, GovernorVotesQuorumFraction | [🔗](../certora/reports/2021-10.pdf) | ``` █▀▀ █▀█ █ █ █▄ █ █▀▀ █ █ █▀▀ █ █ █▄▄ █▄█ █▄█ █ ▀█ █▄▄ █ █▄▄ █▄▄ █▄▄ █ ``` # Council CLI A CLI for interfacing with the [Council protocol](https://github.com/delvtech/council). - [Installation](#installation) - [Basic Usage](#basic-usage) - [Help](#help) - [Deploying a local instance](#deploying-a-local-instance) - [1. Start the local server](#1-start-the-local-server) - [3. Deploy the contracts](#3-deploy-the-contracts) - [Creating proposals](#creating-proposals) - [1. Encode the function data for the proposed actions](#1-encode-the-function-data-for-the-proposed-actions) - [2. Encode the function data to register the call in the Timelock](#2-encode-the-function-data-to-register-the-call-in-the-timelock) - [3. Create the proposal](#3-create-the-proposal) ## Installation The Council CLI isn't currently available as a stand alone package but can be used directly from the root of the `council-kit` monorepo or installed within the council monorepo. 1. Clone the `council-kit` monorepo. 2. Add `"@council/cli": "*"` to the app or package's package.json. 3. Run install: `yarn`. ## Basic Usage The easiest way to use the CLI is to call it from within the monorepo: ``` yarn workspace @council/cli council ``` This will show the guided walkthrough which will have you select commands and prompt for input for the options. ![Council CLI intro prompt screenshot](docs/intro-prompt.png) You can also call commands directly without using the prompts. ```sh # start a local ethereum node server on port 8545 yarn workspace @council/cli council server -p 8545 ``` > You will be prompted for input on any required options that are missing from the command. ## Help You can use the `--help` option to get information on commands, options, descriptions, and defaults. ``` yarn workspace @council/cli council --help ``` ![Council help text screenshot](docs/council-help.png) This option can be used at any level of the CLI. For example, to get help on the `server` command: ``` yarn workspace @council/cli council server --help ``` ![Council server help text screenshot](docs/council-server-help.png) ## Deploying a local instance The CLI has 2 commands to quickly get a local testnet started and deploy a default version of Council. ### 1. Start the local server Use the `server` command to start the local testnet. ``` yarn workspace @council/cli council server -p 8545 ``` This will start a testnet server hosted at `http://127.0.0.1:8545` and show a list of generated accounts with their private keys and ETH balance. ![Council server started message screenshot](docs/council-server.png) ### 3. Deploy the contracts Use the `deploy default` command to deploy a default version of the contracts. ``` yarn workspace @council/cli council deploy default ``` ![Council default deployment screenshot](docs/council-deploy-default.png) ## Creating proposals To create a new proposal in Council, you must know the address of the target contract(s) that the `CoreVoting` contract will call when the proposal is executed and the data to call it with. The CLI includes `encode` commands which can be used to generate the call data for any Council contract and a `proposal` command that can be used to create and execute proposals. To understand how it all works, let's walk through an example of creating a proposal to increase the default quorum to 1.5 million. We'll assume our deployment of Council is using a timelock contract so we'll also need to register the call with the timelock. ### 1. Encode the function data for the proposed actions ``` yarn workspace @council/cli council encode core-voting set-default-quorum --power 1500000 --decimals 18 ``` This uses the `set-default-quorum` command to encode function data for a `CoreVoting.setDefaultQuorum` call. The `--power` option is used to define the new default quorum and the `--decimals` option scales the `--power` value by `10 ** decimals`. The resulting call data is: ``` 0x7d5709eb000000000000000000000000000000000000000000013da329b6336471800000 ``` ### 2. Encode the function data to register the call in the Timelock Since the `CoreVoting` contract needs to go through the timelock to make any changes to the protocol, we have to use the call data we just generated to encode data for `Timelock.registerCall`. ``` yarn workspace @council/cli council encode timelock register-call --targets <voting-contract-address> --calldatas 0x7d5709eb000000000000000000000000000000000000000000013da329b6336471800000 ``` The `--targets` option is used to identify the contract we want to register a call to. The `--calldatas` option is used to identify the data we want the registered call to use when it calls out target. We can use the encoded data we generated previously. Replace the `<voting-contract-address>` with an actual address. This results in the following call data: ``` 0x88b49b83dc0bdcecdf6757652124a4cf28d00de01c12935d6fd3113205e645b0abb7cf28 ``` ### 3. Create the proposal ``` yarn workspace @council/cli council proposal create --address <voting-contract-address> --vaults <space-separated-vault-addresses> --targets <timelock-address> --calldatas 0x88b49b83dc0bdcecdf6757652124a4cf28d00de01c12935d6fd3113205e645b0abb7cf28 --last-call 648000 --ballot yes --wallet-key <wallet-private-key> ``` You can also just use `yarn workspace @council/cli council proposal create` to be prompted for all required options. # Forge Standard Library • [![CI status](https://github.com/foundry-rs/forge-std/actions/workflows/ci.yml/badge.svg)](https://github.com/foundry-rs/forge-std/actions/workflows/ci.yml) Forge Standard Library is a collection of helpful contracts and libraries for use with [Forge and Foundry](https://github.com/foundry-rs/foundry). It leverages Forge's cheatcodes to make writing tests easier and faster, while improving the UX of cheatcodes. **Learn how to use Forge-Std with the [📖 Foundry Book (Forge-Std Guide)](https://book.getfoundry.sh/forge/forge-std.html).** ## Install ```bash forge install foundry-rs/forge-std ``` ## Contracts ### stdError This is a helper contract for errors and reverts. In Forge, this contract is particularly helpful for the `expectRevert` cheatcode, as it provides all compiler builtin errors. See the contract itself for all error codes. #### Example usage ```solidity import "forge-std/Test.sol"; contract TestContract is Test { ErrorsTest test; function setUp() public { test = new ErrorsTest(); } function testExpectArithmetic() public { vm.expectRevert(stdError.arithmeticError); test.arithmeticError(10); } } contract ErrorsTest { function arithmeticError(uint256 a) public { uint256 a = a - 100; } } ``` ### stdStorage This is a rather large contract due to all of the overloading to make the UX decent. Primarily, it is a wrapper around the `record` and `accesses` cheatcodes. It can *always* find and write the storage slot(s) associated with a particular variable without knowing the storage layout. The one _major_ caveat to this is while a slot can be found for packed storage variables, we can't write to that variable safely. If a user tries to write to a packed slot, the execution throws an error, unless it is uninitialized (`bytes32(0)`). This works by recording all `SLOAD`s and `SSTORE`s during a function call. If there is a single slot read or written to, it immediately returns the slot. Otherwise, behind the scenes, we iterate through and check each one (assuming the user passed in a `depth` parameter). If the variable is a struct, you can pass in a `depth` parameter which is basically the field depth. I.e.: ```solidity struct T { // depth 0 uint256 a; // depth 1 uint256 b; } ``` #### Example usage ```solidity import "forge-std/Test.sol"; contract TestContract is Test { using stdStorage for StdStorage; Storage test; function setUp() public { test = new Storage(); } function testFindExists() public { // Lets say we want to find the slot for the public // variable `exists`. We just pass in the function selector // to the `find` command uint256 slot = stdstore.target(address(test)).sig("exists()").find(); assertEq(slot, 0); } function testWriteExists() public { // Lets say we want to write to the slot for the public // variable `exists`. We just pass in the function selector // to the `checked_write` command stdstore.target(address(test)).sig("exists()").checked_write(100); assertEq(test.exists(), 100); } // It supports arbitrary storage layouts, like assembly based storage locations function testFindHidden() public { // `hidden` is a random hash of a bytes, iteration through slots would // not find it. Our mechanism does // Also, you can use the selector instead of a string uint256 slot = stdstore.target(address(test)).sig(test.hidden.selector).find(); assertEq(slot, uint256(keccak256("my.random.var"))); } // If targeting a mapping, you have to pass in the keys necessary to perform the find // i.e.: function testFindMapping() public { uint256 slot = stdstore .target(address(test)) .sig(test.map_addr.selector) .with_key(address(this)) .find(); // in the `Storage` constructor, we wrote that this address' value was 1 in the map // so when we load the slot, we expect it to be 1 assertEq(uint(vm.load(address(test), bytes32(slot))), 1); } // If the target is a struct, you can specify the field depth: function testFindStruct() public { // NOTE: see the depth parameter - 0 means 0th field, 1 means 1st field, etc. uint256 slot_for_a_field = stdstore .target(address(test)) .sig(test.basicStruct.selector) .depth(0) .find(); uint256 slot_for_b_field = stdstore .target(address(test)) .sig(test.basicStruct.selector) .depth(1) .find(); assertEq(uint(vm.load(address(test), bytes32(slot_for_a_field))), 1); assertEq(uint(vm.load(address(test), bytes32(slot_for_b_field))), 2); } } // A complex storage contract contract Storage { struct UnpackedStruct { uint256 a; uint256 b; } constructor() { map_addr[msg.sender] = 1; } uint256 public exists = 1; mapping(address => uint256) public map_addr; // mapping(address => Packed) public map_packed; mapping(address => UnpackedStruct) public map_struct; mapping(address => mapping(address => uint256)) public deep_map; mapping(address => mapping(address => UnpackedStruct)) public deep_map_struct; UnpackedStruct public basicStruct = UnpackedStruct({ a: 1, b: 2 }); function hidden() public view returns (bytes32 t) { // an extremely hidden storage slot bytes32 slot = keccak256("my.random.var"); assembly { t := sload(slot) } } } ``` ### stdCheats This is a wrapper over miscellaneous cheatcodes that need wrappers to be more dev friendly. Currently there are only functions related to `prank`. In general, users may expect ETH to be put into an address on `prank`, but this is not the case for safety reasons. Explicitly this `hoax` function should only be used for address that have expected balances as it will get overwritten. If an address already has ETH, you should just use `prank`. If you want to change that balance explicitly, just use `deal`. If you want to do both, `hoax` is also right for you. #### Example usage: ```solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "forge-std/Test.sol"; // Inherit the stdCheats contract StdCheatsTest is Test { Bar test; function setUp() public { test = new Bar(); } function testHoax() public { // we call `hoax`, which gives the target address // eth and then calls `prank` hoax(address(1337)); test.bar{value: 100}(address(1337)); // overloaded to allow you to specify how much eth to // initialize the address with hoax(address(1337), 1); test.bar{value: 1}(address(1337)); } function testStartHoax() public { // we call `startHoax`, which gives the target address // eth and then calls `startPrank` // // it is also overloaded so that you can specify an eth amount startHoax(address(1337)); test.bar{value: 100}(address(1337)); test.bar{value: 100}(address(1337)); vm.stopPrank(); test.bar(address(this)); } } contract Bar { function bar(address expectedSender) public payable { require(msg.sender == expectedSender, "!prank"); } } ``` ### Std Assertions Expand upon the assertion functions from the `DSTest` library. ### `console.log` Usage follows the same format as [Hardhat](https://hardhat.org/hardhat-network/reference/#console-log). It's recommended to use `console2.sol` as shown below, as this will show the decoded logs in Forge traces. ```solidity // import it indirectly via Test.sol import "forge-std/Test.sol"; // or directly import it import "forge-std/console2.sol"; ... console2.log(someValue); ``` If you need compatibility with Hardhat, you must use the standard `console.sol` instead. Due to a bug in `console.sol`, logs that use `uint256` or `int256` types will not be properly decoded in Forge traces. ```solidity // import it indirectly via Test.sol import "forge-std/Test.sol"; // or directly import it import "forge-std/console.sol"; ... console.log(someValue); ``` ## License Forge Standard Library is offered under either [MIT](LICENSE-MIT) or [Apache 2.0](LICENSE-APACHE) license. # Sismo Connect - Onchain Tutorial Repository This repository aims at providing a simple starting codebase to follow the [Sismo Connect - Onchain Tutorial](https://docs.sismo.io/sismo-docs/build-with-sismo-connect/tutorials/onchain-tutorials/tuto). It will help you understand how the [SafeDrop Case Study](https://case-studies.sismo.io/db/safe-drop) has been technically been built. You can also fork the onchain boilerplate that implements this case study with a polished UI by going to [this repository](https://github.com/sismo-core/sismo-connect-boilerplate-onchain). ## Usage ### Prerequisites - [Node.js](https://nodejs.org/en/download/) >= 18.15.0 (Latest LTS version) - [Yarn](https://classic.yarnpkg.com/en/docs/install) - [Foundry](https://book.getfoundry.sh/) ### Clone the repository ```bash git clone https://github.com/sismo-core/sismo-connect-onchain-tutorial cd sismo-connect-onchain-tutorial ``` ### Install contract dependencies ```bash # updates foundry foundryup # install smart contract dependencies forge install ``` ### Launch a local fork chain ```bash # in another terminal # starts a local fork of Mumbai yarn anvil ``` ### Launch the local application You can now launch your local dapp with the commands: ```bash # in another terminal # install frontend dependencies cd front yarn # launch local application yarn dev ``` The frontend is now available on http://localhost:3000/ and the contracts have been deployed on your local blockchain. You can now experiment the user flow by going to your local frontend http://localhost:3000/. ### Deploy your Airdrop contract With a private key, a RPC url and an etherscan api key: ```bash forge script DeployAirdrop \ --rpc-url $RPC_URL \ --private-key "$PRIVATE_KEY" \ --broadcast \ --slow \ --etherscan-api-key "$ETHERSCAN_API_KEY" \ --verify \ --watch ``` With a mnemonic and a sender: ```bash forge script DeployAirdrop \ --rpc-url $RPC_URL \ --mnemonics "$MNEMONIC" \ --sender $SENDER \ --broadcast \ --slow \ --etherscan-api-key "$ETHERSCAN_API_KEY" \ --verify \ --watch ``` ### Run contract tests Sismo Connect contracts are currently deployed on several chains. You can find the deployed addresses [here](https://docs.sismo.io/sismo-docs/knowledge-base/resources/sismo-101). You can then run tests on a local fork network to test your contracts. ```bash ## Run fork tests with goerli forge test --fork-url https://rpc.ankr.com/eth_goerli ## Run fork tests with mumbai forge test --fork-url https://rpc.ankr.com/polygon_mumbai ## Run fork tests with optimism forge test --fork-url https://rpc.ankr.com/optimism # you can aslo use the rpc url you want by passing an environment variable forge test --fork-url $RPC_URL ``` # @council/deploy Scripts for deploying the Council contracts to your network of choice, i.e.: `goerli` or `mainnet`. ## Principles Setting up and deploying the Council contracts is a complex process that requires doing things in a specific order. This project serves to be a reference point for anyone looking to deploy their own version of Council. You might not need every contract provided by Council. Perhaps you don't need a GSC, Treasury, or a specific Voting Vault. You might already have a voting token and don't need to deploy the one provided here. We intend to make this customization process easy with different Recipes for common deployment cases. We also recommend that you deploy your Council contracts to `goerli` first to resolve any issues before going live on `mainnet`. ## Installation 1. Clone the council-monorepo then run, `yarn install`. 2. Run `yarn workspace @council/deploy run load-contracts` to grab the latest contract code 3. Add your environment variables to `packages/council-deploy/.env`. See the `.env.sample` in this project for a template. 4. Run `yarn workspace @council/deploy run build`. ## Deploy contracts Contracts are deployed using the private key of the wallet specified in the `.env` file, see: `GOERLI_DEPLOYER_PRIVATE_KEY`. Once all contracts are deployed, each one will be verified on Etherscan automatically. (Don't forget to add your `ETHERSCAN_API_KEY` to the .env file.) The entire process takes around 10 minutes. This is because some contracts need to interact with other contracts. It also takes a little extra time for Etherscan to index new contracts before they can be verified. ### Goerli: Run: `yarn workspace @council/deploy run goerli:deploy-contracts` ### Mainnet: TBD ## Handy Scripts Either for demo purposes or just general usefulness, there are a handful of CLI scripts that can make life easier when working with the contracts. ### `yarn workspace @council/deploy run goerli:mint-voting-tokens` Prompts for a wallet address and voting token, then mints and transfers a specified amount of tokens. ### `yarn workspace @council/deploy run goerli:deposit-voting-tokens-into-locking-vault` Prompts for a locking vault address, then transfers a specified amount of its voting token from the user's wallet to the vault. If the wallet does not have any of the voting token, it will prompt you to mint some. ## File Structure All code that deploys, verifies, or interacts with the contracts lives under `src/`. When contracts are deployed, The network-specific `*.deployments.json` file under `src/deployments` is updated with the contract deployment information. This file has a strict JSONSchema and typescript types so it can be imported and used safely in other projects. Deployments are checked into the repo since each deployment is unique. Each contract type, (eg: Timelock, Treasury, Voting Vaults) is treated as a separate feature of Council, so each one lives in its own folder containing all the necessary logic to deploy and interact with it. Some contracts like `src/votingToken` are completely decoupled from all other contracts. Others, like `src/vaults/lockingVault` are allowed to import from other folders where it makes sense (In this example, the locking vault needs to know about the votingToken). Deployment of the entire set of Council contracts lives in `src/deployCouncil.ts`. You are encouraged to read the heavily commented code there to better understand how the contracts talk to each other during the deployment process. This is also where you can modify the deployment process based on what makes sense for your needs. ### Note about Proposals If you need to test voting, then make sure you do this step AFTER your account has vote power. To get vote power, deposit some of your tokens to the locking vault through the UI. Contract presets are now deprecated in favor of [Contracts Wizard](https://wizard.openzeppelin.com/) as a more powerful alternative. # ERC4626 Property Tests Foundry (dapptools-style) property-based tests for [ERC4626] standard conformance. [ERC4626]: <https://eips.ethereum.org/EIPS/eip-4626> You can read our post on "_[Generalized property tests for ERC4626 vaults][post]_." [post]: <https://a16zcrypto.com/generalized-property-tests-for-erc4626-vaults> ## Overview #### What is it? - Test suites for checking if the given ERC4626 implementation satisfies the **standard requirements**. - Dapptools-style **property-based tests** for fuzzing or symbolic execution testing. - Tests that are **independent** from implementation details, thus applicable for any ERC4626 vaults. #### What isn’t it? - It does NOT test implementation-specific details, e.g., how to generate and distribute yields, how to compute the share price, etc. #### Testing properties: - **Round-trip properties**: no one can make a free profit by depositing and immediately withdrawing back and forth. - **Functional correctness**: the `deposit()`, `mint()`, `withdraw()`, and `redeem()` functions update the balance and allowance properly. - The `preview{Deposit,Redeem}()` functions **MUST NOT over-estimate** the exact amount.[^1] [^1]: That is, the `deposit()` and `redeem()` functions “MUST return the same or more amounts as their preview function if called in the same transaction.” - The `preview{Mint,Withdraw}()` functions **MUST NOT under-estimate** the exact amount.[^2] [^2]: That is, the `mint()` and `withdraw()` functions “MUST return the same or fewer amounts as their preview function if called in the same transaction.” - The `convertTo{Shares,Assets}` functions “**MUST NOT show any variations** depending on the caller.” - The `asset()`, `totalAssets()`, and `max{Deposit,Mint,Withdraw,Redeem}()` functions “**MUST NOT revert**.” ## Usage **Step 0**: Install [foundry] and add [forge-std] in your vault repo: ```bash $ curl -L https://foundry.paradigm.xyz | bash $ cd /path/to/your-erc4626-vault $ forge install foundry-rs/forge-std ``` [foundry]: <https://getfoundry.sh/> [forge-std]: <https://github.com/foundry-rs/forge-std> **Step 1**: Add this [erc4626-tests] as a dependency to your vault: ```bash $ cd /path/to/your-erc4626-vault $ forge install a16z/erc4626-tests ``` [erc4626-tests]: <https://github.com/a16z/erc4626-tests> **Step 2**: Extend the abstract test contract [`ERC4626Test`](ERC4626.test.sol) with your own custom vault setup method, for example: ```solidity // SPDX-License-Identifier: AGPL-3.0 pragma solidity >=0.8.0 <0.9.0; import "erc4626-tests/ERC4626.test.sol"; import { ERC20Mock } from "/path/to/mocks/ERC20Mock.sol"; import { ERC4626Mock } from "/path/to/mocks/ERC4626Mock.sol"; contract ERC4626StdTest is ERC4626Test { function setUp() public override { _underlying_ = address(new ERC20Mock("Mock ERC20", "MERC20", 18)); _vault_ = address(new ERC4626Mock(ERC20Mock(__underlying__), "Mock ERC4626", "MERC4626")); _delta_ = 0; _vaultMayBeEmpty = false; _unlimitedAmount = false; } } ``` Specifically, set the state variables as follows: - `_vault_`: the address of your ERC4626 vault. - `_underlying_`: the address of the underlying asset of your vault. Note that the default `setupVault()` and `setupYield()` methods of `ERC4626Test` assume that it implements `mint(address to, uint value)` and `burn(address from, uint value)`. You can override the setup methods with your own if such `mint()` and `burn()` are not implemented. - `_delta_`: the maximum approximation error size to be passed to [`assertApproxEqAbs()`]. It must be given as an absolute value (not a percentage) in the smallest unit (e.g., Wei or Satoshi). Note that all the tests are expected to pass with `__delta__ == 0` as long as your vault follows the [preferred rounding direction] as specified in the standard. If your vault doesn't follow the preferred rounding direction, you can set `__delta__` to a reasonable size of rounding errors where the adversarial profit of exploiting such rounding errors stays sufficiently small compared to the gas cost. (You can read our [post] for more about the adversarial profit.) - `_vaultMayBeEmpty`: when set to false, fuzz inputs that empties the vault are ignored. - `_unlimitedAmount`: when set to false, fuzz inputs are restricted to the currently available amount from the caller. Limiting the amount can speed up fuzzing, but may miss some edge cases. [`assertApproxEqAbs()`]: <https://book.getfoundry.sh/reference/forge-std/assertApproxEqAbs> [preferred rounding direction]: <https://eips.ethereum.org/EIPS/eip-4626#security-considerations> **Step 3**: Run `forge test` ``` $ forge test ``` ## Examples Below are examples of adding these property tests to existing ERC4626 vaults: - [OpenZeppelin ERC4626] [[diff](https://github.com/daejunpark/openzeppelin-contracts/pull/1/files)] - [Solmate ERC4626] [[diff](https://github.com/daejunpark/solmate/pull/1/files)] - [Revenue Distribution Token] [[diff](https://github.com/daejunpark/revenue-distribution-token/pull/1/files)] - [Yield Daddy ERC4626 wrappers] [[diff](https://github.com/daejunpark/yield-daddy/pull/1/files)][^bug] [OpenZeppelin ERC4626]: <https://github.com/OpenZeppelin/openzeppelin-contracts/blob/a1948250ab8c441f6d327a65754cb20d2b1b4554/contracts/token/ERC20/extensions/ERC4626.sol> [Solmate ERC4626]: <https://github.com/transmissions11/solmate/blob/c2594bf4635ad773a8f4763e20b7e79582e41535/src/mixins/ERC4626.sol> [Revenue Distribution Token]: <https://github.com/maple-labs/revenue-distribution-token/blob/be9592fd72bfa7142a217507f2d5500a7856329e/contracts/RevenueDistributionToken.sol> [Yield Daddy ERC4626 wrappers]: <https://github.com/timeless-fi/yield-daddy> [^bug]: Our property tests indeed revealed an [issue](https://github.com/timeless-fi/yield-daddy/issues/7) in their eToken testing mock contract. The tests passed after it is [fixed](https://github.com/daejunpark/yield-daddy/commit/721cf4bd766805fd409455434aa5fd1a9b2df25c). ## Disclaimer _These smart contracts are being provided as is. No guarantee, representation or warranty is being made, express or implied, as to the safety or correctness of the user interface or the smart contracts. They have not been audited and as such there can be no assurance they will work as intended, and users may experience delays, failures, errors, omissions or loss of transmitted information. THE SMART CONTRACTS CONTAINED HEREIN ARE FURNISHED AS IS, WHERE IS, WITH ALL FAULTS AND WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING ANY WARRANTY OF MERCHANTABILITY, NON-INFRINGEMENT OR FITNESS FOR ANY PARTICULAR PURPOSE. Further, use of any of these smart contracts may be restricted or prohibited under applicable law, including securities laws, and it is therefore strongly advised for you to contact a reputable attorney in any jurisdiction where these smart contracts may be accessible for any questions or concerns with respect thereto. Further, no information provided in this repo should be construed as investment advice or legal advice for any particular facts or circumstances, and is not meant to replace competent counsel. a16z is not liable for any use of the foregoing, and users should proceed with caution and use at their own risk. See a16z.com/disclosures for more info._ <br /> <div align="center"> <img src="https://static.sismo.io/readme/top-main.png" alt="Logo" width="150" height="150" style="borderRadius: 20px"> <h3 align="center"> Sismo Connect onchain verifier </h3> <p align="center"> Made by <a href="https://docs.sismo.io/" target="_blank">Sismo</a> </p> <p align="center"> <a href="https://discord.gg/sismo" target="_blank"> <img src="https://img.shields.io/badge/Discord-7289DA?style=for-the-badge&logo=discord&logoColor=white"/> </a> <a href="https://twitter.com/sismo_eth" target="_blank"> <img src="https://img.shields.io/badge/Twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white"/> </a> </p> </div> Sismo Connect onchain verifier is a Solidity library that allows you to verify the zk-proofs of your Sismo Connect Application onchain. Here is the link to the full documentation of the library: [Sismo Connect Solidity library](https://docs.sismo.io/sismo-docs/technical-documentation/sismo-connect/solidity-library) You can learn more on Sismo Connect [here](https://docs.sismo.io/sismo-docs/readme/sismo-connect). ## License Distributed under the MIT License. ## Contribute Please, feel free to open issues, PRs or simply provide feedback! ## Contact Prefer [Discord](https://discord.gg/sismo) or [Twitter](https://twitter.com/sismo_eth) <br/> <img src="https://static.sismo.io/readme/bottom-main.png" alt="bottom" width="100%" > # DAO_Managed_Vault # Abstract Permissionless creation of simple interest bearing vaults and strategies. Usable Dapps are necessary on new chains and cross-listing of protocols is beneficial for protocols involved. Yield or interest rate farming via Yearn style vaults and strategies is a common contract system pattern heavily used across the ecosystem and boosts chain TVLs when first launched. We allow a pre-set group of real users (worldcoin/sismo sybil resistant IDs) to create and deploy ERC4626 vaults via a clone function protected by GovernorBravo. # Introduction Imagine a new user on a new chain. They want to earn interest and try new protocols but aren't sure where to start. But there's a good chance they've used yearn on mainnet or beefy on other chains. The DAO managed vault system allows DAO members to permissionlessly deploy new vaults and strategies. A helping hand of sorts for new users to discover new protocols and earn interest. And for slightly more experiemced users to create new vaults with alpha and research on the chain and earn part of the pool interest. # Problems - Difficult to discover new protocols on new chains - Difficult to deploy contracts on new chains sometimes - Non-technical users and investors may have alpha but cannot share it in a profitable manner - No incentives to truly share alpha - Yield bearing protocols can often rug/move tokens on behalf of users # Solutions - Our systems features a simple ERC4626 vault and underlying strategy pairing. - Each vault has just 1 strategy - Real users can create new vaults and strategies using the clone function - This allows for sharing of alpha - Alongside earning part of the yield as incentives The solution allows for faster iteration of yield bearing vaults and permissionless creation even in the absence of core-devs maintaining the protocol. # Impl ![](daoframework.drawio.png) 1. Frontend uses sismo and/or world coin starter kits 2. Sismo connect or idkit is used to verify if a user is real 3. Unique users are allowed to mint a governance token 4. The token is accepted in a Compound GovernorBravo compliant contract to create proposals via Tally/Delv 5. Once the proposal passes, calldata in it is executed, this would typically be of type `clone(...)` which would create new vaults and strategies with different underlying and deposit contracts (Compound / crv) 6. Users could then interact with these new vaults and deposit the given underlying token 7. On deposit/withdraw andSync is called, which reports losses/gains from the strategy to the vault while updating share math accurately 8. Users can withdraw the underlying token + interest at the end of the reward cycle length. Note: Care is and must continue to be taken to ensure safety against ERC4626 inflation attacks. # Projects Incorporated: ### Deployed on - NEAR BOS https://near.org/chimera_defi.near/widget/Daovault - Linea - Polygon zkEVM Polygon Tweet link: https://twitter.com/GoodMorninnnng/status/1672864573362262016?s=20 - Deployment Addresses: - Vault: https://testnet-zkevm.polygonscan.com/address/0x013D706Ff9bdA75C390a4611F512ee61Ecbf9389 - Strategy: https://testnet-zkevm.polygonscan.com/address/0x8a53ca850564ae980bcf43a679d11cfe90fc418b - Vault Token Wrapper: https://testnet-zkevm.polygonscan.com/address/0x60d09097d21Aca152e6825EFEADE395609F6a025 - Vault Governor: https://testnet-zkevm.polygonscan.com/address/0x572c2ea3469917c1f3a072b62a4778d8b39dbd33 - Note: Governance and token wrapper still need to be properly introduced to the vault-strategy pairing. - Goerli - Relevant Address links located: https://www.one-tab.com/page/v5UmgDBvTcWpBYdB8goowA - Gnosis Chiadao ### Using RPC - Quicknode ### Deployed With - Delv ### Credentials Powered By - Sismo - Worldcoin - Apecoin # Dev Docs ## Deployment Stages 1. Deploy new instance of ACTUAL4626 - 0x6637867dF88Ae4a24C090E5B03C6255a1f5b51cE Constructor: Set the underlying, Set the rewards cycle Governor is temporarily set to my EOA Optional: Verify the vault on etherscan. 2. Deploy a strategy - 0x5d309a073505991beDB1cc14Af5C189B092d2104 Constructor: Set the underlying Set the vault to be the ACTUAL2626 addy Optional: Verify the strategy on etherscan. 3. Set the strategy of the Actual4626 to be whatever strategy address is being used. Constructor: Approve the vault on the underlying. Deposit into the vault and receive share tokens. Optional: Call syncRewards on the ACTUAL4626 to simply move assets from the vault into the strategy. 4. Deploy a vaultTokenWrapperFlattened - 0x261ED1EAE1829e18728088cc72C9459cD551AC2F Constructor: Use the ACTUAL4626 Vault receipt token as the underlying token to wrap. Optional: Verify the contract on Etherscan. 5. Approve the vaultTokenWrapperFlattened on the ACTUAL4626. 6. Wrap the vault receipt token into the vault token wrapper by calling depositFor. 7. Deploy vault_governor_flattened Constructor: Set the underlying to be the wrapped vault token. Set the timelock to be 0x00000.....(0x00 address) Verify contract if neccessary 8. Create the governor on tally or Delv using the right addresses n whatnot... 9. Add the given governor to the list of pre-approved governors.... 10. The DAO can then vote to remove the EOA governor from the list. # Photo Album ![Hackathon_Tally_Screenshot](https://github.com/Laser420/DAO_Managed_Vault/assets/38286334/e6f2505a-252e-4389-b027-58dca36558de) Becoming a proper is easy! ![Generate Proof](doc/scr1.png First generate your proof with Sismo connect ![Claiming proposal tokens](doc/scr3.png) Then claim your proposal tokens ![Tokens claimed!](doc/scr2.png) Congrats! You're a proposer now ![Delv mainnet](doc/delv_elfi_remote.png) Delv mainnet Element fi council ![Delv localhost](doc/Delv_local.png) Delv localhost with proposals against vaults/gov bravo # `tsconfig` These are base shared `tsconfig.json`s from which all other `tsconfig.json`'s inherit from. Contract presets are now deprecated in favor of [Contracts Wizard](https://wizard.openzeppelin.com/) as a more powerful alternative. # world-id-onchain-template Template repository for a World ID # council-sdk-starter A reference project with example scripts using the council sdk. - [Installation](#installation) - [Getting started](#getting-started) - [Environment](#environment) - [Starting](#starting) - [Get Proposal Results](#get-proposal-results) - [Get GSC Members](#get-gsc-members) - [Create a Proposal](#create-a-proposal) - [Building](#building) ## Installation The Council SDK isn't currently available as a stand alone package but can be installed within the council monorepo. 1. Clone the council-monorepo. 2. Add `"@council/sdk": "*"` to the app or package's package.json. 3. Run install: `yarn`. ## Getting started ### Environment Create your own `.env`. An example template is included in the project in `.env.example`. Provide an RPC url and a private key to sign and pay for transactions. ### Starting Multiple example scripts are included in [`src/scripts`](src/scripts). Each one has a corresponding npm script to run it. #### Get Proposal Results ``` yarn workspace council-sdk-start getProposalResults ``` #### Get GSC Members ``` yarn workspace council-sdk-start getGSCMembers ``` #### Create a Proposal _Caution! this will require paying gas._ ``` yarn workspace council-sdk-start createProposal ``` ### Building ```bash yarn workspace council-sdk-starter build ``` ![Council Kit Logo](https://i.imgur.com/2n9k3Rv.png) # Council-Kit Council kit is the complete toolkit for scaffolding your own DAO using the council protocol. This repository is designed to be forkable for your own council protocol variant. Get started with the [Docs](https://github.com/delvtech/council-kit/wiki). Requires `Node 14+`. ## What's inside? This monorepo uses [Yarn](https://classic.yarnpkg.com/) as a package manager. It includes the following packages/apps: ### Apps | Name | Description | | --------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- | | [council-ui](https://github.com/delvtech/council-kit/tree/main/apps/council-ui) | A reference user interface built with NextJS and using the SDK. | | [council-sdk-starter](https://github.com/delvtech/council-kit/tree/main/apps/council-sdk-starter) | A boilerplate TypeScript project that uses the SDK. | ### Packages | Name | Description | | --------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | | [council-sdk](https://github.com/delvtech/council-kit/tree/main/packages/council-sdk) | A TypeScript SDK for interfacing with the Council protocol. | | [council-deploy](https://github.com/delvtech/council-kit/tree/main/packages/council-deploy) | A template for deploying council contracts on Goerli. | | [council-typechain](https://github.com/delvtech/council-kit/tree/main/packages/council-typechain) | Type classes generated from the council protocol contracts using Typechain. | ### Utility Packages | Name | Description | | ----------------------------------------------------------------------------------------------- | ------------------------------------ | | [eslint-config](https://github.com/delvtech/council-kit/tree/main/packages/eslint-config) | Package for static type checking. | | [prettier-config](https://github.com/delvtech/council-kit/tree/main/packages/prettier-config) | Package for code formatting. | | [tsconfig](https://github.com/delvtech/council-kit/tree/main/packages/tsconfig) | Package for TypeScript configuation. | Each package/app is 100% [TypeScript](https://www.typescriptlang.org/). ## Monorepo commands ### Build To build all apps and packages, run the following command: ```bash yarn build # build only packages (useful for app development) yarn build:packages ``` ### Develop To run the development server for all apps, run the following command: ```bash yarn dev ``` ### Linting To run linting on all apps and packages, run the following command: ```bash yarn lint ``` ### Formatting To run formatting on all apps and packages, run the following command: ```bash yarn format:check # write formatting changes to files yarn format ``` ## Development 1. Clone the repo: `git clone git@github.com:delvtech/council-kit.git` 2. Run `yarn` at the top-level to install all packages across every workspace ### Installing new packages Here are a few examples of how to install packages in this repo: ```bash # Install prettier for the top-level package.json, useful for tooling that # runs against the entire monorepo yarn add prettier # Install lodash for the packages/council-sdk workspace. # Note: specify the workspace by the name in its `package.json`, ie: `@council/sdk` not `council-sdk` yarn workspace @council/sdk add lodash ``` ### Installing a workspace package To install a project from the packages/ directory as a dependency, copy it directly into your app package.json like this, then run `yarn`. ```json { "dependencies": { "@council/sdk": "*", "@council/typechain": "*" } } ``` ### Running workspace scripts To run scripts in workspaces, use the following command: ```bash yarn workspace <workspace-name> <package.json script> ``` Example ```bash yarn workspace council-ui start ``` ## Turborepo This package uses the [turborepo](https://turbo.build/) monorepo framework. Turborepo provides additional features compared to a plain monorepo such as local/remote command caching and parallel npm script execution. ### Remote Caching Turborepo can use a technique known as [Remote Caching](https://turborepo.org/docs/core-concepts/remote-caching) to share cache artifacts across machines, enabling you to share build caches with your team and CI/CD pipelines. By default, Turborepo will cache locally. To enable Remote Caching you will need an account with Vercel. If you don't have an account you can [create one](https://vercel.com/signup), then enter the following commands: ``` cd my-turborepo npx turbo login ``` This will authenticate the Turborepo CLI with your [Vercel account](https://vercel.com/docs/concepts/personal-accounts/overview). Next, you can link your Turborepo to your Remote Cache by running the following command from the root of your turborepo: ``` npx turbo link ``` ### Resources Learn more about the power of Turborepo: - [Pipelines](https://turborepo.org/docs/core-concepts/pipelines) - [Caching](https://turborepo.org/docs/core-concepts/caching) - [Remote Caching](https://turborepo.org/docs/core-concepts/remote-caching) - [Scoped Tasks](https://turborepo.org/docs/core-concepts/scopes) - [Configuration Options](https://turborepo.org/docs/reference/configuration) - [CLI Usage](https://turborepo.org/docs/reference/command-line-reference) # <img src="logo.svg" alt="OpenZeppelin" height="40px"> [![NPM Package](https://img.shields.io/npm/v/@openzeppelin/contracts.svg)](https://www.npmjs.org/package/@openzeppelin/contracts) [![Coverage Status](https://codecov.io/gh/OpenZeppelin/openzeppelin-contracts/graph/badge.svg)](https://codecov.io/gh/OpenZeppelin/openzeppelin-contracts) [![GitPOAPs](https://public-api.gitpoap.io/v1/repo/OpenZeppelin/openzeppelin-contracts/badge)](https://www.gitpoap.io/gh/OpenZeppelin/openzeppelin-contracts) [![Docs](https://img.shields.io/badge/docs-%F0%9F%93%84-yellow)](https://docs.openzeppelin.com/contracts) [![Forum](https://img.shields.io/badge/forum-%F0%9F%92%AC-yellow)](https://docs.openzeppelin.com/contracts) **A library for secure smart contract development.** Build on a solid foundation of community-vetted code. * Implementations of standards like [ERC20](https://docs.openzeppelin.com/contracts/erc20) and [ERC721](https://docs.openzeppelin.com/contracts/erc721). * Flexible [role-based permissioning](https://docs.openzeppelin.com/contracts/access-control) scheme. * Reusable [Solidity components](https://docs.openzeppelin.com/contracts/utilities) to build custom contracts and complex decentralized systems. :mage: **Not sure how to get started?** Check out [Contracts Wizard](https://wizard.openzeppelin.com/) — an interactive smart contract generator. :building_construction: **Want to scale your decentralized application?** Check out [OpenZeppelin Defender](https://openzeppelin.com/defender) — a secure platform for automating and monitoring your operations. ## Overview ### Installation ``` $ npm install @openzeppelin/contracts ``` OpenZeppelin Contracts features a [stable API](https://docs.openzeppelin.com/contracts/releases-stability#api-stability), which means that your contracts won't break unexpectedly when upgrading to a newer minor version. An alternative to npm is to use the GitHub repository (`openzeppelin/openzeppelin-contracts`) to retrieve the contracts. When doing this, make sure to specify the tag for a release such as `v4.5.0`, instead of using the `master` branch. ### Usage Once installed, you can use the contracts in the library by importing them: ```solidity pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; contract MyCollectible is ERC721 { constructor() ERC721("MyCollectible", "MCO") { } } ``` _If you're new to smart contract development, head to [Developing Smart Contracts](https://docs.openzeppelin.com/learn/developing-smart-contracts) to learn about creating a new project and compiling your contracts._ To keep your system secure, you should **always** use the installed code as-is, and neither copy-paste it from online sources nor modify it yourself. The library is designed so that only the contracts and functions you use are deployed, so you don't need to worry about it needlessly increasing gas costs. ## Learn More The guides in the [documentation site](https://docs.openzeppelin.com/contracts) will teach about different concepts, and how to use the related contracts that OpenZeppelin Contracts provides: * [Access Control](https://docs.openzeppelin.com/contracts/access-control): decide who can perform each of the actions on your system. * [Tokens](https://docs.openzeppelin.com/contracts/tokens): create tradeable assets or collectives, and distribute them via [Crowdsales](https://docs.openzeppelin.com/contracts/crowdsales). * [Utilities](https://docs.openzeppelin.com/contracts/utilities): generic useful tools including non-overflowing math, signature verification, and trustless paying systems. The [full API](https://docs.openzeppelin.com/contracts/api/token/ERC20) is also thoroughly documented, and serves as a great reference when developing your smart contract application. You can also ask for help or follow Contracts's development in the [community forum](https://forum.openzeppelin.com). Finally, you may want to take a look at the [guides on our blog](https://blog.openzeppelin.com/guides), which cover several common use cases and good practices. The following articles provide great background reading, though please note that some of the referenced tools have changed, as the tooling in the ecosystem continues to rapidly evolve. * [The Hitchhiker’s Guide to Smart Contracts in Ethereum](https://blog.openzeppelin.com/the-hitchhikers-guide-to-smart-contracts-in-ethereum-848f08001f05) will help you get an overview of the various tools available for smart contract development, and help you set up your environment. * [A Gentle Introduction to Ethereum Programming, Part 1](https://blog.openzeppelin.com/a-gentle-introduction-to-ethereum-programming-part-1-783cc7796094) provides very useful information on an introductory level, including many basic concepts from the Ethereum platform. * For a more in-depth dive, you may read the guide [Designing the Architecture for Your Ethereum Application](https://blog.openzeppelin.com/designing-the-architecture-for-your-ethereum-application-9cec086f8317), which discusses how to better structure your application and its relationship to the real world. ## Security This project is maintained by [OpenZeppelin](https://openzeppelin.com) with the goal of providing a secure and reliable library of smart contract components for the ecosystem. We address security through risk management in various areas such as engineering and open source best practices, scoping and API design, multi-layered review processes, and incident response preparedness. The security policy is detailed in [`SECURITY.md`](./SECURITY.md), and specifies how you can report security vulnerabilities, which versions will receive security patches, and how to stay informed about them. We run a [bug bounty program on Immunefi](https://immunefi.com/bounty/openzeppelin) to reward the responsible disclosure of vulnerabilities. The engineering guidelines we follow to promote project quality can be found in [`GUIDELINES.md`](./GUIDELINES.md). Past audits can be found in [`audits/`](./audits). Smart contracts are a nascent technology and carry a high level of technical risk and uncertainty. Although OpenZeppelin is well known for its security audits, using OpenZeppelin Contracts is not a substitute for a security audit. OpenZeppelin Contracts is made available under the MIT License, which disclaims all warranties in relation to the project and which limits the liability of those that contribute and maintain the project, including OpenZeppelin. As set out further in the Terms, you acknowledge that you are solely responsible for any use of OpenZeppelin Contracts and you assume all risks associated with any such use. ## Contribute OpenZeppelin Contracts exists thanks to its contributors. There are many ways you can participate and help build high quality software. Check out the [contribution guide](CONTRIBUTING.md)! ## License OpenZeppelin Contracts is released under the [MIT License](LICENSE). ## Legal Your use of this Project is governed by the terms found at www.openzeppelin.com/tos (the "Terms"). # Council SDK A TypeScript SDK built with [ethers v5](https://docs.ethers.org/v5/) for interfacing with the [Council protocol](https://github.com/delvtech/council). > _[Ethers v6](https://docs.ethers.org/v6/) and/or [viem](https://github.com/wagmi-dev/viem) support TBD soon._ - [Installation](#installation) - [Basic Usage](#basic-usage) - [Primary Concepts](#primary-concepts) - [Models](#models) - [Data Sources](#data-sources) - [Context](#context) - [Utils](#utils) - [Extending](#extending) - [Adding a new Voting Vault](#adding-a-new-voting-vault) - [Reference](#reference) - [Models](#models-1) - [Data Sources](#data-sources-1) - [Context](#context-1) - [Utils](#utils-1) ## Installation The Council SDK isn't currently available as a stand alone package but can be installed within the council monorepo. 1. Clone the council-monorepo. 2. Add `"@council/sdk": "*"` to the app or package's package.json. 3. Run install: `yarn`. ## Basic Usage ```ts import { providers } from "ethers"; import { CouncilContext, VotingContract } from "@council/sdk"; const provider = new providers.JsonRpcProvider("http://localhost:8545"); // 1. Create a new context instance const context = new CouncilContext(provider); // 2. Create model instances const coreVoting = new VotingContract("0x0...", [], context); // 3. Call methods on the models const aliceVotes = coreVoting.getVotes("0x..."); ``` ## Primary Concepts The SDK is made up of 4 main concepts: - [Models](#models) - [Data Sources](#data-sources) - [Context](#context) - [Utils (utilities)](#utils) ### Models Models are the primary interface for the SDK. They're JavaScript classes that represent specific entities within Council and include methods on them to fetch data and submit transactions. When possible, these data fetching methods will return other models. For example, fetching a proposal from a `VotingContract` model will return a new `Proposal` model instance with it's own methods. This makes it easy to work with return values rather than just returning addresses or ids like you might expect from an API. ```ts // initiates a new VotingContract Model instance const coreVoting = new VotingContract("0x0...", [], context); // returns a new Proposal Model instance const proposal0 = await coreVoting.getProposal(0); // returns a plain string since there is no model for Quorum. const quorum = await proposal.getCurrentQuorum(); ``` For more info, checkout the [Models reference](#models-1). ### Data Sources Data sources are JavaScript classes that act as an interchangeable data access layer for the models. They handle querying and caching logic so the models can just focus on defining the shape of Council entities and their relationships. As an SDK user, you'll likely never touch the data sources directly. A basic data source takes arguments from a model, fetches and caches on-chain data, and returns it to the model for any further transformations or model construction. Data sources return basic values and objects. They'll never return other data sources or models (class instances). ```ts const coreVoting = new CoreVotingContractDataSource("0x...", context); // returns a plain JavaScript object of data from the contract const proposal = await coreVoting.getProposal(0); ``` For more info, checkout the [DataSources reference](#data-sources-1). ### Context The [`CouncilContext`](docs/classes/CouncilContext.md) stores common information used in model and data source methods including shared data sources and their cache. It also includes a couple utility methods for getting and registering new shared data sources. As an SDK user, you likely won't call any methods on the context. You'll just construct the Context and pass it to new Models. ```ts const context = new CouncilContext(provider); ``` For more info, checkout the [CouncilContext reference](docs/classes//CouncilContext.md). ### Utils Utils are functions for common operations performed when building with the Council SDK. ```ts // Turn a block number into a Date object with the getBlockDate util. const blockDate = getBlockDate(minedBlockNumber, provider); // Estimate future dates (e.g., expiration dates) with the estimateFutureDates option. const estimatedDate = getBlockDate(futureBlockNumber, provider, { estimateFutureDates: true, }); ``` For more info, checkout the [Utils reference](#utils-1). ## Extending The Council SDK is purpose built to be extended and modified in a number of ways. Some examples of what you could do: - Initiate models with a custom data source - Add new model variations (e.g., new vault types) - Extend existing models with custom properties or methods - Modify the way context manages shared data sources. The Council Kit monorepo is a great starting point to get all the src code including packages that haven't been published to a registry yet. However, making modifications directly to the source code can make it difficult to upgrade to newer versions. Extensions should be made either in a new package such as `@myprotocol/council-vaults` or inside app code. Once version 1.0.0 of the sdk has been published to NPM, this package can be removed from the monorepo and the version updated in dependent apps and packages from `*` to `^1.0.0`. ### Adding a new Voting Vault For this guide we'll assume you've already generated an [ethers v5 typechain](https://github.com/dethcrypto/TypeChain/tree/@typechain/ethers-v5@10.2.0/packages/target-ethers-v5) instances for your voting vault. See [@council/typechain](https://github.com/delvtech/council-kit/tree/main/packages/council-typechain) for an example. **1. Create a new DataSource class** To fetch data from the custom vault, add a new `DataSource` class for it. ```ts import { FooVault, FooVault__factory } from "@foo/typechain"; import { CouncilContext, VotingVaultContractDataSource } from "@council/sdk"; // Extend the `VotingVaultContractDataSource` class to get data from on chain // and inherit the `queryVotePower` method. export class FooVaultDataSource extends VotingVaultContractDataSource<FooVault> { constructor(address: string, context: CouncilContext) { super(FooVault__factory.connect(address, context.provider), context); } // Add some custom data fetching methods taking advantage of util methods on // the super class like `this.call()` and `this.getEvents()` getAmount(address: string) { const [amount, delegate] = this.call("amount", [address]); return { amount: amount.toString(), delegate, }; } } ``` **2. Create the Model class** Create a new `Model` class to transform some values into other `Model` instances and make it possible to initiate many model instances in different parts of the code that will all share the same data source instance and its cached data. ```ts import { Voter } from "@council.typechain"; import { FooVaultDataSouce } from "./FooVaultDataSouce"; export class FooVault extends VotingVault<FooVaultDataSource> { constructor(address: string, context: CouncilContext) { super(address, context, { name: "Foo Vault", dataSource: context.registerDataSource( { address }, new FooVaultDataSource(address, context), ), }); } // add some methods to use in an app async getAmount() { const { amount, delegate } = this.dataSource.getAmount(); return { amount, delegate: new Voter(delegate, this.context.provider), }; } } ``` ## Reference ### Models - [`VotingContract`](docs/classes/VotingContract.md) - [`GSCVotingContract`](docs/classes/GSCVotingContract.md) - [`VotingVault`](docs/classes/VotingVault.md) - [`LockingVault`](docs/classes/LockingVault.md) - [`VestingVault`](docs/classes/VestingVault.md) - [`GSCVault`](docs/classes/GSCVault.md) - [`Proposal`](docs/classes/Proposal.md) - [`Token`](docs/classes/Token.md) - [`Vote`](docs/classes/Vote.md) - [`Voter`](docs/classes/Voter.md) ### Data Sources - [`CachedDataSource`](docs/classes/CachedDataSource.md) - [`ContractDataSource`](docs/classes/ContractDataSource.md) - [`CoreVotingContractDataSource`](docs/classes/CoreVotingContractDataSource.md) - [`VotingVaultContractDataSource`](docs/classes/VotingVaultContractDataSource.md) - [`LockingVaultContractDataSource`](docs/classes/LockingVaultContractDataSource.md) - [`VestingVaultContractDataSource`](docs/classes/VestingVaultContractDataSource.md) - [`GSCVaultContractDataSource`](docs/classes/GSCVaultContractDataSource.md) - [`ERC20ContractDataSource`](docs/classes/ERC20ContractDataSource.md) - [`HTTPDataSource`](docs/classes/HTTPDataSource.md) ### Context - [`CouncilContext`](docs/classes//CouncilContext.md) ### Utils - [`cached`](docs/modules.md#cached) - [`cachedKey`](docs/modules.md#cachedkey) - [`getBlockDate`](docs/modules.md#getblockdate) - [`sumStrings`](docs/modules.md#sumstrings)
GiselleNessi_crea
.github workflows tests.yml .gitpod.yml README.md contract Cargo.toml README.md build.sh deploy.sh src lib.rs target .rustc_info.json release .fingerprint Inflector-10c620bdb7f37e48 lib-inflector.json ahash-c8d1118186e94544 build-script-build-script-build.json borsh-derive-aad49e72430898a0 lib-borsh-derive.json borsh-derive-internal-cb8a258ca9dbd655 lib-borsh-derive-internal.json borsh-schema-derive-internal-0d2777bd5b06fa33 lib-borsh-schema-derive-internal.json crunchy-91f9799fc0f4bbc6 build-script-build-script-build.json near-sdk-macros-ce1f6d812e9eb4df lib-near-sdk-macros.json proc-macro-crate-9f6a1dcfa4d4c161 lib-proc-macro-crate.json proc-macro2-1f5afd6948926129 run-build-script-build-script-build.json proc-macro2-3fc1d4604bc39d56 build-script-build-script-build.json proc-macro2-e1c0ceae7251e579 lib-proc-macro2.json quote-23c77dad18de56ed lib-quote.json quote-4098c42be8913518 build-script-build-script-build.json quote-99d016a09feb7fdd run-build-script-build-script-build.json serde-3bf61c8c1429a23a lib-serde.json serde-4542faf6c2e2e18c build-script-build-script-build.json serde-627dfb6b8ea1f978 run-build-script-build-script-build.json serde-d21d2dc39185a01a build-script-build-script-build.json serde_derive-0165a136f1aaa9c3 build-script-build-script-build.json serde_derive-72d4d40a0b967dde run-build-script-build-script-build.json serde_derive-c28c8d6a11806050 lib-serde_derive.json serde_json-be8c1d7e067c8e17 build-script-build-script-build.json syn-36ff0495092a7c5b build-script-build-script-build.json syn-5af822a10800774d run-build-script-build-script-build.json syn-ccf5ce15868252b2 lib-syn.json toml-2a556e9fe39ee8d6 lib-toml.json unicode-ident-de8e9009b3acaae4 lib-unicode-ident.json version_check-049d01f041e9a22c lib-version_check.json wee_alloc-630d18744a8e9cfb build-script-build-script-build.json wasm32-unknown-unknown release .fingerprint ahash-299f5e501475e162 run-build-script-build-script-build.json ahash-4f5ab85216a522a0 lib-ahash.json base64-47b3a42f4999b6f0 lib-base64.json borsh-fbb5ec9639452911 lib-borsh.json bs58-819701bbd83b5d13 lib-bs58.json byteorder-f93b4ec619cebd2f lib-byteorder.json cfg-if-34376ad3f7a54b93 lib-cfg-if.json contract-90b1a6f00cb41a14 lib-contract.json crunchy-9fe105036f3e22da run-build-script-build-script-build.json crunchy-c24c4e6a381d34d3 lib-crunchy.json hashbrown-dbb25048bc3bb29d lib-hashbrown.json hex-983b4369bec67dc9 lib-hex.json itoa-a9148f56e4eabfc3 lib-itoa.json memory_units-ec5a7b8a5f807132 lib-memory_units.json near-sdk-65836db701eeb8fd lib-near-sdk.json near-sys-02ca2383815920c7 lib-near-sys.json once_cell-e5dbbf95cdff4edd lib-once_cell.json ryu-3e18064c74dcb5b6 lib-ryu.json serde-778c3281145c910c run-build-script-build-script-build.json serde-79367a7338ea08b6 lib-serde.json serde_json-02888c933f962a05 lib-serde_json.json serde_json-054d97b577e83087 run-build-script-build-script-build.json static_assertions-5aab06e8fe197e08 lib-static_assertions.json uint-ebdd76e18cd5c708 lib-uint.json wee_alloc-7b320e4c3c819f24 run-build-script-build-script-build.json wee_alloc-90febd77b5e64bbc lib-wee_alloc.json frontend assets global.css 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
# Count on NEAR 🧮 [![](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/counter-rust) [![](https://img.shields.io/badge/Contract-rust-red)](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) Count on NEAR is a decentralized app that stores a simple counter, enabling to increment, decrement and reset it. ![](https://docs.near.org/assets/images/count-on-near-banner-2df2978ef988be400aafd5e0f99878be.png) # What This Example Shows 1. How to store, modify and retrieve information in the NEAR network. 2. How to integrate a smart contract in a web frontend. <br /> # Quickstart Clone this repository locally or [**open it in gitpod**](https://gitpod.io/#/github.com/near-examples/counter-rust). 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). # Count on NEAR Contract The smart contract exposes methods to interact with a counter stored in the NEAR network. ```rust // Public read-only method: Returns the counter value. pub fn get_num(&self) -> i8 { return self.val; } // Public method: Increment the counter. pub fn increment(&mut self) { self.val += 1; log!("Increased number to {}", self.val); } // Public method: Decrement the counter. pub fn decrement(&mut self) { self.val -= 1; log!("Decreased number to {}", self.val); } // Public method - Reset to zero. pub fn reset(&mut self) { self.val = 0; log!("Reset counter to zero"); } ``` <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. Get the Counter `get_num` 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 counter value near view <dev-account> get_num ``` <br /> ## 3. Modify the Counter `increment`, `decrement` and `reset` change the contract's state, for which they are `call` methods. `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 increment the counter near call <dev-account> increment --accountId <dev-account> ``` **Tip:** If you would like to call `increment` 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_wasmer
.cargo config.toml .github ISSUE_TEMPLATE ---bug-report.md ---feature-request.md --question.md BOUNTY.yml codecov.yml pull_request_template.md stale.yml .tarpaulin.toml ATTRIBUTIONS.md LLVM Exceptions to the Apache 2.0 License CHANGELOG.md CODE_OF_CONDUCT.md CONTRIBUTING.md Cargo.toml PACKAGING.md README.md SECURITY.md Xargo.toml assets README.md diagrams Diagram_module_compilation.svg Diagram_module_instantiation.svg Diagram_module_serialization.svg languages c.svg cpp.svg crystal.svg csharp.svg d.svg dart.svg elixir.svg go.svg java.svg js.svg lisp.svg php.svg postgres.svg python.svg r.svg ruby.svg rust.svg swift.svg benches README.md many_functions.rs static_and_dynamic_functions.rs bors.toml build.rs deny.toml docs README.md cn README.md de README.md deps_dedup.svg es README.md fr README.md ja README.md ko README.md migration_to_1.0.0.md examples README.md compiler_cranelift.rs compiler_llvm.rs compiler_singlepass.rs early_exit.rs engine_cross_compilation.rs engine_headless.rs engine_universal.rs errors.rs exports_function.rs exports_global.rs exports_memory.rs features.rs hello_world.rs imports_exports.rs imports_function.rs imports_function_env.rs imports_global.rs instance.rs memory.rs metering.rs platform_ios_headless.rs table.rs tunables_limit_memory.rs fuzz Cargo.toml README.md fuzz_targets deterministic.rs equivalence_universal.rs metering.rs universal_cranelift.rs universal_llvm.rs universal_singlepass.rs lib README.md api Cargo.toml README.md src lib.rs sys cell.rs env.rs exports.rs externals function.rs global.rs memory.rs mod.rs table.rs import_object.rs instance.rs mod.rs module.rs native.rs ptr.rs store.rs tunables.rs types.rs utils.rs tests sys_export.rs sys_externals.rs sys_instance.rs sys_module.rs sys_reference_types.rs cli Cargo.toml README.md build.rs src bin wasmer.rs wasmer_headless.rs c_gen mod.rs staticlib_header.rs cli.rs commands.rs commands binfmt.rs cache.rs compile.rs config.rs create_exe.rs inspect.rs run.rs self_update.rs validate.rs wasmer_create_exe_main.c wast.rs common.rs compilers llvm.rs error.rs lib.rs logging.rs store.rs suggestions.rs utils.rs compiler-cranelift Cargo.toml README.md build.rs src address_map.rs compiler.rs config.rs debug address_map.rs mod.rs dwarf.rs func_environ.rs lib.rs sink.rs trampoline dynamic_function.rs function_call.rs mod.rs translator code_translator.rs func_environ.rs func_state.rs func_translator.rs mod.rs translation_utils.rs unwind.rs compiler-llvm Cargo.toml README.md src abi aarch64_systemv.rs mod.rs x86_64_systemv.rs compiler.rs config.rs lib.rs object_file.rs trampoline mod.rs wasm.rs translator code.rs intrinsics.rs mod.rs stackmap.rs state.rs compiler-singlepass Cargo.toml README.md src address_map.rs codegen_x64.rs compiler.rs config.rs emitter_x64.rs lib.rs machine.rs x64_decl.rs compiler Cargo.toml README.md src address_map.rs compiler.rs error.rs function.rs jump_table.rs lib.rs module.rs relocation.rs section.rs sourceloc.rs target.rs translator environ.rs error.rs mod.rs module.rs sections.rs state.rs trap.rs unwind.rs derive Cargo.toml src lib.rs parse.rs tests basic.rs compile-fail bad-attribute.rs bad-export-arg.rs no-lazy-init.rs compiletest.rs engine-universal Cargo.toml README.md src artifact.rs builder.rs code_memory.rs engine.rs executable.rs lib.rs link.rs unwind dummy.rs mod.rs systemv.rs windows_x64.rs engine Cargo.toml README.md src engine.rs error.rs executable.rs export.rs lib.rs resolver.rs trap error.rs frame_info.rs mod.rs types Cargo.toml README.md src archives.rs entity boxed_slice.rs iter.rs keys.rs mod.rs packed_option.rs primary_map.rs secondary_map.rs extern_ref.rs features.rs indexes.rs initializers.rs lib.rs memory_view.rs module.rs native.rs types.rs units.rs values.rs vm Cargo.toml README.md build.rs src artifact.rs export.rs func_data_registry.rs global.rs imports.rs instance allocator.rs mod.rs ref.rs lib.rs libcalls.rs memory.rs mmap.rs probestack.rs resolver.rs sig_registry.rs table.rs trap handlers.c mod.rs trapcode.rs traphandlers.rs tunables.rs vmcontext.rs vmoffsets.rs scripts publish.py update-version.sh windows-installer wax.cmd tests compilers compilation.rs config.rs deterministic.rs fast_gas_metering.rs imports.rs issues.rs main.rs multi_value_imports.rs native_functions.rs serialize.rs stack_limiter.rs traps.rs wast.rs deprecated.rs deprecated README.md ignores.txt integration README.md cli Cargo.toml src assets.rs lib.rs link_code.rs util.rs tests compile.rs create_exe.rs run.rs staticlib_engine_test_c_source.c version.rs ios Cargo.toml DylibExample DylibExample AppDelegate.swift Assets.xcassets AccentColor.colorset Contents.json AppIcon.appiconset Contents.json Contents.json DylibExample-Bridging-Header.h SceneDelegate.swift ViewController.swift calc.cpp calc.h DylibExampleTests DylibExampleTests.swift tests dylib.rs lib README.md compiler-test-derive Cargo.toml build.rs src ignores.rs lib.rs tests.rs test-generator Cargo.toml src lib.rs processors.rs wast Cargo.toml README.md src error.rs lib.rs spectest.rs wast.rs wast README.md spec Contributing.md README.md extract-parts.sh repos README.md update-testsuite.sh wasmer README.md
<div align="center"> <a href="https://wasmer.io" target="_blank" rel="noopener noreferrer"> <img width="300" src="https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/logo.png" alt="Wasmer logo"> </a> <p> <a href="https://github.com/wasmerio/wasmer/actions?query=workflow%3Abuild"> <img src="https://github.com/wasmerio/wasmer/workflows/build/badge.svg?style=flat-square" alt="Build Status"> </a> <a href="https://github.com/wasmerio/wasmer/blob/master/LICENSE"> <img src="https://img.shields.io/github/license/wasmerio/wasmer.svg" alt="License"> </a> <a href="https://docs.wasmer.io"> <img src="https://img.shields.io/static/v1?label=Docs&message=docs.wasmer.io&color=blue" alt="Wasmer Docs"> </a> <a href="https://slack.wasmer.io"> <img src="https://img.shields.io/static/v1?label=Slack&message=join%20us!&color=brighgreen" alt="Slack channel"> </a> </p> </div> <br /> Wasmer는 _초경량 컨테이너_ 를 *Desktop*에서부터 *Cloud*, *Edge*, *IoT* 기기들까지 어디에서나 실행할 수 있는 _빠르고 안전한_ [**WebAssembly**](https://webassembly.org) 런타임 입니다. > _이 문서는 아래와 같은 언어들을 지원합니다.: [🇨🇳 中 文 -Chinese](https://github.com/wasmerio/wasmer/blob/master/docs/cn/README.md) • [🇩🇪 Deutsch-German](https://github.com/wasmerio/wasmer/blob/master/docs/de/README.md) • [🇪🇸 Español-Spanish](https://github.com/wasmerio/wasmer/blob/master/docs/es/README.md) • [🇫🇷 Français-French](https://github.com/wasmerio/wasmer/blob/master/docs/fr/README.md) • [🇯🇵 日本 語 -Japanese](https://github.com/wasmerio/wasmer/blob/master/docs/ja/README.md)_. [🇰🇷 한국어 -Korean](https://github.com/wasmerio/wasmer/blob/master/docs/ko/README.md)_. ### 특징 * 기본적으로 안전합니다. 파일, 네트워크, 환경 접근이 명시적으로 활성화 되지 않습니다. * [WASI](https://github.com/WebAssembly/WASI)와 [Emscripten](https://emscripten.org/)을 즉시 지원합니다. * 빠릅니다. native에 가까운 속도로 WebAssembly를 실행합니다. * [여러 프로그래밍 언어](https://github.com/wasmerio/wasmer/#-language-integrations)에 임베디드 가능합니다. * 최신 WebAssembly 제안(SIMD, Reference Types, Threads, ...)을 준수합니다. ### 설치 Wasmer CLI는 종속성이 없는 단일 실행 파일로 제공됩니다. ```sh curl https://get.wasmer.io -sSfL | sh ``` <details> <summary>다른 설치 옵션 (Powershell, Brew, Cargo, ...)</summary> _Wasmer는 다양한 패키지 매니저를 통해 설치 할 수 있습니다. 환경에 가장 적합한 것을 선택하십시오.:_ * Powershell (Windows) ```powershell iwr https://win.wasmer.io -useb | iex ``` * <a href="https://formulae.brew.sh/formula/wasmer">Homebrew</a> (macOS, Linux) ```sh brew install wasmer ``` * <a href="https://github.com/ScoopInstaller/Main/blob/master/bucket/wasmer.json">Scoop</a> (Windows) ```sh scoop install wasmer ``` * <a href="https://chocolatey.org/packages/wasmer">Chocolatey</a> (Windows) ```sh choco install wasmer ``` * <a href="https://crates.io/crates/wasmer-cli/">Cargo</a> _Note: 사용 가능한 모든 기능은 [`wasmer-cli` crate docs](https://github.com/wasmerio/wasmer/tree/master/lib/cli/README.md) 문서에 설명되어 있습니다._ ```sh cargo install wasmer-cli ``` > 더 많은 설치 옵션을 찾고 계십니까? 자세한 내용은 [the `wasmer-install` repository](https://github.com/wasmerio/wasmer-install)를 참조하십시오! </details> ### 빠른 시작 WebAssembly 모듈([`qjs.wasm`](https://registry-cdn.wapm.io/contents/_/quickjs/0.0.3/build/qjs.wasm))로 컴파일된 작고 포함 가능한 Javascript 엔진인 [QuickJS](https://github.com/bellard/quickjs/)를 실행하여 시작할 수 있습니다.: ```bash $ wasmer qjs.wasm QuickJS - Type "\h" for help qjs > const i = 1 + 2; qjs > console.log("hello " + i); hello 3 ``` #### 다음에 할 수 있는 일 : - [어플리케이션에서 wasmer 사용](https://docs.wasmer.io/integrations/rust) - [WAPM에 wasm 패키지 게시](https://docs.wasmer.io/ecosystem/wapm/publishing-your-package) - [Wasmer에 대해 자세히 알아보기](https://medium.com/wasmer/) ## 📦 다른 언어와의 통합 Wasmer 런타임은 **다른 언어에 내장된** 라이브러리로 사용할 수 있으므로 _어디에서나_ WebAssembly를 사용할 수 있습니다. | | Language | Package | Documentation | |-|-|-|-| | ![Rust logo] | [**Rust**][Rust integration] | [`wasmer` Rust crate] | [Learn][rust docs] | ![C logo] | [**C/C++**][C integration] | [`wasmer.h` header] | [Learn][c docs] | | ![C# logo] | [**C#**][C# integration] | [`WasmerSharp` NuGet package] | [Learn][c# docs] | | ![D logo] | [**D**][D integration] | [`wasmer` Dub package] | [Learn][d docs] | | ![Python logo] | [**Python**][Python integration] | [`wasmer` PyPI package] | [Learn][python docs] | | ![JS logo] | [**Javascript**][JS integration] | [`@wasmerio` NPM packages] | [Learn][js docs] | | ![Go logo] | [**Go**][Go integration] | [`wasmer` Go package] | [Learn][go docs] | | ![PHP logo] | [**PHP**][PHP integration] | [`wasm` PECL package] | [Learn][php docs] | | ![Ruby logo] | [**Ruby**][Ruby integration] | [`wasmer` Ruby Gem] | [Learn][ruby docs] | | ![Java logo] | [**Java**][Java integration] | [`wasmer/wasmer-jni` Bintray package] | [Learn][java docs] | | ![Elixir logo] | [**Elixir**][Elixir integration] | [`wasmex` hex package] | [Learn][elixir docs] | | ![R logo] | [**R**][R integration] | *공개 패키지 없음* | [Learn][r docs] | | ![Postgres logo] | [**Postgres**][Postgres integration] | *공개 패키지 없음* | [Learn][postgres docs] | | | [**Swift**][Swift integration] | *공개 패키지 없음* | | | ![Zig logo] | [**Zig**][Zig integration] | *공개 패키지 없음* | | | ![Dart logo] | [**Dart**][Dart integration] | [`wasm` pub package] | | | | [**Lisp**][Lisp integration] | *under heavy development - no published package* | | [👋&nbsp;&nbsp;없는 언어가 있습니까?](https://github.com/wasmerio/wasmer/issues/new?assignees=&labels=%F0%9F%8E%89+enhancement&template=---feature-request.md&title=) [rust logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/rust.svg [rust integration]: https://github.com/wasmerio/wasmer/tree/master/lib/api [`wasmer` rust crate]: https://crates.io/crates/wasmer/ [rust docs]: https://docs.rs/wasmer/ [c logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/c.svg [c integration]: https://github.com/wasmerio/wasmer/tree/master/lib/c-api [`wasmer.h` header]: https://github.com/wasmerio/wasmer/blob/master/lib/c-api/wasmer.h [c docs]: https://docs.rs/wasmer-c-api/*/wasmer_c_api/wasm_c_api/index.html [c# logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/csharp.svg [c# integration]: https://github.com/migueldeicaza/WasmerSharp [`wasmersharp` nuget package]: https://www.nuget.org/packages/WasmerSharp/ [c# docs]: https://migueldeicaza.github.io/WasmerSharp/ [d logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/d.svg [d integration]: https://github.com/chances/wasmer-d [`wasmer` Dub package]: https://code.dlang.org/packages/wasmer [d docs]: https://chances.github.io/wasmer-d [python logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/python.svg [python integration]: https://github.com/wasmerio/wasmer-python [`wasmer` pypi package]: https://pypi.org/project/wasmer/ [python docs]: https://wasmerio.github.io/wasmer-python/api/wasmer/ [go logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/go.svg [go integration]: https://github.com/wasmerio/wasmer-go [`wasmer` go package]: https://pkg.go.dev/github.com/wasmerio/wasmer-go/wasmer [go docs]: https://pkg.go.dev/github.com/wasmerio/wasmer-go/wasmer?tab=doc [php logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/php.svg [php integration]: https://github.com/wasmerio/wasmer-php [`wasm` pecl package]: https://pecl.php.net/package/wasm [php docs]: https://wasmerio.github.io/wasmer-php/ [js logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/js.svg [js integration]: https://github.com/wasmerio/wasmer-js [`@wasmerio` npm packages]: https://www.npmjs.com/org/wasmer [js docs]: https://docs.wasmer.io/integrations/js/reference-api [ruby logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/ruby.svg [ruby integration]: https://github.com/wasmerio/wasmer-ruby [`wasmer` ruby gem]: https://rubygems.org/gems/wasmer [ruby docs]: https://wasmerio.github.io/wasmer-ruby/wasmer_ruby/index.html [java logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/java.svg [java integration]: https://github.com/wasmerio/wasmer-java [`wasmer/wasmer-jni` bintray package]: https://bintray.com/wasmer/wasmer-jni/wasmer-jni [java docs]: https://github.com/wasmerio/wasmer-java/#api-of-the-wasmer-library [elixir logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/elixir.svg [elixir integration]: https://github.com/tessi/wasmex [elixir docs]: https://hexdocs.pm/wasmex/api-reference.html [`wasmex` hex package]: https://hex.pm/packages/wasmex [r logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/r.svg [r integration]: https://github.com/dirkschumacher/wasmr [r docs]: https://github.com/dirkschumacher/wasmr#example [postgres logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/postgres.svg [postgres integration]: https://github.com/wasmerio/wasmer-postgres [postgres docs]: https://github.com/wasmerio/wasmer-postgres#usage--documentation [swift integration]: https://github.com/AlwaysRightInstitute/SwiftyWasmer [zig logo]: https://raw.githubusercontent.com/ziglang/logo/master/zig-favicon.png [zig integration]: https://github.com/zigwasm/wasmer-zig [dart logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/dart.svg [dart integration]: https://github.com/dart-lang/wasm [`wasm` pub package]: https://pub.dev/packages/wasm [lisp integration]: https://github.com/helmutkian/cl-wasm-runtime ## 기여 도움을 주셔서 감사합니다! 💜 [Wasmer를 빌드](https://docs.wasmer.io/ecosystem/wasmer/building-from-source)하거나 [변경 사항을 테스트](https://docs.wasmer.io/ecosystem/wasmer/building-from-source/testing)하는 방법에 대한 문서를 확인하십시오. ## 커뮤니티 Wasmer에는 개발자의 기여가 있는 훌륭한 커뮤니티가 있습니다. 환영합니다! 꼭 참여해주세요! 👋 - [Wasmer Community Slack](https://slack.wasmer.io/) - [Wasmer on Twitter](https://twitter.com/wasmerio) - [Wasmer on Facebook](https://www.facebook.com/wasmerio) - [Email](mailto:hello@wasmer.io) <div align="center"> <a href="https://wasmer.io" target="_blank" rel="noopener noreferrer"> <img width="300" src="https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/logo.png" alt="Wasmer logo"> </a> <p> <a href="https://github.com/wasmerio/wasmer/actions?query=workflow%3Abuild"> <img src="https://github.com/wasmerio/wasmer/workflows/build/badge.svg?style=flat-square" alt="Build Status"> </a> <a href="https://github.com/wasmerio/wasmer/blob/master/LICENSE"> <img src="https://img.shields.io/github/license/wasmerio/wasmer.svg?style=flat-square" alt="License"> </a> <a href="https://slack.wasmer.io"> <img src="https://img.shields.io/static/v1?label=Slack&message=join%20chat&color=brighgreen&style=flat-square" alt="Slack channel"> </a> </p> <h3> <a href="https://wasmer.io/">网站</a> <span> • </span> <a href="https://docs.wasmer.io">文档</a> <span> • </span> <a href="https://slack.wasmer.io/">聊天</a> </h3> </div> <br /> [Wasmer](https://wasmer.io/) 提供基于 [WebAssembly](https://webassembly.org/) 的超轻量级容器,其可以在任何地方运行:从桌面到云、以及 IoT 设备,并且能也嵌入在 [*任何编程语言*](https://github.com/wasmerio/wasmer#language-integrations). > 其他语言的 Readme: [🇩🇪 Deutsch-德語](https://github.com/wasmerio/wasmer/blob/master/docs/de/README.md) • [🇬🇧 English-英文](https://github.com/wasmerio/wasmer/blob/master/README.md) • [🇪🇸 Español-西班牙语](https://github.com/wasmerio/wasmer/blob/master/docs/es/README.md) • [🇫🇷 Français-法语](https://github.com/wasmerio/wasmer/blob/master/docs/fr/README.md) • [🇯🇵 日本語-日文](https://github.com/wasmerio/wasmer/blob/master/docs/ja/README.md). ## 特性 * **快速又安全**. Wasmer在完全沙盒化的环境中以“接近本机”的速度运行 WebAssembly。 * **可插拔**. Wasmer 可以根据你的需求支持不同的编译框架 (LLVM,Cranelift ...). * **通用的**. 你可以在**任何平台**(macOS, Linux and Windows) 和芯片组运行 Wasmer. * **符合标准**. 运行时通过了[官方WebAssembly测试集](https://github.com/WebAssembly/testsuite) 支持[WASI](https://github.com/WebAssembly/WASI) 和[Emscripten](https://emscripten.org/). ## 快速开始 Wasmer 不需要安装其他依赖. 你可以使用以下安装程序进行安装: ```sh curl https://get.wasmer.io -sSfL | sh ``` <details> <summary>使用Powershell (Windows)</summary> <p> ```powershell iwr https://win.wasmer.io -useb | iex ``` </p> </details> > 有关更多安装选项,请参见 [wasmer-install](https://github.com/wasmerio/wasmer-install): Homebrew, Scoop, Cargo... #### 执行WebAssembly文件 安装Wasmer之后,你已经准备好执行第一个WebAssemby文件了! 🎉 您可以通过运行 QuickJS 开始: [qjs.wasm](https://registry-cdn.wapm.io/contents/_/quickjs/0.0.3/build/qjs.wasm) ```bash $ wasmer qjs.wasm QuickJS - Type "\h" for help qjs > ``` #### 接下来是你可以做的: - [在你的Rust应用程序中使用Wasmer](https://docs.wasmer.io/integrations/rust) - [在WAPM上发布Wasm程序包](https://docs.wasmer.io/ecosystem/wapm/publishing-your-package) - [阅读有关Wasmer的更多信息](https://medium.com/wasmer/) ## 语言整合 📦 Wasmer 运行时能以库的形式**嵌入到不同的语言**,因此你可以在任何地方使用WebAssembly. | &nbsp; | 语言 | 程序包 | 文档 | |-|-|-|-| | ![Rust logo] | [**Rust**][Rust integration] | [`wasmer` Rust crate] | [文档][rust docs] | ![C logo] | [**C/C++**][C integration] | [`wasmer.h` headers] | [文档][c docs] | | ![C# logo] | [**C#**][C# integration] | [`WasmerSharp` NuGet package] | [文档][c# docs] | | ![D logo] | [**D**][D integration] | [`wasmer` Dub package] | [文档][d docs] | | ![Python logo] | [**Python**][Python integration] | [`wasmer` PyPI package] | [文档][python docs] | | ![JS logo] | [**Javascript**][JS integration] | [`@wasmerio` NPM packages] | [文档][js docs] | | ![Go logo] | [**Go**][Go integration] | [`wasmer` Go package] | [文档][go docs] | | ![PHP logo] | [**PHP**][PHP integration] | [`wasm` PECL package] | [文档][php docs] | | ![Ruby logo] | [**Ruby**][Ruby integration] | [`wasmer` Ruby Gem] | [文档][ruby docs] | | ![Java logo] | [**Java**][Java integration] | [`wasmer/wasmer-jni` Bintray package] | [文档][java docs] | | ![Elixir logo] | [**Elixir**][Elixir integration] | [`wasmex` hex package] | [文档][elixir docs] | | ![R logo] | [**R**][R integration] | *没有已发布的软件包* | [文档][r docs] | | ![Postgres logo] | [**Postgres**][Postgres integration] | *没有已发布的软件包* | [文档][postgres docs] | | | [**Swift**][Swift integration] | *没有已发布的软件包* | | | ![Zig logo] | [**Zig**][Zig integration] | *no published package* | | [👋 缺少语言?](https://github.com/wasmerio/wasmer/issues/new?assignees=&labels=%F0%9F%8E%89+enhancement&template=---feature-request.md&title=) [rust logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/rust.svg [rust integration]: https://github.com/wasmerio/wasmer/tree/master/lib/api [`wasmer` rust crate]: https://crates.io/crates/wasmer/ [rust docs]: https://wasmerio.github.io/wasmer/crates/wasmer [c logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/c.svg [c integration]: https://github.com/wasmerio/wasmer/tree/master/lib/c-api [`wasmer.h` headers]: https://wasmerio.github.io/wasmer/c/ [c docs]: https://wasmerio.github.io/wasmer/c/ [c# logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/csharp.svg [c# integration]: https://github.com/migueldeicaza/WasmerSharp [`wasmersharp` nuget package]: https://www.nuget.org/packages/WasmerSharp/ [c# docs]: https://migueldeicaza.github.io/WasmerSharp/ [d logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/d.svg [d integration]: https://github.com/chances/wasmer-d [`wasmer` Dub package]: https://code.dlang.org/packages/wasmer [d docs]: https://chances.github.io/wasmer-d [python logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/python.svg [python integration]: https://github.com/wasmerio/wasmer-python [`wasmer` pypi package]: https://pypi.org/project/wasmer/ [python docs]: https://github.com/wasmerio/wasmer-python#api-of-the-wasmer-extensionmodule [go logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/go.svg [go integration]: https://github.com/wasmerio/wasmer-go [`wasmer` go package]: https://pkg.go.dev/github.com/wasmerio/wasmer-go/wasmer [go docs]: https://pkg.go.dev/github.com/wasmerio/wasmer-go/wasmer?tab=doc [php logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/php.svg [php integration]: https://github.com/wasmerio/wasmer-php [`wasm` pecl package]: https://pecl.php.net/package/wasm [php docs]: https://wasmerio.github.io/wasmer-php/wasm/ [js logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/js.svg [js integration]: https://github.com/wasmerio/wasmer-js [`@wasmerio` npm packages]: https://www.npmjs.com/org/wasmer [js docs]: https://docs.wasmer.io/integrations/js/reference-api [ruby logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/ruby.svg [ruby integration]: https://github.com/wasmerio/wasmer-ruby [`wasmer` ruby gem]: https://rubygems.org/gems/wasmer [ruby docs]: https://www.rubydoc.info/gems/wasmer/ [java logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/java.svg [java integration]: https://github.com/wasmerio/wasmer-java [`wasmer/wasmer-jni` bintray package]: https://bintray.com/wasmer/wasmer-jni/wasmer-jni [java docs]: https://github.com/wasmerio/wasmer-java/#api-of-the-wasmer-library [elixir logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/elixir.svg [elixir integration]: https://github.com/tessi/wasmex [elixir docs]: https://hexdocs.pm/wasmex/api-reference.html [`wasmex` hex package]: https://hex.pm/packages/wasmex [r logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/r.svg [r integration]: https://github.com/dirkschumacher/wasmr [r docs]: https://github.com/dirkschumacher/wasmr#example [postgres logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/postgres.svg [postgres integration]: https://github.com/wasmerio/wasmer-postgres [postgres docs]: https://github.com/wasmerio/wasmer-postgres#usage--documentation [swift integration]: https://github.com/AlwaysRightInstitute/SwiftyWasmer [zig logo]: https://raw.githubusercontent.com/ziglang/logo/master/zig-favicon.png [zig integration]: https://github.com/zigwasm/wasmer-zig ## 贡献 **我们欢迎任何形式的贡献,尤其是来自社区新成员的贡献** 💜 你可以在[我们的出色文档](https://docs.wasmer.io/ecosystem/wasmer/building-from-source) 中学习如何构建 Wasmer 运行时! ### 测试 想要测试吗? [参考 Wasmer 文档](https://docs.wasmer.io/ecosystem/wasmer/building-from-source/testing). ## 社区 Wasmer 拥有一个由出色的开发人员和贡献者组成的社区。 欢迎你,请加入我们! 👋 ### 频道 - [Slack](https://slack.wasmer.io/) - [Twitter](https://twitter.com/wasmerio) - [Facebook](https://www.facebook.com/wasmerio) - [Email](mailto:hello@wasmer.io) # WebAssembly testsuite Here is where all the `.wast` tests live. # `wasmer-vm` [![Build Status](https://github.com/wasmerio/wasmer/workflows/build/badge.svg?style=flat-square)](https://github.com/wasmerio/wasmer/actions?query=workflow%3Abuild) [![Join Wasmer Slack](https://img.shields.io/static/v1?label=Slack&message=join%20chat&color=brighgreen&style=flat-square)](https://slack.wasmer.io) [![MIT License](https://img.shields.io/github/license/wasmerio/wasmer.svg?style=flat-square)](https://github.com/wasmerio/wasmer/blob/master/LICENSE) This crate contains the Wasmer VM runtime library, supporting the Wasm ABI used by any [`wasmer-engine`] implementation. The Wasmer runtime is modular by design, and provides several libraries where each of them provides a specific set of features. This `wasmer-vm` library contains the low-level foundation for the runtime itself. It provides all the APIs the [`wasmer-engine`](https://crates.io/crates/wasmer-engine) needs to operate, from the `instance`, to `memory`, `probestack`, signature registry, `trap`, `table`, `VMContext`, `libcalls` etc. It is very unlikely that a user will need to deal with `wasmer-vm` directly. The `wasmer` crate provides types that embed types from `wasmer-vm` with a higher-level API. [`wasmer-engine`]: https://crates.io/crates/wasmer-engine ### Acknowledgments This project borrowed some of the code for the VM structure and trapping from the [wasmtime-runtime](https://crates.io/crates/wasmtime-runtime). Please check [Wasmer ATTRIBUTIONS](https://github.com/wasmerio/wasmer/blob/master/ATTRIBUTIONS.md) to further see licenses and other attributions of the project. # Tests: Deprecated In this folder we will test deprecated APIs to verify that they still work the way it should, so users of Wasmer are happy while transitioning to newer APIs. As time passes and adoption of new APIs rises, tests on this folder should start tending towards 0. Therefore, deprecated tests are intended to be deleted on the long term. # `wasmer-compiler-llvm` [![Build Status](https://github.com/wasmerio/wasmer/workflows/build/badge.svg?style=flat-square)](https://github.com/wasmerio/wasmer/actions?query=workflow%3Abuild) [![Join Wasmer Slack](https://img.shields.io/static/v1?label=Slack&message=join%20chat&color=brighgreen&style=flat-square)](https://slack.wasmer.io) [![MIT License](https://img.shields.io/github/license/wasmerio/wasmer.svg?style=flat-square)](https://github.com/wasmerio/wasmer/blob/master/LICENSE) [![crates.io](https://img.shields.io/crates/v/wasmer-compiler-llvm.svg)](https://crates.io/crates/wasmer-compiler-llvm) This crate contains a compiler implementation based on [the LLVM Compiler Infrastructure][LLVM]. ## Usage ```rust use wasmer::{Store, Universal}; use wasmer_compiler_llvm::LLVM; let compiler = LLVM::new(); // Put it into an engine and add it to the store let store = Store::new(&Universal::new(compiler).engine()); ``` *Note: you can find a [full working example using LLVM compiler here][example].* ## When to use LLVM We recommend using LLVM as the default compiler when running WebAssembly files on any **production** system, as it offers maximum peformance near to native speeds. ## Requirements The LLVM compiler requires a valid installation of LLVM in your system. It currently requires **LLVM 12**. You can install LLVM easily on your Debian-like system via this command: ```bash wget https://apt.llvm.org/llvm.sh -O /tmp/llvm.sh sudo bash /tmp/llvm.sh 12 ``` Or in macOS: ```bash brew install llvm ``` Or via any of the [pre-built binaries that LLVM offers][llvm-pre-built]. [LLVM]: https://llvm.org/ [example]: https://github.com/wasmerio/wasmer/blob/master/examples/compiler_llvm.rs [llvm-pre-built]: https://releases.llvm.org/download.html # Wasmer Integration tests All Wasmer end to end integration tests live here. We have different kind of integration tests: ## CLI Integration tests This tests check that the `wasmer` CLI works as it should when running it as a Command in a shell, for each of the supported compilers. ## C Integration tests This tests verify that Wasmer wasm-c-api tests are passing for each of the supported compilers. ## Rust Integration tests This tests verify that the `wasmer` API fulfill the required API that external users use. # The Wasmer runtime crates The philosophy of Wasmer is to be very modular by design. It's composed of a set of crates. We can group them as follows: * `api` — The public Rust API exposes everything a user needs to use Wasmer programatically through the `wasmer` crate, * `cache` — The traits and types to cache compiled WebAssembly modules, * `cli` — The Wasmer CLI itself, * `compiler` — The base for the compiler implementations, it defines the framework for the compilers and provides everything they need: * `compiler-cranelift` — A WebAssembly compiler based on the Cranelift compiler infrastructure, * `compiler-llvm` — A WebAssembly compiler based on the LLVM compiler infrastructure; recommended for runtime speed performance, * `compiler-singlepass` — A WebAssembly compiler based on our own compilation infrastructure; recommended for compilation-time speed performance. * `derive` — A set of procedural macros used inside Wasmer, * `engine` — The general abstraction for creating an engine, which is responsible of leading the compiling and running flow. Using the same compiler, the runtime performance will be approximately the same, however the way it stores and loads the executable code will differ: * `engine-universal` — stores the code in a custom file format, and loads it in memory, * `types` — The basic structures to use WebAssembly, * `vm` — The Wasmer VM runtime library, the low-level base of everything. <div align="center"> <a href="https://wasmer.io" target="_blank" rel="noopener noreferrer"> <img width="300" src="https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/logo.png" alt="Wasmer Logo"> </a> <p> <a href="https://github.com/wasmerio/wasmer/actions?query=workflow%3Abuild"> <img src="https://github.com/wasmerio/wasmer/workflows/build/badge.svg?style=flat-square" alt="Build Status"> </a> <a href="https://github.com/wasmerio/wasmer/blob/master/LICENSE"> <img src="https://img.shields.io/github/license/wasmerio/wasmer.svg" alt="Lizenz"> </a> <a href="https://docs.wasmer.io"> <img src="https://img.shields.io/static/v1?label=Docs&message=docs.wasmer.io&color=blue" alt="Wasmer Doku"> </a> <a href="https://slack.wasmer.io"> <img src="https://img.shields.io/static/v1?label=Slack&message=teilnehmen&color=brighgreen" alt="Slack Kanal"> </a> </p> </div> <br /> Wasmer ist eine _schnelle_ und _sichere_ [**WebAssembly**](https://webassembly.org) Runtime, die das Ausführen von _schlanken Containern_ überall ermöglicht: auf dem *Desktop* in der *Cloud*, so wie auf *Edge* und *IoT* Geräten. > _Die README ist auch in folgenden Sprachen verfügbar: [🇨🇳 中文-Chinesisch](https://github.com/wasmerio/wasmer/blob/master/docs/cn/README.md) • [🇬🇧 English-Englisch](https://github.com/wasmerio/wasmer/blob/master/README.md) • [🇪🇸 Español-Spanisch](https://github.com/wasmerio/wasmer/blob/master/docs/es/README.md) • [🇫🇷 Français-Französisch](https://github.com/wasmerio/wasmer/blob/master/docs/fr/README.md) • [🇯🇵 日本語-Japanisch](https://github.com/wasmerio/wasmer/blob/master/docs/ja/README.md)_. ### Leistungsmerkmale * Standardmäßig sicher. Kein Datei-, Netzwerk- oder Umgebungszugriff, sofern nicht explizit aktiviert. * Unterstützt [WASI](https://github.com/WebAssembly/WASI) und [Emscripten](https://emscripten.org/) standardmäßig. * Schnell. Führt WebAssembly in nahezu nativer Geschwindigkeit aus. * Einbettbar in [mehrere Programmiersprachen](https://github.com/wasmerio/wasmer/#-language-integrations) * Kompatibel mit den neuesten Empfehlungen für WebAssembly (SIMD, Referenztypen, Threads, ...) ### Installation Wasmer CLI wird als eine einzige ausführbare Datei ohne Abhängigkeiten ausgeliefert. ```sh curl https://get.wasmer.io -sSfL | sh ``` <details> <summary>Weitere Installationsmöglichkeiten (Powershell, Brew, Cargo, ...)</summary> _Wasmer kann über verschiedene Paketmanager installiert werden. Wählen Sie den für Ihre Umgebung am besten geeigneten aus:_ * Powershell (Windows) ```powershell iwr https://win.wasmer.io -useb | iex ``` * <a href="https://formulae.brew.sh/formula/wasmer">Homebrew</a> (macOS, Linux) ```sh brew install wasmer ``` * <a href="https://github.com/ScoopInstaller/Main/blob/master/bucket/wasmer.json">Scoop</a> (Windows) ```sh scoop install wasmer ``` * <a href="https://chocolatey.org/packages/wasmer">Chocolatey</a> (Windows) ```sh choco install wasmer ``` * <a href="https://crates.io/crates/wasmer-cli/">Cargo</a> _Note: All the available features are described in the [`wasmer-cli` crate docs](https://github.com/wasmerio/wasmer/tree/master/lib/cli/README.md)_ ```sh cargo install wasmer-cli ``` > Suchen Sie nach weiteren Installationsmöglichkeiten? Im [`wasmer-install` Repository](https://github.com/wasmerio/wasmer-install) können Si mehr erfahren! </details> ### Schnellstart Sie können beginnen, [QuickJS](https://github.com/bellard/quickjs/) auszuführen, eine kleine und einbettbare Javascript Engine, die als WebAssembly Modul kompiliert ist: ([`qjs.wasm`](https://registry-cdn.wapm.io/contents/_/quickjs/0.0.3/build/qjs.wasm)): ```bash $ wasmer qjs.wasm QuickJS - Type "\h" for help qjs > const i = 1 + 2; qjs > console.log("hello " + i); hello 3 ``` #### Folgendes können Sie als nächstes tun: - [Wasmer für eine Rust Anwendung nutzen](https://docs.wasmer.io/integrations/rust) - [Ein asm Paket auf WAPM veröffentlichen](https://docs.wasmer.io/ecosystem/wapm/publishing-your-package) - [Mehr zu Wasmer lesen](https://medium.com/wasmer/) ## 📦 Unterstützte Sprachen Die Wasmer-Laufzeit kann als Bibliothek **eingebettet in verschiedenen Sprachen** verwendet werden, so dass Sie WebAssembly _überall_ einsetzen können. | | Sprache | Paket | Dokumentation | |-|-|-|-| | ![Rust logo] | [**Rust**][Rust Integration] | [`wasmer` Rust crate] | [Lernen][rust docs] | ![C logo] | [**C/C++**][C Integration] | [`wasmer.h` header] | [Lernen][c docs] | | ![C# logo] | [**C#**][C# Integration] | [`WasmerSharp` NuGet Paket] | [Lernen][c# docs] | | ![D logo] | [**D**][D Integration] | [`wasmer` Dub Paket] | [Lernen][d docs] | | ![Python logo] | [**Python**][Python Integration] | [`wasmer` PyPI Paket] | [Lernen][python docs] | | ![JS logo] | [**Javascript**][JS Integration] | [`@wasmerio` NPM Paket] | [Lernen][js docs] | | ![Go logo] | [**Go**][Go Integration] | [`wasmer` Go Paket] | [Lernen][go docs] | | ![PHP logo] | [**PHP**][PHP Integration] | [`wasm` PECL Paket] | [Lernen][php docs] | | ![Ruby logo] | [**Ruby**][Ruby Integration] | [`wasmer` Ruby Gem] | [Lernen][ruby docs] | | ![Java logo] | [**Java**][Java Integration] | [`wasmer/wasmer-jni` Bintray Paket] | [Lernen][java docs] | | ![Elixir logo] | [**Elixir**][Elixir Integration] | [`wasmex` hex Paket] | [Lernen][elixir docs] | | ![R logo] | [**R**][R Integration] | *kein Paket veröffentlicht* | [Lernen][r docs] | | ![Postgres logo] | [**Postgres**][Postgres Integration] | *kein Paket veröffentlicht* | [Lernen][postgres docs] | | | [**Swift**][Swift Integration] | *kein Paket veröffentlicht* | | | ![Zig logo] | [**Zig**][Zig Integration] | *kein Paket veröffentlicht* | | | ![Dart logo] | [**Dart**][Dart Integration] | [`wasm` pub Paket] | | [👋&nbsp;&nbsp;Fehlt eine Sprache?](https://github.com/wasmerio/wasmer/issues/new?assignees=&labels=%F0%9F%8E%89+enhancement&template=---feature-request.md&title=) [rust logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/rust.svg [rust integration]: https://github.com/wasmerio/wasmer/tree/master/lib/api [`wasmer` rust crate]: https://crates.io/crates/wasmer/ [rust docs]: https://wasmerio.github.io/wasmer/crates/wasmer [c logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/c.svg [c integration]: https://github.com/wasmerio/wasmer/tree/master/lib/c-api [`wasmer.h` header]: https://github.com/wasmerio/wasmer/blob/master/lib/c-api/wasmer.h [c docs]: https://wasmerio.github.io/wasmer/crates/wasmer_c_api [c# logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/csharp.svg [c# integration]: https://github.com/migueldeicaza/WasmerSharp [`wasmersharp` nuget package]: https://www.nuget.org/packages/WasmerSharp/ [c# docs]: https://migueldeicaza.github.io/WasmerSharp/ [d logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/d.svg [d integration]: https://github.com/chances/wasmer-d [`wasmer` Dub package]: https://code.dlang.org/packages/wasmer [d docs]: https://chances.github.io/wasmer-d [python logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/python.svg [python integration]: https://github.com/wasmerio/wasmer-python [`wasmer` pypi package]: https://pypi.org/project/wasmer/ [python docs]: https://wasmerio.github.io/wasmer-python/api/wasmer/ [go logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/go.svg [go integration]: https://github.com/wasmerio/wasmer-go [`wasmer` go package]: https://pkg.go.dev/github.com/wasmerio/wasmer-go/wasmer [go docs]: https://pkg.go.dev/github.com/wasmerio/wasmer-go/wasmer?tab=doc [php logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/php.svg [php integration]: https://github.com/wasmerio/wasmer-php [`wasm` pecl package]: https://pecl.php.net/package/wasm [php docs]: https://wasmerio.github.io/wasmer-php/wasm/ [js logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/js.svg [js integration]: https://github.com/wasmerio/wasmer-js [`@wasmerio` npm packages]: https://www.npmjs.com/org/wasmer [js docs]: https://docs.wasmer.io/integrations/js/reference-api [ruby logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/ruby.svg [ruby integration]: https://github.com/wasmerio/wasmer-ruby [`wasmer` ruby gem]: https://rubygems.org/gems/wasmer [ruby docs]: https://wasmerio.github.io/wasmer-ruby/wasmer_ruby/index.html [java logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/java.svg [java integration]: https://github.com/wasmerio/wasmer-java [`wasmer/wasmer-jni` bintray package]: https://bintray.com/wasmer/wasmer-jni/wasmer-jni [java docs]: https://github.com/wasmerio/wasmer-java/#api-of-the-wasmer-library [elixir logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/elixir.svg [elixir integration]: https://github.com/tessi/wasmex [elixir docs]: https://hexdocs.pm/wasmex/api-reference.html [`wasmex` hex package]: https://hex.pm/packages/wasmex [r logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/r.svg [r integration]: https://github.com/dirkschumacher/wasmr [r docs]: https://github.com/dirkschumacher/wasmr#example [postgres logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/postgres.svg [postgres integration]: https://github.com/wasmerio/wasmer-postgres [postgres docs]: https://github.com/wasmerio/wasmer-postgres#usage--documentation [swift integration]: https://github.com/AlwaysRightInstitute/SwiftyWasmer [zig logo]: https://raw.githubusercontent.com/ziglang/logo/master/zig-favicon.png [zig integration]: https://github.com/zigwasm/wasmer-zig [dart logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/dart.svg [dart integration]: https://github.com/dart-lang/wasm [`wasm` pub package]: https://pub.dev/packages/wasm ## Unterstützen Wir sind dankbar für Ihre Hilfe! 💜 Lesen Sie in unserer Dokumentation nach, wie man [Wasmer aus dem Quellcode kompiliert](https://docs.wasmer.io/ecosystem/wasmer/building-from-source) oder [testen Sie Änderungen](https://docs.wasmer.io/ecosystem/wasmer/building-from-source/testing). ## Community Wasmer hat eine wunderbare Community von Entwicklern und Mitwirkenden. Sie sind herzlich willkommen, bitte machen Sie mit! 👋 - [Wasmer Community auf Slack](https://slack.wasmer.io/) - [Wasmer auf Twitter](https://twitter.com/wasmerio) - [Wasmer auf Facebook](https://www.facebook.com/wasmerio) - [Email](mailto:hello@wasmer.io) # `wasmer` [![Build Status](https://github.com/wasmerio/wasmer/workflows/build/badge.svg?style=flat-square)](https://github.com/wasmerio/wasmer/actions?query=workflow%3Abuild) [![Join Wasmer Slack](https://img.shields.io/static/v1?label=Slack&message=join%20chat&color=brighgreen&style=flat-square)](https://slack.wasmer.io) [![MIT License](https://img.shields.io/github/license/wasmerio/wasmer.svg?style=flat-square)](https://github.com/wasmerio/wasmer/blob/master/LICENSE) [![crates.io](https://img.shields.io/crates/v/wasmer.svg)](https://crates.io/crates/wasmer) [`Wasmer`](https://wasmer.io/) is the most popular [WebAssembly](https://webassembly.org/) runtime for Rust. It supports JIT (Just In Time) and AOT (Ahead Of Time) compilation as well as pluggable compilers suited to your needs. It's designed to be safe and secure, and runnable in any kind of environment. ## Usage Here is a small example of using Wasmer to run a WebAssembly module written with its WAT format (textual format): ```rust use wasmer::{Store, Module, Instance, Value, imports}; fn main() -> anyhow::Result<()> { let module_wat = r#" (module (type $t0 (func (param i32) (result i32))) (func $add_one (export "add_one") (type $t0) (param $p0 i32) (result i32) get_local $p0 i32.const 1 i32.add)) "#; let store = Store::default(); let module = Module::new(&store, &module_wat)?; // The module doesn't import anything, so we create an empty import object. let import_object = imports! {}; let instance = Instance::new(&module, &import_object)?; let add_one = instance.exports.get_function("add_one")?; let result = add_one.call(&[Value::I32(42)])?; assert_eq!(result[0], Value::I32(43)); Ok(()) } ``` [Discover the full collection of examples](https://github.com/wasmerio/wasmer/tree/master/examples). ## Features Wasmer is not only fast, but also designed to be *highly customizable*: * **Pluggable engines** — An engine is responsible to drive the compilation process and to store the generated executable code somewhere, either: * in-memory (with [`wasmer-engine-universal`]), * in a native shared object file (with [`wasmer-engine-dylib`], `.dylib`, `.so`, `.dll`), then load it with `dlopen`, * in a native static object file (with [`wasmer-engine-staticlib`]), in addition to emitting a C header file, which both can be linked against a sandboxed WebAssembly runtime environment for the compiled module with no need for runtime compilation. * **Pluggable compilers** — A compiler is used by an engine to transform WebAssembly into executable code: * [`wasmer-compiler-singlepass`] provides a fast compilation-time but an unoptimized runtime speed, * [`wasmer-compiler-cranelift`] provides the right balance between compilation-time and runtime performance, useful for development, * [`wasmer-compiler-llvm`] provides a deeply optimized executable code with the fastest runtime speed, ideal for production. * **Headless mode** — Once a WebAssembly module has been compiled, it is possible to serialize it in a file for example, and later execute it with Wasmer with headless mode turned on. Headless Wasmer has no compiler, which makes it more portable and faster to load. It's ideal for constrainted environments. * **Cross-compilation** — Most compilers support cross-compilation. It means it possible to pre-compile a WebAssembly module targetting a different architecture or platform and serialize it, to then run it on the targetted architecture and platform later. * **Run Wasmer in a JavaScript environment** — With the `js` Cargo feature, it is possible to compile a Rust program using Wasmer to WebAssembly. In this context, the resulting WebAssembly module will expect to run in a JavaScript environment, like a browser, Node.js, Deno and so on. In this specific scenario, there is no engines or compilers available, it's the one available in the JavaScript environment that will be used. Wasmer ships by default with the Cranelift compiler as its great for development purposes. However, we strongly encourage to use the LLVM compiler in production as it performs about 50% faster, achieving near-native speeds. Note: if one wants to use multiple compilers at the same time, it's also possible! One will need to import them directly via each of the compiler crates. Read [the documentation to learn more](https://wasmerio.github.io/wasmer/crates/doc/wasmer/). --- Made with ❤️ by the Wasmer team, for the community [`wasmer-engine-universal`]: https://github.com/wasmerio/wasmer/tree/master/lib/engine-universal [`wasmer-engine-dylib`]: https://github.com/wasmerio/wasmer/tree/master/lib/engine-dylib [`wasmer-engine-staticlib`]: https://github.com/wasmerio/wasmer/tree/master/lib/engine-staticlib [`wasmer-compiler-singlepass`]: https://github.com/wasmerio/wasmer/tree/master/lib/compiler-singlepass [`wasmer-compiler-cranelift`]: https://github.com/wasmerio/wasmer/tree/master/lib/compiler-cranelift [`wasmer-compiler-llvm`]: https://github.com/wasmerio/wasmer/tree/master/lib/compiler-llvm # `wasmer-compiler-cranelift` [![Build Status](https://github.com/wasmerio/wasmer/workflows/build/badge.svg?style=flat-square)](https://github.com/wasmerio/wasmer/actions?query=workflow%3Abuild) [![Join Wasmer Slack](https://img.shields.io/static/v1?label=Slack&message=join%20chat&color=brighgreen&style=flat-square)](https://slack.wasmer.io) [![MIT License](https://img.shields.io/github/license/wasmerio/wasmer.svg?style=flat-square)](https://github.com/wasmerio/wasmer/blob/master/LICENSE) [![crates.io](https://img.shields.io/crates/v/wasmer-compiler-cranelift.svg)](https://crates.io/crates/wasmer-compiler-cranelift) This crate contains a compiler implementation based on Cranelift. ## Usage ```rust use wasmer::{Store, Universal}; use wasmer_compiler_cranelift::Cranelift; let compiler = Cranelift::new(); // Put it into an engine and add it to the store let store = Store::new(&Universal::new(compiler).engine()); ``` *Note: you can find a [full working example using Cranelift compiler here][example].* ## When to use Cranelift We recommend using this compiler crate **only for development proposes**. For production we recommend using [`wasmer-compiler-llvm`] as it offers a much better runtime speed (50% faster on average). ### Acknowledgments This project borrowed some of the function lowering from [`cranelift-wasm`]. Please check [Wasmer `ATTRIBUTIONS`] to further see licenses and other attributions of the project. [example]: https://github.com/wasmerio/wasmer/blob/master/examples/compiler_cranelift.rs [`wasmer-compiler-llvm`]: https://github.com/wasmerio/wasmer/tree/master/lib/compiler-llvm [`cranelift-wasm`]: https://crates.io/crates/cranelift-wasm [Wasmer `ATTRIBUTIONS`]: https://github.com/wasmerio/wasmer/blob/master/ATTRIBUTIONS.md <div align="center"> <a href="https://wasmer.io" target="_blank" rel="noopener noreferrer"> <img width="300" src="https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/logo.png" alt="Wasmerロゴ"> </a> <p> <a href="https://github.com/wasmerio/wasmer/actions?query=workflow%3Abuild"> <img src="https://github.com/wasmerio/wasmer/workflows/build/badge.svg?style=flat-square" alt="ビルドステータス"> </a> <a href="https://github.com/wasmerio/wasmer/blob/master/LICENSE"> <img src="https://img.shields.io/github/license/wasmerio/wasmer.svg?style=flat-square" alt="ライセンス"> </a> <a href="https://slack.wasmer.io"> <img src="https://img.shields.io/static/v1?label=Slack&message=join%20chat&color=brighgreen&style=flat-square" alt="Slackチャンネル"> </a> </p> <h3> <a href="https://wasmer.io/">Website</a> <span> • </span> <a href="https://docs.wasmer.io">Docs</a> <span> • </span> <a href="https://slack.wasmer.io/">Chat</a> </h3> </div> <br /> [Wasmer](https://wasmer.io/) は、[WebAssembly](https://webassembly.org/) をベースとした非常に軽量なコンテナを実現します。デスクトップからクラウドや IoT デバイス上まで、どんな環境でも実行でき、さらに[*任意のプログラミング言語*](#他の言語とのインテグレーション)に埋め込むこともできます。 > この readme は、次の言語でも利用可能です。[🇩🇪 Deutsch-ドイツ語](https://github.com/wasmerio/wasmer/blob/master/docs/de/README.md) • [🇨🇳 中文-Chinese](https://github.com/wasmerio/wasmer/blob/master/docs/cn/README.md) • [🇬🇧 English-英語](https://github.com/wasmerio/wasmer/blob/master/README.md) • [🇪🇸 Español-Spanish](https://github.com/wasmerio/wasmer/blob/master/docs/es/README.md) • [🇫🇷 Français-French](https://github.com/wasmerio/wasmer/blob/master/docs/fr/README.md) ## 機能 * **高速かつ安全**。WebAssembly を完全なサンドボックス環境内で*ネイティブに近い*スピードで実行します。 * **プラガブル**。異なるコンパイルフレームワーク (LLVM、Cranelift など...) をサポートしているため、ニーズに合った最適なフレームワークを選択できます。 * **ユニバーサル**。どんなプラットフォーム上 (macOS、Linux、Windows) でも、どんな*チップセット*上でも実行できます。 * **標準に準拠**。ランタイムは[公式の WebAssembly テストスイート](https://github.com/WebAssembly/testsuite)に通っており、[WASI](https://github.com/WebAssembly/WASI) と [Emscripten](https://emscripten.org/) をサポートします。 ## クイックスタート Wasmer は依存関係なしで動作します。以下のコマンドでインストーラーを使用してインストールできます。 ```sh curl https://get.wasmer.io -sSfL | sh ``` <details> <summary>PowerShell の場合 (Windows)</summary> <p> ```powershell iwr https://win.wasmer.io -useb | iex ``` </p> </details> > Homebrew、Scoop、Cargo など、他のインストール方法については、[wasmer-install](https://github.com/wasmerio/wasmer-install) を参照してください。 #### WebAssembly ファイルの実行 Wasmer をインストールしたら、初めての WebAssembly ファイルの実行準備が完了です! 🎉 QuickJS ([qjs.wasm](https://registry-cdn.wapm.io/contents/_/quickjs/0.0.3/build/qjs.wasm)) を実行することで、すぐに始められます。 ```bash $ wasmer qjs.wasm QuickJS - Type "\h" for help qjs > ``` #### 次にできること - [Rust アプリケーションから Wasmer を使用する](https://docs.wasmer.io/integrations/rust) - [WAPM で Wasm パッケージを公開する](https://docs.wasmer.io/ecosystem/wapm/publishing-your-package) - [Wasmer についてさらに学ぶ](https://medium.com/wasmer/) ## 他の言語とのインテグレーション 📦 Wasmer ランタイムは**他の言語に組み込んで**使用できるため、WebAssembly は_どんな場所でも_利用できます。 | &nbsp; | Language | Package | Docs | |-|-|-|-| | ![Rust logo] | [**Rust**][Rust integration] | [`wasmer` Rust crate] | [Docs][rust docs] | ![C logo] | [**C/C++**][C integration] | [`wasmer.h` headers] | [Docs][c docs] | | ![C# logo] | [**C#**][C# integration] | [`WasmerSharp` NuGet package] | [Docs][c# docs] | | ![D logo] | [**D**][D integration] | [`wasmer` Dub package] | [Docs][d docs] | | ![Python logo] | [**Python**][Python integration] | [`wasmer` PyPI package] | [Docs][python docs] | | ![JS logo] | [**Javascript**][JS integration] | [`@wasmerio` NPM packages] | [Docs][js docs] | | ![Go logo] | [**Go**][Go integration] | [`wasmer` Go package] | [Docs][go docs] | | ![PHP logo] | [**PHP**][PHP integration] | [`wasm` PECL package] | [Docs][php docs] | | ![Ruby logo] | [**Ruby**][Ruby integration] | [`wasmer` Ruby Gem] | [Docs][ruby docs] | | ![Java logo] | [**Java**][Java integration] | [`wasmer/wasmer-jni` Bintray package] | [Docs][java docs] | | ![Elixir logo] | [**Elixir**][Elixir integration] | [`wasmex` hex package] | [Docs][elixir docs] | | ![R logo] | [**R**][R integration] | *公開パッケージなし* | [Docs][r docs] | | ![Postgres logo] | [**Postgres**][Postgres integration] | *公開パッケージなし* | [Docs][postgres docs] | | | [**Swift**][Swift integration] | *公開パッケージなし* | | | ![Zig logo] | [**Zig**][Zig integration] | *no published package* | | [👋 言語が見当たらない?](https://github.com/wasmerio/wasmer/issues/new?assignees=&labels=%F0%9F%8E%89+enhancement&template=---feature-request.md&title=) [rust logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/rust.svg [rust integration]: https://github.com/wasmerio/wasmer/tree/master/lib/api [`wasmer` rust crate]: https://crates.io/crates/wasmer/ [rust docs]: https://wasmerio.github.io/wasmer/crates/wasmer [c logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/c.svg [c integration]: https://github.com/wasmerio/wasmer/tree/master/lib/c-api [`wasmer.h` headers]: https://wasmerio.github.io/wasmer/c/ [c docs]: https://wasmerio.github.io/wasmer/c/ [c# logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/csharp.svg [c# integration]: https://github.com/migueldeicaza/WasmerSharp [`wasmersharp` nuget package]: https://www.nuget.org/packages/WasmerSharp/ [c# docs]: https://migueldeicaza.github.io/WasmerSharp/ [d logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/d.svg [d integration]: https://github.com/chances/wasmer-d [`wasmer` Dub package]: https://code.dlang.org/packages/wasmer [d docs]: https://chances.github.io/wasmer-d [python logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/python.svg [python integration]: https://github.com/wasmerio/wasmer-python [`wasmer` pypi package]: https://pypi.org/project/wasmer/ [python docs]: https://github.com/wasmerio/wasmer-python#api-of-the-wasmer-extensionmodule [go logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/go.svg [go integration]: https://github.com/wasmerio/wasmer-go [`wasmer` go package]: https://pkg.go.dev/github.com/wasmerio/wasmer-go/wasmer [go docs]: https://pkg.go.dev/github.com/wasmerio/wasmer-go/wasmer?tab=doc [php logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/php.svg [php integration]: https://github.com/wasmerio/wasmer-php [`wasm` pecl package]: https://pecl.php.net/package/wasm [php docs]: https://wasmerio.github.io/wasmer-php/wasm/ [js logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/js.svg [js integration]: https://github.com/wasmerio/wasmer-js [`@wasmerio` npm packages]: https://www.npmjs.com/org/wasmer [js docs]: https://docs.wasmer.io/integrations/js/reference-api [ruby logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/ruby.svg [ruby integration]: https://github.com/wasmerio/wasmer-ruby [`wasmer` ruby gem]: https://rubygems.org/gems/wasmer [ruby docs]: https://www.rubydoc.info/gems/wasmer/ [java logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/java.svg [java integration]: https://github.com/wasmerio/wasmer-java [`wasmer/wasmer-jni` bintray package]: https://bintray.com/wasmer/wasmer-jni/wasmer-jni [java docs]: https://github.com/wasmerio/wasmer-java/#api-of-the-wasmer-library [elixir logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/elixir.svg [elixir integration]: https://github.com/tessi/wasmex [elixir docs]: https://hexdocs.pm/wasmex/api-reference.html [`wasmex` hex package]: https://hex.pm/packages/wasmex [r logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/r.svg [r integration]: https://github.com/dirkschumacher/wasmr [r docs]: https://github.com/dirkschumacher/wasmr#example [postgres logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/postgres.svg [postgres integration]: https://github.com/wasmerio/wasmer-postgres [postgres docs]: https://github.com/wasmerio/wasmer-postgres#usage--documentation [swift integration]: https://github.com/AlwaysRightInstitute/SwiftyWasmer [zig logo]: https://raw.githubusercontent.com/ziglang/logo/master/zig-favicon.png [zig integration]: https://github.com/zigwasm/wasmer-zig ## コントリビューション **どんな形での貢献も歓迎です。コミュニティの新しいメンバーからの貢献は特に歓迎します。** 💜 Wasmer ランタイムのビルド方法は、[素晴らしいドキュメント](https://docs.wasmer.io/ecosystem/wasmer/building-from-source)で確認できます! ### テスト テストを実行したいですか? [Wasmer docs で方法を説明](https://docs.wasmer.io/ecosystem/wasmer/building-from-source/testing)しています。 ## コミュニティ Wasmer には、開発者とコントリビューターの素晴らしいコミュニティがあります。ようこそ! あなたも是非参加してください! 👋 ### チャンネル - [Slack](https://slack.wasmer.io/) - [Twitter](https://twitter.com/wasmerio) - [Facebook](https://www.facebook.com/wasmerio) - [Email](mailto:hello@wasmer.io) # Custom wast tests In this directory we have created wast tests for different cases where we want to test other scenarios than the ones offered by the standard WebAssembly spectests. ## NaN canonicalization: `nan-canonicalization.wast` This is an extra set of tests that assure that operations with NaNs are deterministic regarless of the environment/chipset where it executes in. ## Call Indirect Spilled Stack: `call-indirect-spilledd-stack.wast` We had an issue occuring that was making singlepass not working properly on the WebAssembly benchmark: https://00f.net/2019/10/22/updated-webassembly-benchmark/. This is a test case to ensure it doesn't reproduce again in the future. ## Multiple Traps: `multiple-traps.wast` This is a test assuring functions that trap can be called multiple times. ## Fac: `fac.wast` This is a simple factorial program. ## Check that struct-return on the stack doesn't overflow: `stack-overflow-sret.wast` Stack space for a structure returning function call should be allocated once up front, not once in each call. # Wasmer Benches This directory contains small, punctual benches. Other benchmarks are landing somewhere else. We will update this section soon. # `wasmer-engine` [![Build Status](https://github.com/wasmerio/wasmer/workflows/build/badge.svg?style=flat-square)](https://github.com/wasmerio/wasmer/actions?query=workflow%3Abuild) [![Join Wasmer Slack](https://img.shields.io/static/v1?label=Slack&message=join%20chat&color=brighgreen&style=flat-square)](https://slack.wasmer.io) [![MIT License](https://img.shields.io/github/license/wasmerio/wasmer.svg?style=flat-square)](https://github.com/wasmerio/wasmer/blob/master/LICENSE) This crate is the general abstraction for creating Engines in Wasmer. Wasmer Engines are mainly responsible for two things: * Transform the compilation code (from any Wasmer Compiler) to **create** an `Artifact`, * **Load** an`Artifact` so it can be used by the user (normally, pushing the code into executable memory and so on). It currently has three implementations: 1. Universal with [`wasmer-engine-universal`], 2. Native with [`wasmer-engine-dylib`], 3. Object with [`wasmer-engine-staticlib`]. ## Example Implementation Please check [`wasmer-engine-dummy`] for an example implementation for an `Engine`. ### Acknowledgments This project borrowed some of the code of the trap implementation from the [`wasmtime-api`], the code since then has evolved significantly. Please check [Wasmer `ATTRIBUTIONS`] to further see licenses and other attributions of the project. [`wasmer-engine-universal`]: https://github.com/wasmerio/wasmer/tree/master/lib/engine-universal [`wasmer-engine-dylib`]: https://github.com/wasmerio/wasmer/tree/master/lib/engine-dylib [`wasmer-engine-staticlib`]: https://github.com/wasmerio/wasmer/tree/master/lib/engine-staticlib [`wasmer-engine-dummy`]: https://github.com/wasmerio/wasmer/tree/master/tests/lib/engine-dummy [`wasmtime-api`]: https://crates.io/crates/wasmtime [Wasmer `ATTRIBUTIONS`]: https://github.com/wasmerio/wasmer/blob/master/ATTRIBUTIONS.md Amalgamated WebAssembly Test Suite ================================== This repository holds a mirror of the WebAssembly core testsuite which is maintained [here](https://github.com/WebAssembly/spec/tree/master/test/core), as well as the tests from the various [proposals repositories](https://github.com/WebAssembly/proposals/blob/master/README.md). In addition it also contains tests from various proposals which are currently forks of the primary spec repo. To add new tests or report problems in existing tests, please file issues and PRs within the spec or individual proposal repositories rather than within this mirror repository. To update the tests in this repo from their upstream sources: 1. Run `update-tests.sh` # Wasmer Fuzz Testing [Fuzz testing](https://en.wikipedia.org/wiki/Fuzzing) is: > An automated testing technique that involves providing invalid, > unexpected, or random data as inputs to a program. We use fuzz testing to automatically discover bugs in the Wasmer runtime. This `fuzz/` directory contains the configuration and the fuzz tests for Wasmer. To generate and to run the fuzz tests, we use the [`cargo-fuzz`] library. ## Installation You may need to install the [`cargo-fuzz`] library to get the `cargo fuzz` subcommand. Use ```sh $ cargo install cargo-fuzz ``` `cargo-fuzz` is documented in the [Rust Fuzz Book](https://rust-fuzz.github.io/book/cargo-fuzz.html). ## Running a fuzzer This directory provides multiple fuzzers, like for example `validate`. You can run it with: ```sh $ cargo fuzz run validate ``` Another example with the `universal_cranelift` fuzzer: ```sh $ cargo fuzz run universal_cranelift ``` See the [`fuzz/fuzz_targets`](https://github.com/wasmerio/wasmer/tree/fuzz/fuzz_targets/) directory for the full list of fuzzers. You should see output that looks something like this: ``` #1408022 NEW cov: 115073 ft: 503843 corp: 4659/1807Kb lim: 4096 exec/s: 889 rss: 857Mb L: 2588/4096 MS: 1 ChangeASCIIInt- #1408273 NEW cov: 115073 ft: 503844 corp: 4660/1808Kb lim: 4096 exec/s: 888 rss: 857Mb L: 1197/4096 MS: 1 ShuffleBytes- #1408534 NEW cov: 115073 ft: 503866 corp: 4661/1809Kb lim: 4096 exec/s: 886 rss: 857Mb L: 977/4096 MS: 1 ShuffleBytes- #1408540 NEW cov: 115073 ft: 503869 corp: 4662/1811Kb lim: 4096 exec/s: 886 rss: 857Mb L: 2067/4096 MS: 1 ChangeBit- #1408831 NEW cov: 115073 ft: 503945 corp: 4663/1811Kb lim: 4096 exec/s: 885 rss: 857Mb L: 460/4096 MS: 1 CMP- DE: "\x16\x00\x00\x00\x00\x00\x00\x00"- #1408977 NEW cov: 115073 ft: 503946 corp: 4664/1813Kb lim: 4096 exec/s: 885 rss: 857Mb L: 1972/4096 MS: 1 ShuffleBytes- #1408999 NEW cov: 115073 ft: 503949 corp: 4665/1814Kb lim: 4096 exec/s: 884 rss: 857Mb L: 964/4096 MS: 2 ChangeBit-ShuffleBytes- #1409040 NEW cov: 115073 ft: 503950 corp: 4666/1814Kb lim: 4096 exec/s: 884 rss: 857Mb L: 90/4096 MS: 1 ChangeBit- #1409042 NEW cov: 115073 ft: 503951 corp: 4667/1814Kb lim: 4096 exec/s: 884 rss: 857Mb L: 174/4096 MS: 2 ChangeByte-ChangeASCIIInt- ``` It will continue to generate random inputs forever, until it finds a bug or is terminated. The testcases for bugs it finds go into `fuzz/artifacts/universal_cranelift` and you can rerun the fuzzer on a single input by passing it on the command line `cargo fuzz run universal_cranelift /path/to/testcase`. ## The corpus Each fuzzer has an individual corpus under `fuzz/corpus/test_name`, created on first run if not already present. The fuzzers use `wasm-smith` which means that the testcase files are random number seeds input to the Wasm generator, not `.wasm` files themselves. In order to debug a testcase, you may find that you need to convert it into a `.wasm` file. Using the standalone `wasm-smith` tool doesn't work for this purpose because we use a custom configuration to our `wasm_smith::Module`. Instead, our fuzzers use an environment variable `DUMP_TESTCASE=path`. For example: ```sh $ DUMP_TESTCASE=/tmp/crash.wasm cargo fuzz run --features=universal,singlepass universal_singlepass fuzz/artifacts/universal_singlepass/crash-0966412eab4f89c52ce5d681807c8030349470f6 ``` [`cargo-fuzz`]: https://github.com/rust-fuzz/cargo-fuzz <div align="center"> <a href="https://wasmer.io" target="_blank" rel="noopener noreferrer"> <img width="300" src="https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/logo.png" alt="Logo Wasmer"> </a> <p> <a href="https://github.com/wasmerio/wasmer/actions?query=workflow%3Abuild"> <img src="https://github.com/wasmerio/wasmer/workflows/build/badge.svg?style=flat-square" alt="État des tests"> </a> <a href="https://github.com/wasmerio/wasmer/blob/master/LICENSE"> <img src="https://img.shields.io/github/license/wasmerio/wasmer.svg?style=flat-square" alt="Licence"> </a> <a href="https://slack.wasmer.io"> <img src="https://img.shields.io/static/v1?label=Slack&message=join%20chat&color=brighgreen&style=flat-square" alt="Salon Slack"> </a> </p> <h3> <a href="https://wasmer.io/">Web</a> <span> • </span> <a href="https://docs.wasmer.io">Documentation</a> <span> • </span> <a href="https://slack.wasmer.io/">Chat</a> </h3> </div> <br /> [Wasmer](https://wasmer.io/) permet l'utilisation de conteneurs super légers basés sur [WebAssembly](https://webassembly.org/) qui peuvent fonctionner n'importe où : du bureau au cloud en passant par les appareils IoT, et également intégrés dans [*une multitude de langages de programmation*](https://github.com/wasmerio/wasmer#language-integrations). > This readme is also available in: [🇩🇪 Deutsch-Allemand](https://github.com/wasmerio/wasmer/blob/master/docs/de/README.md) • [🇬🇧 English-Anglaise](https://github.com/wasmerio/wasmer/blob/master/README.md) • [🇪🇸 Español-Espagnol](https://github.com/wasmerio/wasmer/blob/master/docs/es/README.md) • [🇨🇳 中文-Chinoise](https://github.com/wasmerio/wasmer/blob/master/docs/cn/README.md) • [🇯🇵 日本語-japonais](https://github.com/wasmerio/wasmer/blob/master/docs/ja/README.md) ## Fonctionnalités * **Rapide et sûr**. Wasmer exécute WebAssembly à une vitesse *quasi native* dans un environnement entièrement contrôlé (bac à sable, _sandbox_). * **Modulaire**. Wasmer prend en charge différents frameworks de compilation pour répondre au mieux à vos besoins (LLVM, Cranelift ...). * **Universel**. Vous pouvez exécuter Wasmer sur n'importe quelle *plate-forme* (macOS, Linux et Windows) et *processeur*. * **Conforme aux normes**. Wasmer passe [la suite de tests officielle de WebAssembly](https://github.com/WebAssembly/testsuite) prenant en charge [WASI](https://github.com/WebAssembly/WASI) et [Emscripten](https://emscripten.org/) ## Quickstart Wasmer est livré sans aucune dépendance. Vous pouvez l'installer à l'aide des programmes d'installation ci-dessous : ```sh curl https://get.wasmer.io -sSfL | sh ``` <details> <summary>Avec PowerShell (Windows)</summary> <p> ```powershell iwr https://win.wasmer.io -useb | iex ``` </p> </details> > Voir [wasmer-install](https://github.com/wasmerio/wasmer-install) pour plus d'options d'installation: Homebrew, Scoop, Cargo... #### Exécution d'un fichier WebAssembly Après avoir installé Wasmer, vous devriez être prêt à exécuter votre premier fichier WebAssemby ! 🎉 Vous pouvez commencer par exécuter QuickJS : [qjs.wasm](https://registry-cdn.wapm.io/contents/_/quickjs/0.0.3/build/qjs.wasm) ```bash $ wasmer qjs.wasm QuickJS - Type "\h" for help qjs > ``` #### Voici ce que vous pouvez faire ensuite - [Utilisez Wasmer depuis votre application Rust](https://docs.wasmer.io/integrations/rust) - [Publier un paquet Wasm sur WAPM](https://docs.wasmer.io/ecosystem/wapm/publishing-your-package) - [En savoir plus sur Wasmer](https://medium.com/wasmer/) ## Intégrations 📦 Wasmer peut être utilisé comme une bibliothèque **intégrée dans différents langages**, vous pouvez donc utiliser WebAssembly _n'import où_. | &nbsp; | Langage de programmation | Package | Docs | |-|-|-|-| | ![Rust logo] | [**Rust**][Rust integration] | [`wasmer` Rust crate] | [Docs][rust docs] | ![C logo] | [**C/C++**][C integration] | [`wasmer.h` headers] | [Docs][c docs] | | ![C# logo] | [**C#**][C# integration] | [`WasmerSharp` NuGet package] | [Docs][c# docs] | | ![D logo] | [**D**][D integration] | [`wasmer` Dub package] | [Docs][d docs] | | ![Python logo] | [**Python**][Python integration] | [`wasmer` PyPI package] | [Docs][python docs] | | ![JS logo] | [**Javascript**][JS integration] | [`@wasmerio` NPM packages] | [Docs][js docs] | | ![Go logo] | [**Go**][Go integration] | [`wasmer` Go package] | [Docs][go docs] | | ![PHP logo] | [**PHP**][PHP integration] | [`wasm` PECL package] | [Docs][php docs] | | ![Ruby logo] | [**Ruby**][Ruby integration] | [`wasmer` Ruby Gem] | [Docs][ruby docs] | | ![Java logo] | [**Java**][Java integration] | [`wasmer/wasmer-jni` Bintray package] | [Docs][java docs] | | ![Elixir logo] | [**Elixir**][Elixir integration] | [`wasmex` hex package] | [Docs][elixir docs] | | ![R logo] | [**R**][R integration] | *no published package* | [Docs][r docs] | | ![Postgres logo] | [**Postgres**][Postgres integration] | *no published package* | [Docs][postgres docs] | | | [**Swift**][Swift integration] | *no published package* | | | ![Zig logo] | [**Zig**][Zig integration] | *no published package* | | [👋 Il manque un langage ?](https://github.com/wasmerio/wasmer/issues/new?assignees=&labels=%F0%9F%8E%89+enhancement&template=---feature-request.md&title=) [rust logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/rust.svg [rust integration]: https://github.com/wasmerio/wasmer/tree/master/lib/api [`wasmer` rust crate]: https://crates.io/crates/wasmer/ [rust docs]: https://wasmerio.github.io/wasmer/crates/wasmer [c logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/c.svg [c integration]: https://github.com/wasmerio/wasmer/tree/master/lib/c-api [`wasmer.h` headers]: https://wasmerio.github.io/wasmer/c/ [c docs]: https://wasmerio.github.io/wasmer/c/ [c# logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/csharp.svg [c# integration]: https://github.com/migueldeicaza/WasmerSharp [`wasmersharp` nuget package]: https://www.nuget.org/packages/WasmerSharp/ [c# docs]: https://migueldeicaza.github.io/WasmerSharp/ [d logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/d.svg [d integration]: https://github.com/chances/wasmer-d [`wasmer` Dub package]: https://code.dlang.org/packages/wasmer [d docs]: https://chances.github.io/wasmer-d [python logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/python.svg [python integration]: https://github.com/wasmerio/wasmer-python [`wasmer` pypi package]: https://pypi.org/project/wasmer/ [python docs]: https://github.com/wasmerio/wasmer-python#api-of-the-wasmer-extensionmodule [go logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/go.svg [go integration]: https://github.com/wasmerio/wasmer-go [`wasmer` go package]: https://pkg.go.dev/github.com/wasmerio/wasmer-go/wasmer [go docs]: https://pkg.go.dev/github.com/wasmerio/wasmer-go/wasmer?tab=doc [php logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/php.svg [php integration]: https://github.com/wasmerio/wasmer-php [`wasm` pecl package]: https://pecl.php.net/package/wasm [php docs]: https://wasmerio.github.io/wasmer-php/wasm/ [js logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/js.svg [js integration]: https://github.com/wasmerio/wasmer-js [`@wasmerio` npm packages]: https://www.npmjs.com/org/wasmer [js docs]: https://docs.wasmer.io/integrations/js/reference-api [ruby logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/ruby.svg [ruby integration]: https://github.com/wasmerio/wasmer-ruby [`wasmer` ruby gem]: https://rubygems.org/gems/wasmer [ruby docs]: https://www.rubydoc.info/gems/wasmer/ [java logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/java.svg [java integration]: https://github.com/wasmerio/wasmer-java [`wasmer/wasmer-jni` bintray package]: https://bintray.com/wasmer/wasmer-jni/wasmer-jni [java docs]: https://github.com/wasmerio/wasmer-java/#api-of-the-wasmer-library [elixir logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/elixir.svg [elixir integration]: https://github.com/tessi/wasmex [elixir docs]: https://hexdocs.pm/wasmex/api-reference.html [`wasmex` hex package]: https://hex.pm/packages/wasmex [r logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/r.svg [r integration]: https://github.com/dirkschumacher/wasmr [r docs]: https://github.com/dirkschumacher/wasmr#example [postgres logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/postgres.svg [postgres integration]: https://github.com/wasmerio/wasmer-postgres [postgres docs]: https://github.com/wasmerio/wasmer-postgres#usage--documentation [swift integration]: https://github.com/AlwaysRightInstitute/SwiftyWasmer [zig logo]: https://raw.githubusercontent.com/ziglang/logo/master/zig-favicon.png [zig integration]: https://github.com/zigwasm/wasmer-zig ## Contribuer **Nous accueillons toutes formes de contributions, en particulier de la part des nouveaux membres de notre communauté**. 💜 Vous pouvez vérifier comment compiler Wasmer dans [notre documentation](https://docs.wasmer.io/ecosystem/wasmer/building-from-source)! ### Test Vous voulez des tests ? La [documentation de Wasmer](https://docs.wasmer.io/ecosystem/wasmer/building-from-source/testing) vous montrera comment les exécuter. ## Communauté Wasmer a une incroyable communauté de développeurs et de contributeurs. Bienvenue et rejoignez-nous ! 👋 ### Canaux de communications - [Slack](https://slack.wasmer.io/) - [Twitter](https://twitter.com/wasmerio) - [Facebook](https://www.facebook.com/wasmerio) - [Email](mailto:hello@wasmer.io) # Wasmer Documentation Assets This directory contains documentation assets. # Wasmer Documentation Wasmer provides multiple documentations. Here are some pointers: * [The Wasmer runtime `README.md`](https://github.com/wasmerio/wasmer/blob/master/README.md) is a good start for the first steps, like installations, first runs etc., * [The public documentation](https://docs.wasmer.io/) contains all the documentation you need to learn about Wasmer and WebAssembly, * [The Rust crates documentations](https://wasmerio.github.io/wasmer/) contain all the documentations to use the `wasmer-*` Rust crates, with many examples, * [The collection of examples](https://github.com/wasmerio/wasmer/blob/master/examples/README.md) illustrates how to use Wasmer and its numerous features through very commented examples, * [Documentations for all embeddings/language integrations](https://github.com/wasmerio/wasmer/blob/master/README.md): the Wasmer runtime can be embeddeded in various languages or environments, each embedding provides its own documentation, book etc., * [OS distro packaging notes](https://github.com/wasmerio/wasmer/blob/master/PACKAGING.md) contains notes about how to package Wasmer for OS distributions. # `wasmer-compiler` [![Build Status](https://github.com/wasmerio/wasmer/workflows/build/badge.svg?style=flat-square)](https://github.com/wasmerio/wasmer/actions?query=workflow%3Abuild) [![Join Wasmer Slack](https://img.shields.io/static/v1?label=Slack&message=join%20chat&color=brighgreen&style=flat-square)](https://slack.wasmer.io) [![MIT License](https://img.shields.io/github/license/wasmerio/wasmer.svg?style=flat-square)](https://github.com/wasmerio/wasmer/blob/master/LICENSE) This crate is the base for Compiler implementations. It performs the translation from a Wasm module into a basic `ModuleInfo`, but leaves the Wasm function bytecode translation to the compiler implementor. Here are some of the Compilers provided by Wasmer: * [Singlepass](https://github.com/wasmerio/wasmer/tree/master/lib/compiler-singlepass), * [Cranelift](https://github.com/wasmerio/wasmer/tree/master/lib/compiler-cranelift), * [LLVM](https://github.com/wasmerio/wasmer/tree/master/lib/compiler-llvm). ## How to create a compiler To create a compiler, one needs to implement two traits: 1. `CompilerConfig`, that configures and creates a new compiler, 2. `Compiler`, the compiler itself that will compile a module. ```rust /// The compiler configuration options. pub trait CompilerConfig { /// Gets the custom compiler config fn compiler(&self) -> Box<dyn Compiler>; } /// An implementation of a compiler from parsed WebAssembly module to compiled native code. pub trait Compiler { /// Compiles a parsed module. /// /// It returns the [`Compilation`] or a [`CompileError`]. fn compile_module<'data, 'module>( &self, target: &Target, compile_info: &'module CompileModuleInfo, module_translation: &ModuleTranslationState, // The list of function bodies function_body_inputs: PrimaryMap<LocalFunctionIndex, FunctionBodyData<'data>>, ) -> Result<Compilation, CompileError>; } ``` ## Acknowledgments This project borrowed some of the code strucutre from the [`cranelift-wasm`] crate, however it's been adapted to not depend on any specific IR and be abstract of any compiler. Please check [Wasmer `ATTRIBUTIONS`] to further see licenses and other attributions of the project. [`cranelift-wasm`]: https://crates.io/crates/cranelift-wasm [Wasmer `ATTRIBUTIONS`]: https://github.com/wasmerio/wasmer/blob/master/ATTRIBUTIONS.md # `wasmer-cli` [![Build Status](https://github.com/wasmerio/wasmer/workflows/build/badge.svg?style=flat-square)](https://github.com/wasmerio/wasmer/actions?query=workflow%3Abuild) [![Join Wasmer Slack](https://img.shields.io/static/v1?label=Slack&message=join%20chat&color=brighgreen&style=flat-square)](https://slack.wasmer.io) [![MIT License](https://img.shields.io/github/license/wasmerio/wasmer.svg?style=flat-square)](https://github.com/wasmerio/wasmer/blob/master/LICENSE) This crate is the Wasmer CLI. The recommended way to install `wasmer` is via the [wasmer-installer](https://github.com/wasmerio/wasmer-install). However, you can also install `wasmer` via Cargo (you will need to specify the compilers to use): ```bash cargo install wasmer-cli --features "singlepass,cranelift" ``` Or by building it inside the codebase: ```bash cargo build --release --features "singlepass,cranelift" ``` > Note: installing `wasmer` via Cargo (or manual install) will not install > the WAPM cli. If you want to use them together, please use the [wasmer installer](https://github.com/wasmerio/wasmer-install). ## Features The Wasmer supports the following features: * `wat` (default): support for executing WebAssembly text files. * `wast`(default): support for running wast test files. * `universal` (default): support for the [Universal engine]. * `dylib` (default): support for the [Dylib engine]. * `cache` (default): support or automatically caching compiled artifacts. * `wasi` (default): support for [WASI]. * `experimental-io-devices`: support for experimental IO devices in WASI. * `emscripten` (default): support for [Emscripten]. * `singlepass`: support for the [Singlepass compiler]. * `cranelift`: support for the [Cranelift compiler]. * `llvm`: support for the [LLVM compiler]. [Universal engine]: https://github.com/wasmerio/wasmer/tree/master/lib/engine-universal/ [Dylib engine]: https://github.com/wasmerio/wasmer/tree/master/lib/engine-dylib/ [WASI]: https://github.com/wasmerio/wasmer/tree/master/lib/wasi/ [Emscripten]: https://github.com/wasmerio/wasmer/tree/master/lib/emscripten/ [Singlepass compiler]: https://github.com/wasmerio/wasmer/tree/master/lib/compiler-singlepass/ [Cranelift compiler]: https://github.com/wasmerio/wasmer/tree/master/lib/compiler-cranelift/ [LLVM compiler]: https://github.com/wasmerio/wasmer/tree/master/lib/compiler-llvm/ ## CLI commands Once you have Wasmer installed, you can start executing WebAssembly files easily: Get the current Wasmer version: ```bash wasmer -V ``` Execute a WebAssembly file: ```bash wasmer run myfile.wasm ``` Compile a WebAssembly file: ```bash wasmer compile myfile.wasm -o myfile.so --dylib ``` Run a compiled WebAssembly file (fastest): ```bash wasmer run myfile.so ``` <div align="center"> <a href="https://wasmer.io" target="_blank" rel="noopener noreferrer"> <img width="300" src="https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/logo.png" alt="Wasmer logo"> </a> <p> <a href="https://github.com/wasmerio/wasmer/actions?query=workflow%3Abuild"> <img src="https://github.com/wasmerio/wasmer/workflows/build/badge.svg?style=flat-square" alt="Build Status"> </a> <a href="https://github.com/wasmerio/wasmer/blob/master/LICENSE"> <img src="https://img.shields.io/github/license/wasmerio/wasmer.svg?style=flat-square" alt="License"> </a> <a href="https://slack.wasmer.io"> <img src="https://img.shields.io/static/v1?label=Slack&message=join%20chat&color=brighgreen&style=flat-square" alt="Slack channel"> </a> </p> <h3> <a href="https://wasmer.io/">Web</a> <span> • </span> <a href="https://docs.wasmer.io">Documentación</a> <span> • </span> <a href="https://slack.wasmer.io/">Chat</a> </h3> </div> <br /> [Wasmer](https://wasmer.io/) hace posible tener contenedores ultraligeros basados en [WebAssembly](https://webassembly.org/) que pueden ser ejecutados en cualquier sitio: desde tu ordenador hasta la nube y dispositivos de IoT, además de poder ser ejecutados [*en cualquier lenguaje de programación*](https://github.com/wasmerio/wasmer#language-integrations). > This README is also available in: [🇩🇪 Deutsch-Alemán](https://github.com/wasmerio/wasmer/blob/master/docs/de/README.md) • [🇬🇧 English-Inglés](https://github.com/wasmerio/wasmer/blob/master/README.md) • [🇫🇷 Français-Francés](https://github.com/wasmerio/wasmer/blob/master/docs/fr/README.md) • [🇨🇳 中文-Chino](https://github.com/wasmerio/wasmer/blob/master/docs/cn/README.md) • [🇯🇵 日本語-japonés](https://github.com/wasmerio/wasmer/blob/master/docs/ja/README.md). ## Funcionalidades * **Rápido y Seguro**. Wasmer ejecuta WebAssembly a velocidades *nativas* en un entorno completamente protegido. * **Extendible**. Wasmer soporta diferentes métodos de compilación dependiendo de tus necesidades (LLVM, Cranelift...). * **Universal**. Puedes ejecutar Wasmer en cualquier *platforma* (macOS, Linux y Windows) y *chip*. * **Respeta los estándares**. Wasmer pasa los [tests oficiales de WebAssembly](https://github.com/WebAssembly/testsuite) siendo compatible con [WASI](https://github.com/WebAssembly/WASI) y [Emscripten](https://emscripten.org/). ## Empezamos? Wasmer no requiere ninguna dependencia. Puedes instalarlo con uno de éstos instaladores: ```sh curl https://get.wasmer.io -sSfL | sh ``` <details> <summary>Con PowerShell (Windows)</summary> <p> ```powershell iwr https://win.wasmer.io -useb | iex ``` </p> </details> > Visita [wasmer-install](https://github.com/wasmerio/wasmer-install) para más opciones de instalación: Homebrew, Scoop, Cargo... #### Ejecuta un archivo WebAssembly ¡Después de instalar Wasmer deberías estar listo para ejecutar tu primer módulo de WebAssembly! 🎉 Puedes empezar corriendo QuickJS: [qjs.wasm](https://registry-cdn.wapm.io/contents/_/quickjs/0.0.3/build/qjs.wasm) ```bash $ wasmer qjs.wasm QuickJS - Type "\h" for help qjs > ``` #### Esto es lo que puedes hacer: - [Usa Wasmer desde tu aplicación de Rust](https://docs.wasmer.io/integrations/rust) - [Publica un paquete de Wasm en WAPM](https://docs.wasmer.io/ecosystem/wapm/publishing-your-package) - [Lee más sobre Wasmer](https://medium.com/wasmer/) ## Integraciones en diferentes Lenguajes 📦 Wasmer puede ser usado como una librería **integrado en diferentes lenguajes de programación**, para que puedas ejecutar WebAssembly _en cualquier sitio_. | &nbsp; | Lenguaje | Librería | Documentación | |-|-|-|-| | ![Rust logo] | [**Rust**][Rust integration] | [`wasmer` en crates.io] | [Documentación][rust docs] | ![C logo] | [**C/C++**][C integration] | [cabecera `wasmer.h`] | [Documentación][c docs] | | ![C# logo] | [**C#**][C# integration] | [`WasmerSharp` en NuGet] | [Documentación][c# docs] | | ![D logo] | [**D**][D integration] | [`wasmer` en Dug] | [Documentación][d docs] | | ![Python logo] | [**Python**][Python integration] | [`wasmer` en PyPI] | [Documentación][python docs] | | ![JS logo] | [**Javascript**][JS integration] | [`@wasmerio` en NPM] | [Documentación][js docs] | | ![Go logo] | [**Go**][Go integration] | [`wasmer` en Go] | [Documentación][go docs] | | ![PHP logo] | [**PHP**][PHP integration] | [`wasm` en PECL] | [Documentación][php docs] | | ![Ruby logo] | [**Ruby**][Ruby integration] | [`wasmer` en Ruby Gems] | [Documentación][ruby docs] | | ![Java logo] | [**Java**][Java integration] | [`wasmer/wasmer-jni` en Bintray] | [Documentación][java docs] | | ![Elixir logo] | [**Elixir**][Elixir integration] | [`wasmex` en hex] | [Documentación][elixir docs] | | ![R logo] | [**R**][R integration] | *sin paquete publicado* | [Documentación][r docs] | | ![Postgres logo] | [**Postgres**][Postgres integration] | *sin paquete publicado* | [Documentación][postgres docs] | | | [**Swift**][Swift integration] | *sin paquete publicado* | | | ![Zig logo] | [**Zig**][Zig integration] | *no published package* | | [👋 Falta algún lenguaje?](https://github.com/wasmerio/wasmer/issues/new?assignees=&labels=%F0%9F%8E%89+enhancement&template=---feature-request.md&title=) [rust logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/rust.svg [rust integration]: https://github.com/wasmerio/wasmer/tree/master/lib/api [`wasmer` en crates.io]: https://crates.io/crates/wasmer/ [rust docs]: https://wasmerio.github.io/wasmer/crates/wasmer [c logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/c.svg [c integration]: https://github.com/wasmerio/wasmer/tree/master/lib/c-api [cabecera `wasmer.h`]: https://wasmerio.github.io/wasmer/c/ [c docs]: https://wasmerio.github.io/wasmer/c/ [c# logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/csharp.svg [c# integration]: https://github.com/migueldeicaza/WasmerSharp [`wasmersharp` en NuGet]: https://www.nuget.org/packages/WasmerSharp/ [c# docs]: https://migueldeicaza.github.io/WasmerSharp/ [d logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/d.svg [d integration]: https://github.com/chances/wasmer-d [`wasmer` en Dub]: https://code.dlang.org/packages/wasmer [d docs]: https://chances.github.io/wasmer-d [python logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/python.svg [python integration]: https://github.com/wasmerio/wasmer-python [`wasmer` en pypi]: https://pypi.org/project/wasmer/ [python docs]: https://github.com/wasmerio/wasmer-python#api-of-the-wasmer-extensionmodule [go logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/go.svg [go integration]: https://github.com/wasmerio/wasmer-go [`wasmer` en go]: https://pkg.go.dev/github.com/wasmerio/wasmer-go/wasmer [go docs]: https://pkg.go.dev/github.com/wasmerio/wasmer-go/wasmer?tab=doc [php logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/php.svg [php integration]: https://github.com/wasmerio/wasmer-php [php docs]: https://wasmerio.github.io/wasmer-php/wasm/ [`wasm` en pecl]: https://pecl.php.net/package/wasm [js logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/js.svg [js integration]: https://github.com/wasmerio/wasmer-js [`@wasmerio` en npm]: https://www.npmjs.com/org/wasmer [js docs]: https://docs.wasmer.io/integrations/js/reference-api [ruby logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/ruby.svg [ruby integration]: https://github.com/wasmerio/wasmer-ruby [`wasmer` en ruby gems]: https://rubygems.org/gems/wasmer [ruby docs]: https://www.rubydoc.info/gems/wasmer/ [java logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/java.svg [java integration]: https://github.com/wasmerio/wasmer-java [`wasmer/wasmer-jni` en bintray]: https://bintray.com/wasmer/wasmer-jni/wasmer-jni [java docs]: https://github.com/wasmerio/wasmer-java/#api-of-the-wasmer-library [elixir logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/elixir.svg [elixir integration]: https://github.com/tessi/wasmex [elixir docs]: https://hexdocs.pm/wasmex/api-reference.html [`wasmex` en hex]: https://hex.pm/packages/wasmex [r logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/r.svg [r integration]: https://github.com/dirkschumacher/wasmr [r docs]: https://github.com/dirkschumacher/wasmr#example [postgres logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/postgres.svg [postgres integration]: https://github.com/wasmerio/wasmer-postgres [postgres docs]: https://github.com/wasmerio/wasmer-postgres#usage--documentation [swift integration]: https://github.com/AlwaysRightInstitute/SwiftyWasmer [zig logo]: https://raw.githubusercontent.com/ziglang/logo/master/zig-favicon.png [zig integration]: https://github.com/zigwasm/wasmer-zig ## Contribuye **Damos la bienvenida a cualquier forma de contribución, especialmente a los nuevos miembros de la comunidad** 💜 ¡Puedes ver cómo crear el binario de Wasmer con [nuestros increíbles documentos](https://docs.wasmer.io/ecosystem/wasmer/building-from-source)! ### Tests Testear quieres? Los [documentos de Wasmer te enseñarán cómo](https://docs.wasmer.io/ecosystem/wasmer/building-from-source/testing). ## Comunidad Wasmer tiene una comunidad increíble de desarrolladores y colaboradores ¡Bienvenido, únete a nosotros! 👋 ### Medios - [Slack](https://slack.wasmer.io/) - [Twitter](https://twitter.com/wasmerio) - [Facebook](https://www.facebook.com/wasmerio) - [Email](mailto:hello@wasmer.io) <div align="center"> <a href="https://wasmer.io" target="_blank" rel="noopener noreferrer"> <img width="300" src="https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/logo.png" alt="Wasmer logo"> </a> <p> <a href="https://github.com/wasmerio/wasmer/actions?query=workflow%3Abuild"> <img src="https://github.com/wasmerio/wasmer/workflows/build/badge.svg?style=flat-square" alt="Build Status"> </a> <a href="https://github.com/wasmerio/wasmer/blob/master/LICENSE"> <img src="https://img.shields.io/github/license/wasmerio/wasmer.svg" alt="License"> </a> <a href="https://docs.wasmer.io"> <img src="https://img.shields.io/static/v1?label=Docs&message=docs.wasmer.io&color=blue" alt="Wasmer Docs"> </a> <a href="https://slack.wasmer.io"> <img src="https://img.shields.io/static/v1?label=Slack&message=join%20us!&color=brighgreen" alt="Slack channel"> </a> </p> </div> <br /> Wasmer is a _fast_ and _secure_ [**WebAssembly**](https://webassembly.org) runtime that enables super _lightweight containers_ to run anywhere: from *Desktop* to the *Cloud*, *Edge* and *IoT* devices. > _This document is also available in: [🇨🇳 中 文 -Chinese](https://github.com/wasmerio/wasmer/blob/master/docs/cn/README.md) • [🇩🇪 Deutsch-German](https://github.com/wasmerio/wasmer/blob/master/docs/de/README.md) • [🇪🇸 Español-Spanish](https://github.com/wasmerio/wasmer/blob/master/docs/es/README.md) • [🇫🇷 Français-French](https://github.com/wasmerio/wasmer/blob/master/docs/fr/README.md) • [🇯🇵 日本 語 -Japanese](https://github.com/wasmerio/wasmer/blob/master/docs/ja/README.md) • [🇰🇷 한국인 -Korean](https://github.com/wasmerio/wasmer/blob/master/docs/ko/README.md)_. ### Features * Secure by default. No file, network, or environment access, unless explicitly enabled. * Supports [WASI](https://github.com/WebAssembly/WASI) and [Emscripten](https://emscripten.org/) out of the box. * Fast. Run WebAssembly at near-native speeds. * Embeddable in [multiple programming languages](https://github.com/wasmerio/wasmer/#-language-integrations) * Compliant with latest WebAssembly Proposals (SIMD, Reference Types, Threads, ...) ### Install Wasmer CLI ships as a single executable with no dependencies. ```sh curl https://get.wasmer.io -sSfL | sh ``` <details> <summary>Other installation options (Powershell, Brew, Cargo, ...)</summary> _Wasmer can be installed from various package managers. Choose the one that fits best for your environment:_ * Powershell (Windows) ```powershell iwr https://win.wasmer.io -useb | iex ``` * <a href="https://formulae.brew.sh/formula/wasmer">Homebrew</a> (macOS, Linux) ```sh brew install wasmer ``` * <a href="https://github.com/ScoopInstaller/Main/blob/master/bucket/wasmer.json">Scoop</a> (Windows) ```sh scoop install wasmer ``` * <a href="https://chocolatey.org/packages/wasmer">Chocolatey</a> (Windows) ```sh choco install wasmer ``` * <a href="https://crates.io/crates/wasmer-cli/">Cargo</a> _Note: All the available features are described in the [`wasmer-cli` crate docs](https://github.com/wasmerio/wasmer/tree/master/lib/cli/README.md)_ ```sh cargo install wasmer-cli ``` > Looking for more installation options? See [the `wasmer-install` repository](https://github.com/wasmerio/wasmer-install) to learn more! </details> ### Quickstart You can start by running [QuickJS](https://github.com/bellard/quickjs/), a small and embeddable Javascript engine compiled as a WebAssembly module ([`qjs.wasm`](https://registry-cdn.wapm.io/contents/_/quickjs/0.0.3/build/qjs.wasm)): ```bash $ wasmer qjs.wasm QuickJS - Type "\h" for help qjs > const i = 1 + 2; qjs > console.log("hello " + i); hello 3 ``` #### Here is what you can do next: - [Use Wasmer from your Rust application](https://docs.wasmer.io/integrations/rust) - [Publish a Wasm package on WAPM](https://docs.wasmer.io/ecosystem/wapm/publishing-your-package) - [Read more about Wasmer](https://medium.com/wasmer/) ## 📦 Language Integrations The Wasmer runtime can be used as a library **embedded in different languages**, so you can use WebAssembly _anywhere_. | | Language | Package | Documentation | |-|-|-|-| | ![Rust logo] | [**Rust**][Rust integration] | [`wasmer` Rust crate] | [Learn][rust docs] | ![C logo] | [**C/C++**][C integration] | [`wasmer.h` header] | [Learn][c docs] | | ![C# logo] | [**C#**][C# integration] | [`WasmerSharp` NuGet package] | [Learn][c# docs] | | ![D logo] | [**D**][D integration] | [`wasmer` Dub package] | [Learn][d docs] | | ![Python logo] | [**Python**][Python integration] | [`wasmer` PyPI package] | [Learn][python docs] | | ![JS logo] | [**Javascript**][JS integration] | [`@wasmerio` NPM packages] | [Learn][js docs] | | ![Go logo] | [**Go**][Go integration] | [`wasmer` Go package] | [Learn][go docs] | | ![PHP logo] | [**PHP**][PHP integration] | [`wasm` PECL package] | [Learn][php docs] | | ![Ruby logo] | [**Ruby**][Ruby integration] | [`wasmer` Ruby Gem] | [Learn][ruby docs] | | ![Java logo] | [**Java**][Java integration] | [`wasmer/wasmer-jni` Bintray package] | [Learn][java docs] | | ![Elixir logo] | [**Elixir**][Elixir integration] | [`wasmex` hex package] | [Learn][elixir docs] | | ![R logo] | [**R**][R integration] | *no published package* | [Learn][r docs] | | ![Postgres logo] | [**Postgres**][Postgres integration] | *no published package* | [Learn][postgres docs] | | ![Swift logo] | [**Swift**][Swift integration] | *no published package* | | | ![Zig logo] | [**Zig**][Zig integration] | *no published package* | | | ![Dart logo] | [**Dart**][Dart integration] | [`wasm` pub package] | | | ![Crystal logo] | [**Crystal**][Crystal integration] | *no published package* | [Learn][crystal docs] | | ![Lisp logo] | [**Lisp**][Lisp integration] | *under heavy development - no published package* | | [👋&nbsp;&nbsp;Missing a language?](https://github.com/wasmerio/wasmer/issues/new?assignees=&labels=%F0%9F%8E%89+enhancement&template=---feature-request.md&title=) [rust logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/rust.svg [rust integration]: https://github.com/wasmerio/wasmer/tree/master/lib/api [`wasmer` rust crate]: https://crates.io/crates/wasmer/ [rust docs]: https://docs.rs/wasmer/ [c logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/c.svg [c integration]: https://github.com/wasmerio/wasmer/tree/master/lib/c-api [`wasmer.h` header]: https://github.com/wasmerio/wasmer/blob/master/lib/c-api/wasmer.h [c docs]: https://docs.rs/wasmer-c-api/*/wasmer_c_api/wasm_c_api/index.html [c# logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/csharp.svg [c# integration]: https://github.com/migueldeicaza/WasmerSharp [`wasmersharp` nuget package]: https://www.nuget.org/packages/WasmerSharp/ [c# docs]: https://migueldeicaza.github.io/WasmerSharp/ [d logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/d.svg [d integration]: https://github.com/chances/wasmer-d [`wasmer` Dub package]: https://code.dlang.org/packages/wasmer [d docs]: https://chances.github.io/wasmer-d [python logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/python.svg [python integration]: https://github.com/wasmerio/wasmer-python [`wasmer` pypi package]: https://pypi.org/project/wasmer/ [python docs]: https://wasmerio.github.io/wasmer-python/api/wasmer/ [go logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/go.svg [go integration]: https://github.com/wasmerio/wasmer-go [`wasmer` go package]: https://pkg.go.dev/github.com/wasmerio/wasmer-go/wasmer [go docs]: https://pkg.go.dev/github.com/wasmerio/wasmer-go/wasmer?tab=doc [php logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/php.svg [php integration]: https://github.com/wasmerio/wasmer-php [`wasm` pecl package]: https://pecl.php.net/package/wasm [php docs]: https://wasmerio.github.io/wasmer-php/ [js logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/js.svg [js integration]: https://github.com/wasmerio/wasmer-js [`@wasmerio` npm packages]: https://www.npmjs.com/org/wasmer [js docs]: https://docs.wasmer.io/integrations/js/reference-api [ruby logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/ruby.svg [ruby integration]: https://github.com/wasmerio/wasmer-ruby [`wasmer` ruby gem]: https://rubygems.org/gems/wasmer [ruby docs]: https://wasmerio.github.io/wasmer-ruby/wasmer_ruby/index.html [java logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/java.svg [java integration]: https://github.com/wasmerio/wasmer-java [`wasmer/wasmer-jni` bintray package]: https://bintray.com/wasmer/wasmer-jni/wasmer-jni [java docs]: https://github.com/wasmerio/wasmer-java/#api-of-the-wasmer-library [elixir logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/elixir.svg [elixir integration]: https://github.com/tessi/wasmex [elixir docs]: https://hexdocs.pm/wasmex/api-reference.html [`wasmex` hex package]: https://hex.pm/packages/wasmex [r logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/r.svg [r integration]: https://github.com/dirkschumacher/wasmr [r docs]: https://github.com/dirkschumacher/wasmr#example [postgres logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/postgres.svg [postgres integration]: https://github.com/wasmerio/wasmer-postgres [postgres docs]: https://github.com/wasmerio/wasmer-postgres#usage--documentation [swift logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/swift.svg [swift integration]: https://github.com/AlwaysRightInstitute/SwiftyWasmer [zig logo]: https://raw.githubusercontent.com/ziglang/logo/master/zig-favicon.png [zig integration]: https://github.com/zigwasm/wasmer-zig [dart logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/dart.svg [dart integration]: https://github.com/dart-lang/wasm [`wasm` pub package]: https://pub.dev/packages/wasm [lisp logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/lisp.svg [lisp integration]: https://github.com/helmutkian/cl-wasm-runtime [crystal logo]: https://raw.githubusercontent.com/wasmerio/wasmer/master/assets/languages/crystal.svg [crystal integration]: https://github.com/naqvis/wasmer-crystal [crystal docs]: https://naqvis.github.io/wasmer-crystal/ ## Contribute We appreciate your help! 💜 Check our docs on how to [build Wasmer from source](https://docs.wasmer.io/ecosystem/wasmer/building-from-source) or [test your changes](https://docs.wasmer.io/ecosystem/wasmer/building-from-source/testing). ## Community Wasmer has an amazing community of developers and contributors. Welcome, please join us! 👋 - [Wasmer Community Slack](https://slack.wasmer.io/) - [Wasmer on Twitter](https://twitter.com/wasmerio) - [Wasmer on Facebook](https://www.facebook.com/wasmerio) - [Email](mailto:hello@wasmer.io) The spec and proposal repositories will be cloned in this directory by the `update-testsuite.sh` script. Don't apply local changes to these repositories, as the script may destroy them. This is the `wasmer-wast` crate, which contains an implementation of WebAssembly's "wast" test scripting language, which is used in the [WebAssembly spec testsuite], using wasmer for execution. [WebAssembly spec testsuite]: https://github.com/WebAssembly/testsuite > Note: this project started as a fork of [this crate](https://crates.io/crates/wasmtime-wast). # Wasmer Examples This directory contains a collection of examples. This isn't an exhaustive collection though, if one example is missing, please ask, we will be happy to fulfill your needs! ## Handy Diagrams As a quick introduction to Wasmer's main workflows, here are three diagrams. We hope it provides an overview of how the crates assemble together. 1. **Module compilation**, illustrates how WebAssembly bytes are validated, parsed, and compiled, with the help of the `wasmer::Module`, `wasmer_engine::Engine`, and `wasmer_compiler::Compiler` API. ![Module compilation](../assets/diagrams/Diagram_module_compilation.png) 2. **Module serialization**, illustrates how a module can be serialized and deserialized, with the help of `wasmer::Module::serialize` and `wasmer::Module::deserialize`. The important part is that the engine can changed between those two steps, and thus how a headless engine can be used for the deserialization. ![Module serialization](../assets/diagrams/Diagram_module_serialization.png) 3. **Module instantiation**, illustrates what happens when `wasmer::Instance::new` is called. ![Module instantiation](../assets/diagrams/Diagram_module_instantiation.png) ## Examples The examples are written in a difficulty/discovery order. Concepts that are explained in an example is not necessarily re-explained in a next example. ### Basics 1. [**Hello World**][hello-world], explains the core concepts of the Wasmer API for compiling and executing WebAssembly. _Keywords_: introduction, instance, module. <details> <summary><em>Execute the example</em></summary> ```shell $ cargo run --example hello-world --release --features "cranelift" ``` </details> 2. [**Instantiating a module**][instance], explains the basics of using Wasmer and how to create an instance out of a Wasm module. _Keywords_: instance, module. <details> <summary><em>Execute the example</em></summary> ```shell $ cargo run --example instance --release --features "cranelift" ``` </details> 3. [**Handling errors**][errors], explains the basics of interacting with Wasm module memory. _Keywords_: instance, error. <details> <summary><em>Execute the example</em></summary> ```shell $ cargo run --example errors --release --features "cranelift" ``` </details> 4. [**Interacting with memory**][memory], explains the basics of interacting with Wasm module memory. _Keywords_: memory, module. <details> <summary><em>Execute the example</em></summary> ```shell $ cargo run --example memory --release --features "cranelift" ``` </details> ### Exports 1. [**Exported global**][exported-global], explains how to work with exported globals: get/set their value, have information about their type. _Keywords_: export, global. <details> <summary><em>Execute the example</em></summary> ```shell $ cargo run --example exported-global --release --features "cranelift" ``` </details> 2. [**Exported function**][exported-function], explains how to get and how to call an exported function. They come in 2 flavors: dynamic, and “static”/native. The pros and cons are discussed briefly. _Keywords_: export, function, dynamic, static, native. <details> <summary><em>Execute the example</em></summary> ```shell $ cargo run --example exported-function --release --features "cranelift" ``` </details> 3. [**Exported memory**][exported-memory], explains how to read from and write to exported memory. _Keywords_: export, memory. <details> <summary><em>Execute the example</em></summary> ```shell $ cargo run --example exported-memory --release --features "cranelift" ``` </details> ### Imports 1. [**Imported global**][imported-global], explains how to work with imported globals: create globals, import them, get/set their value. _Keywords_: import, global. <details> <summary><em>Execute the example</em></summary> ```shell $ cargo run --example imported-global --release --features "cranelift" ``` </details> 2. [**Imported function**][imported-function], explains how to define an imported function. They come in 2 flavors: dynamic, and “static”/native. _Keywords_: import, function, dynamic, static, native. <details> <summary><em>Execute the example</em></summary> ```shell $ cargo run --example imported-function --release --features "cranelift" ``` </details> ### Externs 1. [**Table**][table], explains how to use Wasm Tables from the Wasmer API. _Keywords_: basic, table, call_indirect <details> <summary><em>Execute the example</em></summary> ```shell $ cargo run --example table --release --features "cranelift" ``` </details> 2. [**Memory**][memory], explains how to use Wasm Memories from the Wasmer API. Memory example is a work in progress. _Keywords_: basic, memory <details> <summary><em>Execute the example</em></summary> ```shell $ cargo run --example memory --release --features "cranelift" ``` </details> ### Tunables 1. [**Limit memory**][tunables-limit-memory], explains how to use Tunables to limit the size of an exported Wasm memory _Keywords_: basic, tunables, memory <details> <summary><em>Execute the example</em></summary> ```shell $ cargo run --example tunables-limit-memory --release --features "cranelift" ``` </details> ### Engines 1. [**Universal engine**][engine-universal], explains what an engine is, what the Universal engine is, and how to set it up. The example completes itself with the compilation of the Wasm module, its instantiation, and finally, by calling an exported function. _Keywords_: Universal, engine, in-memory, executable code. <details> <summary><em>Execute the example</em></summary> ```shell $ cargo run --example engine-universal --release --features "cranelift" ``` </details> 2. [**Dylib engine**][engine-dylib], explains what a Dylib engine is, and how to set it up. The example completes itself with the compilation of the Wasm module, its instantiation, and finally, by calling an exported function. _Keywords_: native, engine, shared library, dynamic library, executable code. <details> <summary><em>Execute the example</em></summary> ```shell $ cargo run --example engine-dylib --release --features "cranelift" ``` </details> 3. [**Headless engines**][engine-headless], explains what a headless engine is, what problem it does solve, and what are the benefits of it. The example completes itself with the instantiation of a pre-compiled Wasm module, and finally, by calling an exported function. _Keywords_: native, engine, constrained environment, ahead-of-time compilation, cross-compilation, executable code, serialization. <details> <summary><em>Execute the example</em></summary> ```shell $ cargo run --example engine-headless --release --features "cranelift" ``` </details> 4. [**Cross-compilation**][cross-compilation], illustrates the power of the abstraction over the engines and the compilers, such as it is possible to cross-compile a Wasm module for a custom target. _Keywords_: engine, compiler, cross-compilation. <details> <summary><em>Execute the example</em></summary> ```shell $ cargo run --example cross-compilation --release --features "cranelift" ``` </details> 5. [**Features**][features], illustrates how to enable WebAssembly features that aren't yet stable. _Keywords_: engine, features. <details> <summary><em>Execute the example</em></summary> ```shell $ cargo run --example features --release --features "cranelift" ``` </details> ### Compilers 1. [**Singlepass compiler**][compiler-singlepass], explains how to use the [`wasmer-compiler-singlepass`] compiler. _Keywords_: compiler, singlepass. <details> <summary><em>Execute the example</em></summary> ```shell $ cargo run --example compiler-singlepass --release --features "singlepass" ``` </details> 2. [**Cranelift compiler**][compiler-cranelift], explains how to use the [`wasmer-compiler-cranelift`] compiler. _Keywords_: compiler, cranelift. <details> <summary><em>Execute the example</em></summary> ```shell $ cargo run --example compiler-cranelift --release --features "cranelift" ``` </details> 3. [**LLVM compiler**][compiler-llvm], explains how to use the [`wasmer-compiler-llvm`] compiler. _Keywords_: compiler, llvm. <details> <summary><em>Execute the example</em></summary> ```shell $ cargo run --example compiler-llvm --release --features "llvm" ``` </details> ### Integrations 1. [**WASI**][wasi], explains how to use the [WebAssembly System Interface][WASI] (WASI), i.e. the [`wasmer-wasi`] crate. _Keywords_: wasi, system, interface <details> <summary><em>Execute the example</em></summary> ```shell $ cargo run --example wasi --release --features "cranelift,wasi" ``` </details> 2. [**WASI Pipes**][wasi-pipes], builds on the WASI example to show off stdio piping in Wasmer. _Keywords_: wasi, system, interface <details> <summary><em>Execute the example</em></summary> ```shell $ cargo run --example wasi-pipes --release --features "cranelift,wasi" ``` </details> [hello-world]: ./hello_world.rs [engine-universal]: ./engine_universal.rs [engine-dylib]: ./engine_dylib.rs [engine-headless]: ./engine_headless.rs [compiler-singlepass]: ./compiler_singlepass.rs [compiler-cranelift]: ./compiler_cranelift.rs [compiler-llvm]: ./compiler_llvm.rs [cross-compilation]: ./engine_cross_compilation.rs [exported-global]: ./exports_global.rs [exported-function]: ./exports_function.rs [exported-memory]: ./exports_memory.rs [imported-global]: ./imports_global.rs [imported-function]: ./imports_function.rs [instance]: ./instance.rs [wasi]: ./wasi.rs [wasi-pipes]: ./wasi_pipes.rs [table]: ./table.rs [memory]: ./memory.rs [errors]: ./errors.rs [tunables-limit-memory]: ./tunables_limit_memory.rs [features]: ./features.rs [`wasmer-compiler-singlepass`]: https://github.com/wasmerio/wasmer/tree/master/lib/compiler-singlepass [`wasmer-compiler-cranelift`]: https://github.com/wasmerio/wasmer/tree/master/lib/compiler-cranelift [`wasmer-compiler-llvm`]: https://github.com/wasmerio/wasmer/tree/master/lib/compiler-llvm [`wasmer-wasi`]: https://github.com/wasmerio/wasmer/tree/master/lib/wasi [WASI]: https://github.com/WebAssembly/WASI # `wasmer-types` [![Build Status](https://github.com/wasmerio/wasmer/workflows/build/badge.svg?style=flat-square)](https://github.com/wasmerio/wasmer/actions?query=workflow%3Abuild) [![Join Wasmer Slack](https://img.shields.io/static/v1?label=Slack&message=join%20chat&color=brighgreen&style=flat-square)](https://slack.wasmer.io) [![MIT License](https://img.shields.io/github/license/wasmerio/wasmer.svg?style=flat-square)](https://github.com/wasmerio/wasmer/blob/master/LICENSE) This library provides all the types and traits necessary to use WebAssembly easily anywhere. Among other things, it defines the following _types_: * `units` like `Pages` or `Bytes` * `types` and `values` like `I32`, `I64`, `F32`, `F64`, `ExternRef`, `FuncRef`, `V128`, value conversions, `ExternType`, `FunctionType` etc. * `native` contains a set of trait and implementations to deal with WebAssembly types that have a direct representation on the host, * `memory_view`, an API to read/write memories when bytes are interpreted as particular types (`i8`, `i16`, `i32` etc.) * `indexes` contains all the possible WebAssembly module indexes for various types * `initializers` for tables, data etc. * `features` to enable or disable some WebAssembly features inside the Wasmer runtime ### Acknowledgments This project borrowed some of the code for the entity structure from [cranelift-entity](https://crates.io/crates/cranelift-entity). We decided to move it here to help on serialization/deserialization and also to ease the integration with other tools like `loupe`. Please check [Wasmer ATTRIBUTIONS](https://github.com/wasmerio/wasmer/blob/master/ATTRIBUTIONS.md) to further see licenses and other attributions of the project. # `wasmer-compiler-singlepass` [![Build Status](https://github.com/wasmerio/wasmer/workflows/build/badge.svg?style=flat-square)](https://github.com/wasmerio/wasmer/actions?query=workflow%3Abuild) [![Join Wasmer Slack](https://img.shields.io/static/v1?label=Slack&message=join%20chat&color=brighgreen&style=flat-square)](https://slack.wasmer.io) [![MIT License](https://img.shields.io/github/license/wasmerio/wasmer.svg?style=flat-square)](https://github.com/wasmerio/wasmer/blob/master/LICENSE) [![crates.io](https://img.shields.io/crates/v/wasmer-compiler-singlepass.svg)](https://crates.io/crates/wasmer-compiler-singlepass) This crate contains a compiler implementation based on the Singlepass linear compiler. ## Usage ```rust use wasmer::{Store, Universal}; use wasmer_compiler_singlepass::Singlepass; let compiler = Singlepass::new(); // Put it into an engine and add it to the store let store = Store::new(&Universal::new(compiler).engine()); ``` *Note: you can find a [full working example using Singlepass compiler here][example].* ## When to use Singlepass Singlepass is designed to emit compiled code at linear time, as such is not prone to JIT bombs and also offers great compilation performance orders of magnitude faster than [`wasmer-compiler-cranelift`] and [`wasmer-compiler-llvm`], however with a bit slower runtime speed. The fact that singlepass is not prone to JIT bombs and offers a very predictable compilation speed makes it ideal for **blockchains** and other systems where fast and consistent compilation times are very critical. [example]: https://github.com/wasmerio/wasmer/blob/master/examples/compiler_singlepass.rs [`wasmer-compiler-cranelift`]: https://github.com/wasmerio/wasmer/tree/master/lib/compiler-cranelift [`wasmer-compiler-llvm`]: https://github.com/wasmerio/wasmer/tree/master/lib/compiler-llvm # Wasmer Test libraries Here is the place where the test libraries will live. # `wasmer-engine-universal` [![Build Status](https://github.com/wasmerio/wasmer/workflows/build/badge.svg?style=flat-square)](https://github.com/wasmerio/wasmer/actions?query=workflow%3Abuild) [![Join Wasmer Slack](https://img.shields.io/static/v1?label=Slack&message=join%20chat&color=brighgreen&style=flat-square)](https://slack.wasmer.io) [![MIT License](https://img.shields.io/github/license/wasmerio/wasmer.svg?style=flat-square)](https://github.com/wasmerio/wasmer/blob/master/LICENSE) The Wasmer Universal engine is usable with any compiler implementation based on [`wasmer-compiler`]. After the compiler process the result, the Universal pushes it into memory and links its contents so it can be usable by the [`wasmer`] API. *Note: you can find a [full working example using the Universal engine here][example].* ### Acknowledgments This project borrowed some of the code of the code memory and unwind tables from the [`wasmtime-jit`], the code since then has evolved significantly. Please check [Wasmer `ATTRIBUTIONS`] to further see licenses and other attributions of the project. [`wasmer-compiler`]: https://github.com/wasmerio/wasmer/tree/master/lib/compiler [`wasmer`]: https://github.com/wasmerio/wasmer/tree/master/lib/api [example]: https://github.com/wasmerio/wasmer/blob/master/examples/engine_universal.rs [`wasmtime-jit`]: https://crates.io/crates/wasmtime-jit [Wasmer `ATTRIBUTIONS`]: https://github.com/wasmerio/wasmer/blob/master/ATTRIBUTIONS.md
frol_block-and-wine-web4-demo
Cargo.toml README.md src index.html lib.rs
Web4 Demo on NEAR protocol for Block & Wine Community ===================================================== [Web4](https://web4.near.page) is a gateway to the smart contracts deployed to NEAR protocol. This demo just shows [blockandwine.com](https://blockandwine.com) landing page that lives on NEAR chain, and thus anyone hosting Web4 gateway can serve it! Be it `block-and-wine.near.page` or `block-and-wine.web4` or `block-and-wine.at-frol.page` or even `block-and-wine.near.google.com`. See it live on testnet: https://block-and-wine.testnet.page When you deploy on mainnet, you should be able to use https://ACCOUNT_ID.near.page as your gateway. ## Build See [near-sdk docs](https://near-sdk.io) for the prerequisites, and then build the contract: ``` $ cargo build --target wasm32-unknown-unknown --release ``` ## Deploy Using [near-cli-rs](https://near.cli.rs) you can deploy the contract to your account: ``` $ near-cli add contract-code network testnet account ACCOUNT_ID.testnet contract-file ./target/wasm32-unknown-unknown/release/block_and_wine_web4_demo.wasm no-initialize sign-with-keychain ```
gpteth_-
ArtifyNet NodeJsServer src controllers ArtworkController.js AuctionController.js UserController.js routes artworkRoutes.js auctionRoutes.js userRoutes.js server.js ReactWebApp src App.js components ArtworkList.js Auction.js MintArtworkForm.js artifyNetSolana.rs AutoChain bootstrap_app index.html scripts.js python_server app.py solana AutoChain.rs CryptoKingdom README.md gamedesign main.js logic JWT.js auth.js config.js database.js landOwnership.js server_config.js on-chain lib.rs CryptoZooAdventures backend controllers authController.js nftController.js userController.js main.js middleware authMiddleware.js models NFT.js User.js routes authRoutes.js frontend-beta src App.js CreateNFT.js NFTList.js login.js smart-contracts Cargo.toml nftycoon.rs DAOAudit fastAPI app.py frontend src app app.component.html app.component.ts app.module.ts audit-create.component.html audit-create.component.ts audit-list.component.html audit-list.component.ts audit.serve.ts lib.rs DAOrganizer app serverside app.py contracts lib.rs DecentraJobs backend app.js controllers authController.js userController.js models JobApplication.js User.js UserJobPosting.js contracts decentralJobsSolana.rs frontend src App.js components CreateJob.js JobDetail.js JobList.js EduChain cargo.toml lib.rs tests.rs web index.html main.js styles.css EduFinHub backend app.py authentication.py enrollment.py models.py requirements.txt users.py edufinhub-solana src edufinhub.rs EventDApp flask auth.py events.py tickets.py smartContracts lib.rs FanFiesta Solana cargo.toml src FanFiesta.rs lib.rs react-app src Header.js app.js index.js membership.js membershipPage.js server App.js controllers UserController.js middleware authentication.js models User.js routes authRoutes.js FarmChain README.md app script.js blockchain lib.rs server app.py FitChain backend src app.js controllers ChallengeController.js UserController.js authenticationMiddleware.js database.js frontend src App.js components Challenge.js Dashboard.js Profile.js solana_smart_contracts fitchain.rs GreenToken README.md src lib.rs marketplace.rs HealthLink HealthLink.rs frontend src App.js components Home.js Portfolio.js StrategyCard.js StrategyList.js server server.js solana.js solanaController.js userController.js InfluencerFi 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 LegalLink appcode index.html main.js styles.css servercode app.py templates contract_details.html create_contract.html index.html solanacode lib.rs NFTycoon README.md gameapp Header.js MArketplace.js NFTdetail.js Profile.js app.js nodejscode app.js solana lib.rs PirateChain javascript_game dashboard.html dashboard.js login.html login.js python_logic app.py login.py pirates.py rust_smart_contract lib.rs README.md RaceToMars backend authController.js database.js index.js spaceCraftController.js frontend app.js onchain racetoMars.rs RentPeer README.md src disputes.rs lib.rs main.rs models.rs p2p_rentals.rs payments.rs reviews.rs SkillDAO flaskcode app.py solana_rustcode lib.rs SolCharityChain app app.js communityprojects.js donate.html donate.js footer.js home.js index.html navbar.js trackdonations.js server routes accounts.js donation-impacts.js donations.js projects.js server.js smartcontract.rs WealthWave portfolio.rs reactApp App.js components Header.js portfolio.js trading.js index.js pages home.js portfolioPage.js tradingPage.js services ai.js blockchain.js
# CryptoKingdom MMORPG CryptoKingdom is a blockchain-based Massively Multiplayer Online Role-Playing Game (MMORPG) where players can explore virtual worlds, own land, build kingdoms, engage in battles, and trade while earning cryptocurrency. ## Project Structure The project consists of three main components: 1. **Ethereum Smart Contracts (Rust)** - `crypto_kingdom.sol`: Solidity contract for land ownership and currency management. 2. **Node.js Back-end** - `server.js`: Main server file to handle HTTP requests and interact with the Ethereum blockchain. - `routes.js`: Define routes for handling game actions (e.g., buying land, trading). - `ethereum.js`: A module to interact with the Ethereum blockchain using web3.js or ethers.js. - `game_logic.js`: Implement game logic, such as battles, exploration, and in-game events. 3. **Front-end (Three.js)** - `index.html`: HTML file for the game's interface. - `main.js`: JavaScript file to initialize the Three.js scene and handle user interactions. - `player.js`: Define player character and controls. - `world.js`: Create and manage the virtual game world. - `networking.js`: Handle communication with the server for real-time updates. ## Setup 1. **Ethereum Smart Contracts (Rust)** - Deploy the `crypto_kingdom.sol` contract on the Ethereum blockchain. - Configure your server to interact with the deployed contract. 2. **Node.js Back-end** - Install Node.js if not already installed. - Run `npm install` to install dependencies. - Set up your Ethereum node connection in `ethereum.js`. - Start the server with `node server.js`. 3. **Front-end (Three.js)** - Host the front-end files on a web server. - Configure the server endpoint in `networking.js` to match your back-end server. ## Usage - Visit the front-end website to play CryptoKingdom. - Explore virtual worlds, buy land, build kingdoms, trade with other players, and engage in battles. - Your in-game actions are recorded on the Ethereum blockchain. ## Contributing Feel free to contribute to this project by creating issues, suggesting improvements, or submitting pull requests. ## License This project is licensed under the [MIT License](LICENSE). ## Acknowledgments Thanks to the open-source community for providing tools and libraries used in this project. # SolCharityChain # NFTycoon 项目说明 NFTycoon 是一款基于区块链的模拟游戏,玩家可以创建、管理和发展他们的虚拟业务,将其产品铸造成 NFT,并在去中心化市场中进行交易。 ## 项目结构 该项目包括前端、后端和智能合约的代码。 ### 前端(React) 前端使用 React 开发,包含游戏界面、用户仪表板和市场交易界面。 # GreenToken (In Development) **GreenToken** is a blockchain-based project aimed at revolutionizing the way we track and incentivize eco-friendly behaviors. This README provides an overview of the project, its goals, and its current development status. ## Table of Contents - [Introduction](#introduction) - [Features](#features) - [Getting Started](#getting-started) - [Contributing](#contributing) - [Development Status](#development-status) - [License](#license) ## Introduction GreenToken is a fully onchain platform that leverages blockchain technology to create a transparent and decentralized ecosystem for rewarding and promoting environmentally friendly actions and practices. The project's main objectives include: - Encouraging sustainable practices, such as recycling, reducing energy consumption, and supporting clean energy initiatives. - Providing an immutable ledger to track and verify eco-friendly activities. - Issuing GreenTokens as rewards for individuals, organizations, and communities that actively contribute to environmental conservation. - Fostering a global community dedicated to environmental sustainability. ## Features GreenToken is designed to offer a wide range of features to its users, including: - **Token Minting:** Create GreenTokens as unique digital assets representing eco-friendly actions and achievements. - **Token Transfer:** Send and receive GreenTokens as rewards for participating in green initiatives. - **Verification:** Utilize smart contracts and blockchain technology to verify and authenticate eco-friendly activities and claims. - **Community Engagement:** Connect with like-minded individuals, organizations, and communities committed to environmental conservation. - **Marketplace:** Trade and exchange GreenTokens for goods, services, or even support environmental causes. - **Governance:** Participate in the project's decision-making process through decentralized governance mechanisms. - **Transparency:** Access a public ledger of all eco-friendly actions recorded on the GreenToken blockchain. ## Getting Started GreenToken is currently under active development. To contribute or explore the project further, follow these steps: 1. Clone this repository to your local machine: 2. Install the necessary dependencies. 3. Run the development environment and explore the codebase. 4. Join the GreenToken community on our [official website](https://www.greentoken.io) and [GitHub repository](https://github.com/YourUsername/GreenToken). ## Contributing We welcome contributions from developers, designers, and anyone passionate about environmental conservation and blockchain technology. If you'd like to contribute to GreenToken, please check out our [Contribution Guidelines](CONTRIBUTING.md) for details on how to get started. ## Development Status GreenToken is currently in the development phase, and many exciting features are yet to be implemented. Our development roadmap includes: - Smart contract development for GreenToken creation and management. - Integration with a public blockchain network (e.g., Ethereum, Binance Smart Chain). - Development of a user-friendly web application. - Community engagement and partnerships to expand our eco-friendly ecosystem. Please note that this project is still evolving, and we encourage you to keep an eye on our [GitHub repository](https://github.com/YourUsername/GreenToken) for updates and contributions. ## License GreenToken is open-source software licensed under the [MIT License](LICENSE.md). Feel free to use, modify, and distribute this software in accordance with the terms of the license. --- **Disclaimer:** GreenToken is a work in progress, and this README serves as an overview of its objectives and features. The actual implementation and functionality may change as development progresses. Thank you for your interest in GreenToken, and we look forward to building a greener future together! # FarmChain - Connecting Farmers and Consumers FarmChain is a platform that aims to connect farmers directly with consumers, enabling the sale and purchase of agricultural products without intermediaries. It ensures transparency in pricing, product origin, and quality, fostering a fair and sustainable agricultural marketplace. ## Table of Contents - [Project Structure](#project-structure) - [Getting Started](#getting-started) - [Frontend](#frontend) - [Backend](#backend) - [Smart Contracts](#smart-contracts) - [Usage](#usage) - [Contributing](#contributing) - [License](#license) ## Project Structure FarmChain project is organized into three main components: 1. **Frontend (Vue.js):** - The `frontend` folder contains the Vue.js application responsible for the user interface. 2. **Backend (Python - Flask):** - The `backend` folder contains the Flask-based backend API that serves as the intermediary between the front end and the smart contracts. 3. **Smart Contracts (Rust):** - The `smart_contracts` folder contains the Rust smart contracts used to manage product data on the blockchain. ## Getting Started Before running the application, you need to set up each component. ### Frontend 1. Navigate to the `frontend` directory: ```bash cd frontend rent-peer/ |-- src/ | |-- main.rs # Main entry point | |-- lib.rs # Library code for the smart contract | |-- models.rs # Data models | |-- reviews.rs # Review system logic | |-- payments.rs # Tokenized payments logic | |-- dispute.rs # Dispute resolution logic | |-- p2p_rentals.rs # P2P rental logic |-- Cargo.toml # Rust project dependencies
near-ndc_wasm-arithmetic-exception
Cargo.toml README.md src lib.rs
# wasm-arithmetic-exception Minimum code to exploit wasm arithmetic exception in the NEAR Core Runtime. Issue: https://github.com/near/nearcore/issues/9393
jayden-dang_smart-contract-vugomars-near
Cargo.toml build.sh deploy.sh src lib.rs
itissandeep98_mazout
.eslintrc.json .github workflows main.yml README.md config constants.js supabase.js layer0.config.js layout LayoutWrapper.js Meta.js next.config.js package.json pages _app.js api hello.js home.js index.js sitemap.xml.js postcss.config.js public Plug.svg capacity.svg charge.svg cycles.svg logo1.svg near.svg range.svg robots.txt voltage.svg routes.js styles globals.css sw service-worker.js tailwind.config.js
# POC for Electric Vehicle Charging station ## Tablet Views ![image](https://user-images.githubusercontent.com/44255731/182032369-8a381458-ffdd-40da-984a-8214f13ddb7e.png) ![image](https://user-images.githubusercontent.com/44255731/182032383-09fe782e-ea86-4e85-beb9-96e8c9950b13.png) ![image](https://user-images.githubusercontent.com/44255731/182032426-db828f99-cae9-41b9-9911-08fbe0ae77ff.png) ![image](https://user-images.githubusercontent.com/44255731/182032455-35d64fc0-8ca7-4f0c-961b-88310cb49bf5.png) ![image](https://user-images.githubusercontent.com/44255731/182032473-c2b962fe-13bf-42e3-a230-602176b07788.png) ## Phone/User Views ![image](https://user-images.githubusercontent.com/44255731/182032574-ceda861a-f71b-4929-b511-73a5b7a18db7.png) ![image](https://user-images.githubusercontent.com/44255731/182032605-34a8cdf4-031b-4858-b3de-f2eb58f2542f.png) ## Development ### Requirements - Node.js >= 16.15.0 - yarn >= 1.22.18 ### Environment variables - NEXT_PUBLIC_SUPABASE_ANON_KEY - NEXT_PUBLIC_SUPABASE_URL Both Needs to be set in .env file or the development environment and can be found after creating a database using [Supabase](https://supabase.com/) ### Local Development - Install Node Modules ``` yarn ``` - Run dev Server ``` yarn dev ``` ## Deployment - Currently it is deployed using [Layer0/Edgio](https://www.layer0.co/) - Use `yarn layer0:deploy` to deploy to Layer0 - Since its a Next.js app you can use your own deployemnt accordingly
esaminu_console-donation-template-3245sdvc
.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).
NEARBuilders_CommunityGroups
README.md | SUMMARY.md about DAO.md NFT.md Wallet.md
# Community Groups ## Quickstart {% content-ref url="https://app.gitbook.com/o/wxNIOkA8NaT6omjLbqYh/s/eYMvXqEeHTuMsh7JRboR/" %} [Start Here](https://app.gitbook.com/o/wxNIOkA8NaT6omjLbqYh/s/eYMvXqEeHTuMsh7JRboR/) {% endcontent-ref %} {% content-ref url="https://app.gitbook.com/o/wxNIOkA8NaT6omjLbqYh/s/paqK4UTfbHO8TsgdzQ0A/" %} [NEARSletter](https://app.gitbook.com/o/wxNIOkA8NaT6omjLbqYh/s/paqK4UTfbHO8TsgdzQ0A/) {% endcontent-ref %} {% content-ref url="https://app.gitbook.com/o/wxNIOkA8NaT6omjLbqYh/s/TMh3Z7C4QzYo9Q8Oa3cq/" %} [NEP Ideation](https://app.gitbook.com/o/wxNIOkA8NaT6omjLbqYh/s/TMh3Z7C4QzYo9Q8Oa3cq/) {% endcontent-ref %} {% content-ref url="https://app.gitbook.com/o/wxNIOkA8NaT6omjLbqYh/s/thv9RgvV6S5LYy0BQz01/" %} [Resources](https://app.gitbook.com/o/wxNIOkA8NaT6omjLbqYh/s/thv9RgvV6S5LYy0BQz01/) {% endcontent-ref %} Community Groups or Builder Groups are developer centric interest groups on specific NEAR ecosystem verticals dedicated to support projects & developer governance from the ground up, and push protocol standards as [NEPs](https://github.com/near/NEPs), and build open source tooling. ## 📚 LEARN ABOUT DEVELOPER GOVERNANCE [neardevgov.org](https://neardevgov.org/) ## 🗳️ submit an idea in the Developer Governance gigs board a [devgovgigs.near.social](https://devgovgigs.near.social/) It also gives an opportunity for **developers, technical PMs, and founders** to learn from each other, connect + collaborate, and implement the latest technologies, serving as NEAR developer incubators amongst the respective verticals.&#x20; | **Builder Group** | **Meeting Dates** | **Telegram** | **Registration Link** | **Governance Post** | **Notes** | **Primary Organizers** | | ------------------------- | -------------------------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | | Protocol Community Group | TBA | [nearbuilders.com/tg-protocol](http://nearbuilders.com/tg-protocol) | TBA | [nearbuilders.com/protocol-post](http://nearbuilders.com/protocol-post) | [nearbuilders.com/protocol-notes](http://nearbuilders.com/protocol-notes) | [Pagoda](https://www.pagoda.co/) | | Wallet | Weekly on Tuesdays at 12PM EST | [nearbuilders.com/tg-wallet](http://nearbuilders.com/tg-wallet) | [nearbuilders.com/wallet-calendar](http://nearbuilders.com/wallet-calendar) | [nearbuilders.com/wallet-post](http://nearbuilders.com/wallet-post) | [nearbuilders.com/wallet-notes](http://nearbuilders.com/wallet-notes) | [Banyan Collective](https://www.banyan.gg/) | | NFT | Weekly on Wednesdays at 12pm EST | [nearbuilders.com/tg-nft](http://nearbuilders.com/tg-nft) | [nearbuilders.com/nft-calendar](http://nearbuilders.com/nft-calendar) | [nearbuilders.com/nft-post](http://nearbuilders.com/nft-post) | [nearbuilders.com/nft-notes](http://nearbuilders.com/nft-notes) | [Banyan Collective](https://www.banyan.gg/) | | DAO | Weekly Tuesday, | [nearbuilders.com/tg-dao](http://nearbuilders.com/tg-dao) | [nearbuilders.com/dao-calendar](http://nearbuilders.com/dao-calendar) | [nearbuilders.com/dao-post](http://nearbuilders.com/dao-post) | [nearbuilders.com/dao-notes](http://nearbuilders.com/dao-notes) | [AstroDAO](https://astrodao.com/), [Banyan Collective](https://www.banyan.gg/) | | DeFi | TBA (Monthly Call) | [nearbuilders.com/tg-defi](http://nearbuilders.com/tg-defi) | TBA (Monthly Call) | [nearbuilders.com/defi-post](http://nearbuilders.com/defi-post) | [nearbuilders.com/defi-notes](http://nearbuilders.com/defi-notes) | [Banyan Collective](https://www.banyan.gg/), [Proximity Labs](https://www.proximity.dev/) | | Data Infrastructure | TBA (Monthly Call) | [nearbuilders.com/tg-data](http://nearbuilders.com/tg-data) | TBA - Monthly Call | [nearbuilders.com/data-post](http://nearbuilders.com/data-post) | [nearbuilders.com/data-notes](http://nearbuilders.com/data-notes) | [Banyan Collective](https://www.banyan.gg/), [Pagoda](https://www.pagoda.co/) | | ZK | TBA | [nearbuilders.com/tg-zk](http://nearbuilders.com/tg-zk) | [nearbuilders.com/zk-calendar](http://nearbuilders.com/zk-calendar) | [nearbuilders.com/zk-post](http://nearbuilders.com/zk-post) | TBA | [Pagoda](https://www.pagoda.co/) | | NEAR SOCIAL | TBA | [nearbuilders.com/tg-social](http://nearbuilders.com/tg-social) | TBA | [nearbuilders.com/social-post](http://nearbuilders.com/social-post) | TBA | James Waugh, NDC (NEAR Digital Collective) | | Python Tooling | TBA | [nearbuilders.com/tg-python](http://nearbuilders.com/tg-python) | TBA | [nearbuilders.com/python-post](http://nearbuilders.com/python-post) | TBA | [NEAR Foundation](http://near.foundation) | | Tooling Community Group | TBA | [nearbuilders.com/tg-tools](http://nearbuilders.com/tg-tools) | TBA | [nearbuilders.com/tools-post](http://nearbuilders.com/tools-post) | TBA | [Pagoda](https://www.pagoda.co/) | | Validator Community Group | TBA | [nearbuilders.com/tg-validator](http://nearbuilders.com/tg-validator) | | [nearbuilders.com/validator-post](http://nearbuilders.com/validator-post) | | Open Shards Alliance | Videos for Banyan Led Builder Calls can be found at [nearbuilders.com/builder-videos](http://nearbuilders.com/builder-videos) ## **🧠 Other Interest Groups** _These groups are for people with common interests not yet established. Reach out if you would like to be part of this._ * 🔐 [Privacy on NEAR](http://nearbuilders.com/tg-privacy): emphasize privacy tools and privacy as the default on NEAR. * 📹 [NEAR Content Creators Working Group](http://nearbuilders.com/tg-content) Goal is to bring all content creators together, support each other, and ultimately increase the quality and quantity of material produced that promotes the NEAR Protocol. [Learn more at the governance post](http://nearbuilders.com/content-post) * 🌉 [NFT Bridging](http://nearbuilders.com/tg-bridge): developing standards and tools to bridge NFTs across different blockchains (chain agnostic) * 🌐 [IBC x NEAR](http://nearbuilders.com/tg-ibc): to increase collaboration between the NEAR and Cosmos ecosystem * 🏗️ [NEAR JS SDK User Group](https://nearbuilders.com/tg-js) for developers using the [NEAR Javascript SDK](https://docs.near.org/tools/near-sdk-js) * 🌻 [NEAR Refi Grower Group](https://nearbuilders.com/tg-refi) build ReFI public goods and bolster NEAR as a ReFI chain
johnedvard_NCD-I
README.md as-pect.config.js asconfig.json package-lock.json package.json scripts 1.dev-deploy.sh 2.use-contract.sh 3.cleanup.sh README.md src as_types.d.ts singleton __tests__ as-pect.d.ts index.unit.spec.ts asconfig.json assembly game.ts index.ts tsconfig.json utils.ts test.js
## Summary This is a project for NEAR certified program level 1. This project was cloned from the starter template, [starter--near-sdk-as](https://github.com/Learn-NEAR/starter--near-sdk-as) This project is based on the Japanese game, [Shiritori Game](https://en.wikipedia.org/wiki/Shiritori), where you have to write a word that starts with the previous's words last character. It's intended to be played using Japanese characters, and only katakana (カタカナ). The rules I have implemtend are simple: 1. Add one word to a list 2. You cannot write the same word that has already been used 3. You cannot write more than one consecutive word (you need to wait for someone else to add a word first) 4. The next word need to start with last word's last character - ['カイ','イクラ'] OK - ['カイ','クライ'] Not OK, you loose the game. 5. The word cannot end with an illegal character (ン), then you loose the game 6. This is a bonus rule, but we are only allowed to have one, and only one game, that starts with the same word - game1: ['カイ', 'イクラ'] -> try to add 'イクラ' again, game resets. - game2: try to add 'カイ' as the first word. Not allowed because game1 uses that word as a key, and its final. When a player looses the game, the game restarts. ## How to run 1. `npm install` 2. deploy contract by running shell script `./scripts/1.dev-deploy.sh` 3. change CONTRACT (and ACCOUNT_ID) in "scripts/2.dev-deploy.sh" with the newly generated dev-account 4. run `./scripts/2.dev-deploy.sh` to see some example usage of the contract functions - Remember to change the ACCOUNT_ID each time you add a new word to the contract (because of the game's rules) ## How to test run `npm run test` to run the tests for the game found in "src/singleton/**tests**/index.unit.spec.ts" ## Additional comments There are a lot of experimental code in this project, but the contact for the submission is inside. - `src/singleton/assembly/index.ts` - `src/singleton/assembly/game.ts` - I have also created some tests in `src/singleton/__tests__/index.unit.spec.ts` Ignore the rest of the files, as they are only for experimenting. If you're not able to run the shell scripts inside ./scripts, check the README, `scripts/README.md` for some help. ## Demo Video on Loom https://www.loom.com/share/81a53b6abe7644f8b74e4d92a569ab63 ## OS Support I'm using Mac, and I have saved new lines in the scripts using `LF` instead of `CRLF`, othwerwise my bash command wouldn't run the scripts. Windows users may have to change all the `LF`s to `CRLF`s to make it work.
GigameshGarages_VajraNet
.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 web-app README.md gulpfile.js jsconfig.json package.json | |
# 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) # [Argon Dashboard React](https://demos.creative-tim.com/argon-dashboard-react?ref=adr-github-readme) [![Tweet](https://img.shields.io/twitter/url/http/shields.io.svg?style=social&logo=twitter)](https://twitter.com/home?status=Argon%20Dashboard%20is%20a%20Free%20Bootstrap%204,%20React%20and%20Reactstrap%20Dashboard%20made%20using%20create-react-app%20%E2%9D%A4%EF%B8%8F%0Ahttps%3A//demos.creative-tim.com/argon-dashboard-react%20%23react%20%23reactstrap%20%23createreactapp%20%23argon%20%23argondesign%20%23reactdashboard%20%23argonreact%20%23reactdesign%20%23bootstrap%20%23material%20%23design%20%23uikit%20%23freebie%20%20via%20%40CreativeTim) ![version](https://img.shields.io/badge/version-1.2.0-blue.svg) ![license](https://img.shields.io/badge/license-MIT-blue.svg) [![GitHub issues open](https://img.shields.io/github/issues/creativetimofficial/argon-dashboard-react.svg?maxAge=2592000)](https://github.com/creativetimofficial/argon-dashboard-react/issues?q=is%3Aopen+is%3Aissue) [![GitHub issues closed](https://img.shields.io/github/issues-closed-raw/creativetimofficial/argon-dashboard-react.svg?maxAge=2592000)](https://github.com/creativetimofficial/argon-dashboard-react/issues?q=is%3Aissue+is%3Aclosed) [![Join the chat at https://gitter.im/NIT-dgp/General](https://badges.gitter.im/NIT-dgp/General.svg)](https://gitter.im/creative-tim-general/Lobby) [![Chat](https://img.shields.io/badge/chat-on%20discord-7289da.svg)](https://discord.gg/E4aHAQy) ![Product Gif](https://raw.githubusercontent.com/creativetimofficial/public-assets/master/argon-dashboard-react/argon-dashboard-react.gif) Start your development with a Dashboard for [Bootstrap 4](https://getbootstrap.com/?ref=creativetim), [React](https://reactjs.org/?ref=creativetim) and [Reactstrap](https://reactstrap.github.io/?ref=creativetim), made with [create-react-app](https://facebook.github.io/create-react-app/?ref=creativetim). It is open source, free and it features many components that can help you create amazing websites. **Fully Coded Components** Argon Dashboard React is built with over 100 individual components, giving you the freedom of choosing and combining. All components can take variations in color, that you can easily modify using SASS files. You will save a lot of time going from prototyping to full-functional code, because all elements are implemented. This Dashboard is coming with pre-built examples, so the development process is seamless, switching from our pages to the real website is very easy to be done. Every element has multiple states for colors, styles, hover, focus, that you can easily access and use. **Complex Documentation** Each element is well presented in a very complex documentation. You can read more about the idea behind this [dashboard here](https://demos.creative-tim.com/argon-dashboard-react/#/documentation/overview?ref=creativetim). You can check the [components here](https://demos.creative-tim.com/argon-dashboard-react/#/documentation/alerts?ref=creativetim) and the [foundation here](https://demos.creative-tim.com/argon-dashboard/#/documentation/colors?ref=creativetim). **Example Pages** If you want to get inspiration or just show something directly to your clients, you can jump start your development with our pre-built example pages. You will be able to quickly set up the basic structure for your web project. ## Table of Contents * [Versions](#versions) * [Demo](#demo) * [Quick Start](#quick-start) * [Documentation](#documentation) * [File Structure](#file-structure) * [Browser Support](#browser-support) * [Resources](#resources) * [Reporting Issues](#reporting-issues) * [Licensing](#licensing) * [Useful Links](#useful-links) ## Versions [<img src="https://github.com/creativetimofficial/public-assets/blob/master/logos/html-logo.jpg?raw=true" width="60" height="60" />](https://www.creative-tim.com/product/argon-dashboard?ref=adr-github-readme)[<img src="https://github.com/creativetimofficial/public-assets/blob/master/logos/react-logo.jpg?raw=true" width="60" height="60" />](https://www.creative-tim.com/product/argon-dashboard-react?ref=adr-github-readme)[<img src="https://github.com/creativetimofficial/public-assets/blob/master/logos/angular-logo.jpg?raw=true" width="60" height="60" />](https://www.creative-tim.com/product/argon-dashboard-angular)[<img src="https://github.com/creativetimofficial/public-assets/blob/master/logos/nodejs-logo.jpg?raw=true" width="60" height="60" />](https://www.creative-tim.com/product/argon-dashboard-nodejs?ref=adr-github-readme)[<img src="https://raw.githubusercontent.com/creativetimofficial/public-assets/master/logos/laravel_logo.png" width="60" height="60" style="background:white"/>](https://www.creative-tim.com/product/argon-dashboard-laravel?ref=adr-github-readme)[<img src="https://raw.githubusercontent.com/creativetimofficial/public-assets/master/logos/sketch-logo.jpg" width="60" height="60" />](https://www.creative-tim.com/product/argon-dashboard-react?ref=adr-github-readme) | HTML | React | Angular | | --- | --- | --- | | [![Argon Dashboard HTML](https://github.com/creativetimofficial/public-assets/blob/master/argon-dashboard/argon-dashboard.jpg?raw=true)](https://www.creative-tim.com/product/argon-dashboard) | [![Argon Dashboard React](https://github.com/creativetimofficial/public-assets/blob/master/argon-dashboard-react/argon-dashboard-react.jpg?raw=true)](https://www.creative-tim.com/product/argon-dashboard-react) | [![Argon Dashboard Angular](https://github.com/creativetimofficial/public-assets/blob/master/argon-dashboard-angular/argon-dashboard-angular.jpg?raw=true)](https://www.creative-tim.com/product/argon-dashboard-angular) | NodeJS | Laravel | | --- | --- | | [![Argon Dashboard NodeJS](https://github.com/creativetimofficial/public-assets/blob/master/argon-dashboard-nodejs/argon-dashboard-nodejs.jpg?raw=true)](https://www.creative-tim.com/product/argon-dashboard-nodejs) | [![Argon Dashboard Laravel](https://github.com/creativetimofficial/public-assets/blob/master/argon-dashboard-laravel/argon-dashboard-laravel.jpg?raw=true)](https://www.creative-tim.com/product/argon-dashboard-laravel) | ## Demo | Dashboard Page | Icons Page | Tables Page | Maps Page | | --- | --- | --- | --- | | [![Dashboard Page](https://github.com/creativetimofficial/public-assets/blob/master/argon-dashboard-react/dashboard-page.png?raw=true)](https://demos.creative-tim.com/argon-dashboard-react/#/admin/index) | [![Icons Page](https://github.com/creativetimofficial/public-assets/blob/master/argon-dashboard-react/icons-page.png?raw=true)](https://demos.creative-tim.com/argon-dashboard-react/#/admin/icons) | [![Tables Page](https://github.com/creativetimofficial/public-assets/blob/master/argon-dashboard-react/tables-page.png?raw=true)](https://demos.creative-tim.com/argon-dashboard-react/#/admin/tables) | [![Maps Page](https://github.com/creativetimofficial/public-assets/blob/master/argon-dashboard-react/maps-page.png?raw=true)](https://demos.creative-tim.com/argon-dashboard-react/#/admin/maps) | Register Page | Login Page Page | Profile Page | | --- | --- | --- | | [![Login Page](https://raw.githubusercontent.com/creativetimofficial/public-assets/master/argon-dashboard-react/register-page.png)](https://demos.creative-tim.com/argon-dashboard-react/#/auth/register) | [![Login Page Page](https://github.com/creativetimofficial/public-assets/blob/master/argon-dashboard-react/login-page.png?raw=true)](https://demos.creative-tim.com/argon-dashboard-react/#/auth/login) | [![Profile Page](https://github.com/creativetimofficial/public-assets/blob/master/argon-dashboard-react/user-page.png?raw=true)](https://demos.creative-tim.com/argon-dashboard-react/#/admin/user-profile) [View More](https://demos.creative-tim.com/argon-dashboard-react?ref=adr-github-readme) ## Quick start - `npm i argon-dashboard-react` - [Download from Github](https://github.com/creativetimofficial/argon-dashboard-react/archive/master.zip). - [Download from Creative Tim](https://www.creative-tim.com/product/argon-dashboard-react?ref=adr-github-readme). - Install with [Bower](https://bower.io/?ref=creativetim): ```bower install argon-dashboard-react```. - Clone the repo: `git clone https://github.com/creativetimofficial/argon-dashboard-react.git`. ## Documentation The documentation for the Material Kit is hosted at our [website](https://demos.creative-tim.com/argon-dashboard-react/#/documentation/overview). ## File Structure Within the download you'll find the following directories and files: ``` Argon Dashboard React . ├── Documentation │   └── documentation.html ├── CHANGELOG.md ├── ISSUE_TEMPLATE.md ├── LICENSE ├── README.md ├── package.json ├── public │   ├── favicon.ico │   ├── index.html │   └── manifest.json └── src ├── assets │   ├── css │   │   ├── argon-dashboard-react.css │   │   ├── argon-dashboard-react.css.map │   │   └── argon-dashboard-react.min.css │   ├── fonts │   │   └── nucleo │   ├── img │   │   ├── brand │   │   ├── icons │   │   │   └── common │   │   └── theme │   ├── scss │   │   ├── argon-dashboard-react.scss │   │   ├── bootstrap │   │   │   ├── mixins │   │   │   └── utilities │   │   ├── core │   │   │   ├── alerts │   │   │   ├── avatars │   │   │   ├── badges │   │   │   ├── buttons │   │   │   ├── cards │   │   │   ├── charts │   │   │   ├── close │   │   │   ├── custom-forms │   │   │   ├── dropdowns │   │   │   ├── footers │   │   │   ├── forms │   │   │   ├── headers │   │   │   ├── icons │   │   │   ├── list-groups │   │   │   ├── maps │   │   │   ├── masks │   │   │   ├── mixins │   │   │   ├── modals │   │   │   ├── navbars │   │   │   ├── navs │   │   │   ├── paginations │   │   │   ├── popovers │   │   │   ├── progresses │   │   │   ├── separators │   │   │   ├── tables │   │   │   ├── type │   │   │   ├── utilities │   │   │   └── vendors │   │   ├── custom │   │   └── react │   └── vendor │   ├── @fortawesome │   │   └── fontawesome-free │   │   ├── LICENSE.txt │   │   ├── css │   │   ├── js │   │   ├── less │   │   ├── scss │   │   ├── sprites │   │   ├── svgs │   │   │   ├── brands │   │   │   ├── regular │   │   │   └── solid │   │   └── webfonts │   └── nucleo │   ├── css │   └── fonts ├── components │   ├── Footers │   │   ├── AdminFooter.jsx │   │   └── AuthFooter.jsx │   ├── Headers │   │   ├── Header.jsx │   │   └── UserHeader.jsx │   ├── Navbars │   │   ├── AdminNavbar.jsx │   │   └── AuthNavbar.jsx │   └── Sidebar │   └── Sidebar.jsx ├── index.js ├── layouts │   ├── Admin.jsx │   └── Auth.jsx ├── routes.js ├── variables │   └── charts.jsx └── views ├── Index.jsx └── examples ├── Icons.jsx ├── Login.jsx ├── Maps.jsx ├── Profile.jsx ├── Register.jsx └── Tables.jsx ``` ## Browser Support At present, we officially aim to support the last two versions of the following browsers: <img src="https://github.com/creativetimofficial/public-assets/blob/master/logos/chrome-logo.png?raw=true" width="64" height="64"> <img src="https://raw.githubusercontent.com/creativetimofficial/public-assets/master/logos/firefox-logo.png" width="64" height="64"> <img src="https://raw.githubusercontent.com/creativetimofficial/public-assets/master/logos/edge-logo.png" width="64" height="64"> <img src="https://raw.githubusercontent.com/creativetimofficial/public-assets/master/logos/safari-logo.png" width="64" height="64"> <img src="https://raw.githubusercontent.com/creativetimofficial/public-assets/master/logos/opera-logo.png" width="64" height="64"> ## Resources - Demo: <https://demos.creative-tim.com/argon-dashboard-react/#/admin/index?ref=adr-github-readme> - Download Page: <https://www.creative-tim.com/product/argon-dashboard-react?ref=adr-github-readme> - Documentation: <https://demos.creative-tim.com/argon-dashboard-react/#/documentation/overview?ref=adr-github-readme> - License Agreement: <https://www.creative-tim.com/license?ref=adr-github-readme> - Support: <https://www.creative-tim.com/contact-us?ref=adr-github-readme> - Issues: [Github Issues Page](https://github.com/creativetimofficial/argon-dashboard-react/issues?ref=creativetim) - **Kit:** | HTML | Vue | | --- | --- | | [![Argon Design System HTML](https://github.com/creativetimofficial/public-assets/blob/master/argon-design-system/argon-design-system.jpg?raw=true)](https://www.creative-tim.com/product/argon-design-system) | [![Vue Argon Design System](https://github.com/creativetimofficial/public-assets/blob/master/vue-argon-design-system/vue-argon-design-system.jpg?raw=true)](https://www.creative-tim.com/product/vue-argon-design-system) | ## Reporting Issues We use GitHub Issues as the official bug tracker for the Material Kit. Here are some advices for our users that want to report an issue: 1. Make sure that you are using the latest version of the Material Kit. Check the CHANGELOG from your dashboard on our [website](https://www.creative-tim.com/?ref=adr-github-readme). 2. Providing us reproducible steps for the issue will shorten the time it takes for it to be fixed. 3. Some issues may be browser specific, so specifying in what browser you encountered the issue might help. ## Licensing - Copyright 2021 Creative Tim (https://www.creative-tim.com/?ref=adr-github-readme) - Licensed under MIT (https://github.com/creativetimofficial/argon-dashboard-react/blob/master/LICENSE.md?ref=creativetim) ## Useful Links - [Tutorials](https://www.youtube.com/channel/UCVyTG4sCw-rOvB9oHkzZD1w?ref=creativetim) - [Affiliate Program](https://www.creative-tim.com/affiliates/new?ref=adr-github-readme) (earn money) - [Blog Creative Tim](http://blog.creative-tim.com/?ref=adr-github-readme) - [Free Products](https://www.creative-tim.com/bootstrap-themes/free?ref=adr-github-readme) from Creative Tim - [Premium Products](https://www.creative-tim.com/bootstrap-themes/premium?ref=adr-github-readme) from Creative Tim - [React Products](https://www.creative-tim.com/bootstrap-themes/react-themes?ref=adr-github-readme) from Creative Tim - [Angular Products](https://www.creative-tim.com/bootstrap-themes/angular-themes?ref=adr-github-readme) from Creative Tim - [VueJS Products](https://www.creative-tim.com/bootstrap-themes/vuejs-themes?ref=adr-github-readme) from Creative Tim - [More products](https://www.creative-tim.com/bootstrap-themes?ref=adr-github-readme) from Creative Tim - Check our Bundles [here](https://www.creative-tim.com/bundles?ref=adr-github-readme) ### Social Media Twitter: <https://twitter.com/CreativeTim?ref=creativetim> Facebook: <https://www.facebook.com/CreativeTim?ref=creativetim> Dribbble: <https://dribbble.com/creativetim?ref=creativetim> Instagram: <https://www.instagram.com/CreativeTimOfficial?ref=creativetim> <div align="center"> <h1><code>Vajra Money on Rainbow Bridge</code></h1> <p> <strong>Stablecoin Streaming on 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 max@near.org 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 max@near.org). 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 max@near.org; * For `<testnet_nodes_url>` you can use `http://rpc.testnet.near.org/`. If you are working in NEAR organization please ask max@near.org; 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 ``` --> # 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`. # EthBridge Ethereum Light Client built on top of NearProtocol with Rust ## Testing ```bash ./test.sh ``` # 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)
Learn-NEAR-Hispano_NCD2--CodingHope
.cache 00 c62409ca3d86638b58edc3bca7c937.json 01 cb1e1cc5f502bc59e2ff7c009a6cff.json 02 960fe6f943f643207e5758e927c5b6.json 9e41a704a7ebc97c68c5f4606bac50.json 03 1d87e942581dd7e561b25b0f2147aa.json 3f6e2cef26ee95ce0d8ce1ac0f1568.json 04 906dcc03451a408faa77d4c88395b1.json a0acd6ca5825ebe43d51b0386200ca.json 06 aa9c8a63b28f7ce8a9bbd9161467af.json 07 519d75bf12307e3aefba12afb34b46.json 08 f37e15d5838d694264adcada02e40c.json 09 6602d2c121a02123d5b01559ce8668.json 0a b8462efdffdb6e4f81571a4da442c7.json bf5a5e582b602fc7682d24bb877a3e.json 0c 3b901a71d3ca9315fdfe78b72cefa4.json 4a10f686fb7e839026ec7592b8ca63.json 0d f1d3046c1c0c574658597953cbc148.json 0e 2f169078c5fba4d8650c868c2bcb97.json 62afcd387c83c3d96a8df38c9eea22.json 0f 397d838327963747032bf3fb8d2160.json 10 00e1735d20b2a6edc9811e83c38336.json cf1888206908f6fabfb66365dbf880.json 11 e3aa2f9d8312af31cc71f2203faf7b.json 13 a783949e0cc65df4a3d3e4bbdcfa64.json b073e4c170b60b75d9376aa4aa2e59.json 15 189afa10604f44a340e80a2f26f0c4.json d1106a76d14b24d463f1d3bf004415.json 17 0b273ab017923e18191d8d1fc6eb08.json 130a77c9902a61805cdc3fbffa9df8.json 2853453f765bda2d72695afe7bf3f9.json 376672b42ad14639d54c39940af44d.json fad1fa445f867a2699a874a02798cd.json 18 f073733906346b05f4336de7d907d0.json 19 bc8b1944f4e407ca968a3941643743.json 1a afef8b55f8edcedc793db8f61c5f7f.json d105a06ef7f4654a1d456bcb752801.json 1c 8ecf99eb9cc0d37c53207c5a71d93a.json 1d 0c0f7234b41ac1b0b251d21d1045cb.json 1e 0f1693a446ac29906dac7611cf702b.json 1f 6dafc1757ac83806a7732ba759d20d.json 21 22c47b4d07999b26ae5376d0516b50.json e25d8d1264e495dbfe61e4ca96b77c.json 23 1c65a50e0218b95b4ecb38ab6b8d1b.json 3264d7c38299ae120cf77f301db3c3.json 92ed859ce2c7df375909bf706628e3.json 24 6e8b56cfdf6274a0461631d1c9b8ad.json c556bcbb761973db6df07ae3223f62.json ef97651a5c52d765e346201499488d.json 25 70f87a387779afaed6f38b73bd57a5.json 26 33652225a7755c359f22f178c0f203.json 29 1518131a1eb1fa69317776bfcc67ba.json 22c09d4b38321cb50ee88fb3fd4204.json 2b 9ac783b7d8530353cff2033b252ee9.json 2c 426faae20c1f7f7cacce9ef822f6fd.json 4d6874015ed476d8138ac214e3f614.json cdd484b7b8f6527db034b601b93c55.json 2d 6b275fed6d5b928d10d8c3655868ad.json acfd124582d6977bfe555185f0489c.json 30 844ac3b5ee1970c64f8fcbb76c7537.json ce079b11b3cdc7d52aa8d81b9a9a37.json f9aea5b7182b11b26979724010c3cc.json 33 71dc346332b66c682604b8b2ec3652.json 9a019aebc0100641846e1abe512fe1.json 34 3225ba079aae2d1a1204f76a597192.json 6197687429fb3af0faf7093ef8d75b.json 855e496d91e6704180f0c56fe7c1d8.json 9cf411a73dfa377a83beebe4022c21.json d6abf5b898820202da735d4555ba77.json 35 b2c1e66c75fcab6854d68f770392f3.json 37 78a6c1a7446f09f3cfcdba1b9eef44.json 38 142f257ac02c766ef1800fd483a679.json fffdf559546e96ff79f009fe44d398.json 3a c1cb3239e2a6ac5979ca8c30862293.json 3b d6b87e2b3fd689de7bcfb1733b8356.json 3c 3a9c9f1cc25fc69a7fb8c48b71f50e.json a18beb1261657da6a4f04b9e1e7453.json 3f 3d017315d721f59b49bc7f5b675a64.json 41 d4c10c407d95b9edd5d626190b18fa.json 42 a945dbbeb824c6a02ea9071f8892f6.json 46 a60dfb95dff1763054ae46fda28bad.json 47 60e771c8af1ab5c2af2d98bbac56a6.json e54b57271c9089942677fe6744fef6.json 48 80350f576b81663ff4ea202d0b308e.json d7de76b8826dbfd4e5253c62e3a0ea.json 49 13821624de3fa415229a672956db39.json 19a7b346237a2fadba0fbf77a851b8.json e16e5726f7af86854c103883da705e.json 4c 1379250d2987248ea8a5c7b2475b63.json 4d 652f6e7bc89516af47c69464d038f8.json d1ae7a945cb3e1c6c644613e435b7d.json 4e 2ee7e5e9e0a46ffe9a7733ba0f5a31.json 4450d45f524d547d6226052ed6124b.json 4f 4b06afea49bab9b9693415f53a7502.json 50 7aa610e165ee4513e430165b1f356a.json dd637ecccd53e9d12a5ac50dcb9d7d.json 53 f1639fb64f2db13b784cce68eb1950.json 55 5310480117d44f0ce42ce3925fd61f.json 9b4dad66e1b09548154a4acb3232c6.json ad552165db5a1698b32b356e38f13c.json 56 245ca93648ca833ebd9fdd695b6656.json 2a2d61ba25de2f6ed950bb9d843460.json f9809bc072923cc7fb10cc0f8b9ae7.json 58 4ca48e18b44bf19999369f95a1733a.json a1c46122f6ceb547149927d9786234.json 5a b36e7acd0502fc87a2a6e2cd4ffcb5.json b3af7ce1a060f1bfaa44ceaae75eb3.json 5b bb34b8583439e169e27a5485e8967d.json 5d 407e9139dee6758efebbdfbe655da5.json 82c473ec6e8bbb8625c31556e1f7d9.json 5e 34eba70a2e1df9479efa00a675c4f4.json 60 d40b0ede5f54b7c6c2e6b1bc57fa35.json ea651d51f752c3d671696c1eb6711b.json 61 f355dbb2704114982176db7026a856.json 63 07c6ef9137a59170d1614241a4128b.json 8c12bfb2e21cb12de5ca6b1183e685.json 64 439cb26026c5c27ef21883a6d9b326.json a72638ed1bd3be6dcf88b41ab3cc29.json 65 d509cbd24deaae9f965d6e5a1c0311.json 66 823a8c0e01b4d76fc2ecdc1b19499a.json b3ee56a76eeb4d0a9c4dfce9ddf533.json 67 a619e84e78350a8c57b9f8d67660a7.json fe891dcaf13b85fbc356c735f8b59b.json 68 153aa01d6a00d0fdb5190cdfacbc66.json ed7808301153863f7829e1c8106209.json 69 05f2ac18764f8f46166ce74d096a0d.json 16e17733c1e82e720b0defbfbf1757.json 6a 1b06e4635e5af3a3f19d8f10ad3f28.json 3e6c1a74a4ff7f56a20046ea92fc2c.json 6c ba24b7670b45d50ef2cd1dbc2330dd.json e1b3c233aa07e369a590f910b42108.json 6d 675fde9dfc85641eac1c5219dd47fe.json ec25233e21d96598c87f5ddf56276d.json 6f 42ec5992753747c5e48b7b26b9a2d9.json 70 6ecfba96c6f71a8c82139fa2bcbc07.json a40a7e4c107ea82937ef522e121de5.json 71 a11ad7b25ac1374297a9a21484e86e.json d431514f34f98d5bf236ffb6223b11.json 73 4698378898f44dc5683964eaa99ecb.json 75 5823edf7810eaddf55dab36606d15a.json 77 38ffa2f5c458d065f35354202388c8.json 78 0c653d771dab102f951c0e9e693cf4.json e3f305c68ffca540d5b51c9f4c09f6.json 7a ea024216e656ebb4e0767c76203958.json 7b 3ccdf5fa33a2c8c010bf30bec87fc0.json 7d b83ebb57b273592286b4d03226207d.json 7e 10e98eb0f324a84d30d12b0f7a5706.json 57f9531d8d97ac43e7a1a79a3cbfa7.json 9260c1b4538954085fc29b9b5d5f9e.json dd516baf19f88c9a633187016fe409.json e5be6ab46b733410f5404bb14f5f25.json 80 b661ce9f60a6b34dc23ba073ad7c20.json 82 08c5ce73c6defc36310da97b4d3e5d.json f556dbaeba20e23ed5cd154a318d06.json 83 a93c6359b18e88561815028eccef59.json 84 9775d4555adbdee7efb1f7199a4984.json 85 a9919c05c1a35d0f3779ff87a1e7ff.json 87 04b980540652bcc1a8630c962eb4cb.json fd75390dc00a81ff1a9f79254ef496.json 89 50ffd2546a7af06597e0f32d7fa622.json 8a a48c17b6a5634f19d7e25b6c7befc5.json b6aff1072904678c92d00f30d06160.json 8b fb9d624c0048fbe3524e6b91f158d2.json 8c c17934389a70266a7d55093f644228.json ddc7c946a8e3a626ba25346b32fc47.json 8d 83a6cb772452bcb84cfb92692e00da.json 8e c4c46d9986679d5750e3d51253fbed.json cf5792b4cbc222a6cbfa832337e00b.json 8f d8b22a355c22ba7a4c0fdca78f5c4d.json e52f269c7036c23bb96784e73d8761.json e6f112cde632675b7962f756f43a4d.json 92 80fe511a2488d41320b3c3c3503691.json 93 15cc85abaabfe848dc4328ae0ad3dc.json 94 935a5413eaa6cabba8a9ae5fc60f1f.json 9bdc1feef02574167a99db3539e7a8.json 95 7cf66c65c96ae61adbd8bd90889078.json 98 32c8c09c9b2c46a90186ec56b2fba6.json 355906b441a58a80049c4b16f74919.json 3d48f8cad5483e21053999b5fbcc5b.json 65315b7b6d214e1edc10228e90e200.json b3dbddeb53efbf78b111bad68c9eb6.json ce7629c39b952e3639a11700b97175.json eae6958a1e2bfa9fa154aa091936c4.json f8b7fd1208f369b8d6ec977a3b1b77.json 99 a613d93de83f92848ad514933fed5f.json b3b02ffebf89f3ed4d68b8ebcd2870.json 9a 0e8af0b2dd30924878ff3f9306e9fd.json 7a8947d40f4946beea36e299c38113.json dc474109f6791e8fe847f18214c210.json 9c 0f0d28801ff1ce903faf7bcf7fc57b.json 34c1b0cb8a2a34d9f411ffb2e6808e.json 5e8fa3641b361ea17e210af976c213.json 5e9e352d7904ed12c97811a396d45b.json 9e c82777eeeea8f71e38c0bcae5e4325.json 9f 365391b65030342655d5880b36238d.json a1 3d83ee9d17f11ee212ce2e4e8d04cb.json a3 b2c2937eb3a244b17ab601022e6bf5.json a4 14eca676f4e803b8079983d474ceff.json f33402bf8ec55cb0ad0fc50a039ded.json a5 c54a6b527ac1957777b308cb711d6a.json a6 0c9eeb097ba5ecfdf409c90387916b.json 20f61e1bf7624a75a3ac9905b83403.json c81da9607bda7b0c66d7b40fa9373f.json a7 f54737a6f84bc989dcec5f6ece9eaa.json a8 14df6c32eaf517087a354610c07e48.json 6039f5985d9da4f3233d32a4ee536b.json a9 1b4f8d043679a18927ea794a8799b5.json 516a94570ec2a9ebe9b8c4784a092b.json aa 20e6b096a31897e9216ef2462b1085.json ab 4d6e0d16239306d756ef0efc45cf0f.json 8effa370409b1435db447ef095362f.json ad b100d7f36ceab0ff892cc0bc990045.json ae 1e9615c69518fe2c697b83cf4bd7af.json 8dd0b16942a7a9518e83e1fe68f83e.json af 429c3e1b4e27bbec31f2233967b3da.json 46061f98d800c1b5bcad5a537602f9.json b1 7dd8351f3493852d307d41786a61aa.json b2 be9d163cb36f592ca20b79ff40393f.json b3 5ab6f5641bda6f86c9535a0d57895c.json b4 894ecb802174424b5426398448692a.json b5 536d61704cf32e12e308c8194274bc.json b6 23c460cd02f31743660190895f514c.json 37e292d1f5bbe212f1223c52597b6c.json b7 cb504ffa8bed8350c9ca1bdd616130.json b8 571e55259a21fe02e8fc0984920b39.json b9 d8fc062be3d0ab298ff389becf64cf.json ba f8f3369aad690a1099251224f665e5.json bb 341e61ef85531f4861416420398835.json 9636ee1eebc51c97f2a4d56c5948c3.json bc d216bc202aa2420b487101c20f0926.json bd 8b3a4187b25362760ad4374f3eb783.json c4f0eaaa29f2522c876db0621a86e8.json be 95bc0859016b69c1f272f8abf8870f.json c1 a42fa5c4b8bd26fbee34d7ab1d8dd4.json d2adc6b8d2ff941b37361b0f2a875c.json c2 4922baece42c3d537d69b2a15cc35c.json 81f87ccfa10bc14e02f6d290a7ae0c.json c3 69da8192697df7bbf29a4be9ebdf37.json c4 04e898b9aaa417bca572045d9309e9.json 13fc0e192d689a21d528b94ef21b36.json c5 2daf0c3245e4a8cd940c7d9b26512f.json c6 197dfbfa09ea95726b2a467ca2a8cb.json 32f22a438e58daa55568a3841f95b1.json 7426258961e54d604d2175c5274708.json ac57f954bc006d3de4765a7afa41f8.json c7 264a7192fa63514db7f19593948881.json 8ea0bfcd30106aa2fbb4f99eb55b76.json c9 900acbec6e16f6e98c2f33d8130d33.json e16de7faf1d4237e3974a21a3bce86.json f2e67370deb4b54c1fce2e31cb1f39.json ca 03758f82753d35e9e3fed4a54dd5d1.json 3b6f2e676236d87af10e8f1e77554b.json cd 5f856ef63e18a53a35fc6c4cf06c7b.json 83e97fb39c301a9dc2c45ec6e78946.json d4504fd266c98d5c2936b849e75e30.json d0 631541e202708adad4cdfe1202896c.json d485e0a973fc046e1a6a7d78025e7b.json d1 e74e41f85d0d1460a53f2326aaf317.json d2 8cfc7986ee3c13e8eeda62a7bf94a2.json e618a28410b4b9a2fe800009be4282.json d3 8aa355a9d138f88de4343ed6a98e9a.json b3df15902415a111e2350cc325ab55.json d4 4ada6ee3be4b677e4758c4002cc6d2.json 5cdaf888a0fd9c9395f02e72c78df8.json d6 55a0077bf68613d5863d02fa30d3b5.json d7 7a811f2158c1f9ff62f09996a42731.json da c03cf287e347cf5295bc145d586263.json db 363a8ae12b36d8f3b82f9e60520f3d.json dc 14fada2329a373cc10813334ee8518.json 9a31ba4bcbb36234a46f9394942815.json dd 0a1453d26ed4058cf178e0476da124.json 928ecba5fdab13d7093ad4e5d790b9.json a5aac9fe75175a39b639a14f9abbec.json de 0075baf3dca0b932e1c0403ee1e9d1.json df 54789c2568e7e44cfe9eed80765736.json 722a0ee9e8e9def846d46f09d79112.json e0 700fa7e8464522efc0f7c8e4e67974.json e82fc7e21b343714c34ad1374909c1.json e1 01d57e85df46e9e0f8363024843f22.json e6fee33295ecf2313f21e892298ebd.json e2 40c9675dba8c98c32372e79fb92521.json e4 6fa65de0061a2056cfaa7485284550.json e5 262c2bc372937bb1159f75548ed5c5.json fac2ecb00fcdc57216ec3db7d5abb0.json e8 1eae153efb844c0e2d34d5523da84c.json 22bb5fab772fd057ef299f5955f5f6.json e9 007249fcae8984f9d5a29d1837d348.json ea 7cc7e27fcabcb7b08be34ec040c045.json eb 03c45ccb113d1a863ad896a95e68aa.json ec 12973455a8e45f97d798bd08f52ad8.json 6a8fec6cb86c242808fc543a7677f0.json bfa1ac6278b2074eda1ec388441153.json ed 1a4075411a1c823bc31b86dbd3f9d7.json 4661aecdb675962af26402e7f54d08.json ee 613091b71e2f67bd243a78e47e4371.json ef 2db2bd8b10ba6e9093130859c119fd.json 4bd3526d73a826a4635ee5fa2307f7.json f0 1db671973f8aca678c54aea3073033.json d3db616bde5be6bf45bc14d207ca89.json f1 53f0ac497637dbe524493822b41cc7.json f2 1a920c00fb4cb0404e25f4f5422c22.json 6bc9c55ff92e65cb8ebac74f85c83d.json f3 3ea46a1b3e9ca22530e940127cdcab.json f4 479d9b1fe84500f66c916abdf1a839.json f5 b50ba85be6be6e85dd8c8e726f23d8.json f6 c88c1bdff5008cb151f40380a79fc7.json f8 e0c3864ad1ff7a0f962dc93eda6ae0.json f9 08a2bc72a52ce1c902b8978239675f.json 5b52afc19c8a0ef8b792cb72318951.json 6f33362a10ca0a27fc9dfc48f0b09f.json fa 521b09690a0dd8da40a97e9510afee.json f024fab0ae8ffac74ba45f0262ad3b.json fb 07a4c1485b44b192d3e1a727f90e37.json 5997ed272edf37771076550f6abf05.json ff 382b35731ba16ad6c4c989ff69189e.json 610b93e319c49c7fa6fc62a57871c5.json e0672e475dfc5f09eb5daed5ae95b4.json File Name: style.css import Fonts import Files skeleton .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 models.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 | | | dist bootstrap.min.8c957710.css custom.ba64f85d.js global.eca22910.css index.html jquery.min.b2d9c366.js logo-black.3916bf24.svg logo-white.c927fc35.svg popper.min.6066f208.js solicitar_ayuda.html solicitar_ayuda_diseño.19bc99bf.js solicitar_ayuda_diseño.7f34c832.js src.0f970cdb.js style.c038c74d.css package-lock.json package.json src assets logo-black.svg logo-white.svg config.js css bootstrap.min.css style.css global.css index.html index.js index_original.html js bootstrap.bundle.min.js custom.js jquery-3.0.0.min.js jquery.mCustomScrollbar.concat.min.js jquery.min.js plugin.js popper.min.js main.test.js solicitar_ayuda.html solicitar_ayuda_diseño.js utils.js wallet login index.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). # 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) # 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 }); }); ... ``` # 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. # 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. # 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. 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 ``` # 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 # 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. # 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. # <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 # 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) ### 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. # 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. # 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. # 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) # 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) # 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 [![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 # 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. ## 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. # 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). # [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-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 # 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. # 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;julian@juliangruber.com&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. # 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-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._ ### 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. 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)); ``` # 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) 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) # 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/ # 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) # 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. Like `chown -R`. Takes the same arguments as `fs.chown()` # 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 ``` # 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). 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. # 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 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 # 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 # 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 # 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._ # 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 # 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. [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;lauri@rooden.ee&gt; [The MIT License](http://lauri.rooden.ee/mit-license.txt) # 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._ 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. # 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.) [![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) [![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_ Shims used when bundling asc for browser usage. # 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() } } ``` [![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. 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) 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) # 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;tj@vision-media.ca&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. 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`. <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 ajv.validator@gmail.com - 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 // 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 # 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._ # 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 `acorn-jsx@3.0`. 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). # 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 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 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 ![](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"> <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 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. [![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/js-base64@3.7.2/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/js-base64@3.7.2/base64.mjs'; </script> ``` ```html <script type="module"> // or if you prefer no Base64 namespace import { encode, decode } from 'https://cdn.jsdelivr.net/npm/js-base64@3.7.2/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) ## 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 (olalonde@gmail.com) - James Talmage (james@talmage.io) - [Ruben Verborgh](https://ruben.verborgh.org/) ## License [https://github.com/follow-redirects/follow-redirects/blob/master/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. # 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 # 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. 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) ``` # 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). # 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. ### 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. # 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. # 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-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 # 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`. [![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). ## 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). # 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 <tannerntannern@gmail.com> * Website - [tannernielsen.com](http://tannernielsen.com) * Github - [tannerntannern](https://github.com/tannerntannern) # 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. # 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) ### 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. [![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). # 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) ``` # 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 # 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) # 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 # 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`. # 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. ### 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. ## 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. # 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. # 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) # 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 # 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 <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 # 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 # 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. # 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' ``` # 1. ¿Que es SeedingHope? _SeedingHope es un smartcontract desarrollado bajo el protocolo de Near, su finalidad u objetivo es que las personas que emprendan un programa social para ayudar a la comunidad, puedan solicitar donaciones para llevarlos a cabo y cumplir con sus objetivos._ **SeedingHope permite:** 1. Crear un programa social 2. Dar de baja un programa social 3. Consultar los programas sociales que están dados de alta en la aplicación 4. Recibir donaciones para programas sociales. ## 2. Instalación Local _Para poder instalar y correr SeedingHope de manera local (en tu equipo) es necesario que cumplas con una serie de pre-requisitos y pasos que deberás de llevar a cabo en estricto orden._ ### 3. 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 testnet near account 5. Instalar el NEAR CLI globally: ``` yarn install --global near-cli ``` ### 4. Clonar SeedingHope en tu equipo 1. Ingresar al repositorio depositado en GitHub: 2. Dar clic en **Fork** para que se cree una copia en tu cuenta de GitHub 3. Dar clic en **Code** y copiar la ruta del repositorio https:// 4. Ir a la terminal de Ubuntu y escribir el siguiente comando que permitirá clonar SeedingHope: ``` git clone ruta del repositorio ``` Ejemplo: ``` git clone https://github.com/usuariogit/SeedingHope-E9.git ``` 5. Una vez clonado desde la terminal ingresar a la carpeta de proyecto con el comando: ``` cd SeedingHope ``` 6. Loguearse con el usuario testnet indicando los siguientes comandos en la terminal de Ubuntu: ``` near login ``` 7. Se abrirá el navegador solicitando ingreses tu cuenta para loguearte y una vez hecho esto regresas a la terminal donde marcará como exitoso el procedimiento. ### 5. Correr el SmartContract de SeedingHope 1. Ya dentro de la carpeta del proyecto y siguiendo en la terminal, instalar la dependencia de [Node.js]: ``` npm install ``` 2. Generar el código y compilación del smartcontract de manera local: ``` yarn build && near dev-deploy ``` Con estos pasos realizados anteriormente ya podrás ejecutar en tu equipo el SmartContract de SeedingHope. ## Pruebas unitarias ------------------------------------- **1. Dar de Alta un Programa Social** Los usuarios interesados en recibir donaciones para su proyecto social, tendrán que registrar el programa e indicar el monto deseado a recaudar. Para dar de alta un Programa Social desde la línea de comandos de Ubuntu: ``` near call username.testnet nuevoProyecto '{"nombre":"nombre","descripcion":"descripcion ","cantidadMeta":monto}' --account-id username.testnet ``` **2. Dar de Baja un Programa Social** Los programas sociales que ya hayan alcanzado la meta o que su objetivo no fue cumplido podrán ser dados de baja de la siguiente manera, desde la terminal de ubuntu: ``` near call username.testnet borrarProyecto '{"id": id}' --account-id username.testnet ``` **3. Consultar un Programa Social** Generar una lista de programas sociales desde la terminal de Ubuntu que previamente fueron dados de alta: ``` near view usename.testnet mostrarProyectos --account-id usarname.testnet ``` **4. Donación a un Programa social** Consiste en que los donadores aporten Nears para apoyar al programa social y este pueda llegar a su meta y que el programa social pueda ser llevado a cabo: ``` near call username.testnet fondearProyecto '{"id": id, "cantidad": cantidad}' --account-id username.testnet ``` **5. Video demo con la funcionalidad del contrato:** https://youtu.be/OlqeNEvVXII [![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 # 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:pass@example.com: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:alpha@example.com,bravo@example.com?subject=SUBSCRIBE&body=Sign%20me%20up!"); //returns: //{ // scheme : "mailto", // to : ["alpha@example.com", "bravo@example.com"], // subject : "SUBSCRIBE", // body : "Sign me up!" //} URI.serialize({ scheme : "mailto", to : ["alpha@example.com"], subject : "REMOVE", body : "Please remove me", headers : { cc : "charlie@example.com" } }) === "mailto:alpha@example.com?cc=charlie@example.com&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. <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 `ignore@2.x` 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* # 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;tj@vision-media.ca&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-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). # 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)) ``` <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 ``` # 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() ``` # 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. # 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;julian@juliangruber.com&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 # 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._ # 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. # 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. # 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. 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. # 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) # 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) 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). # 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 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. # 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;julian@juliangruber.com&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 CodingHope 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 # 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 }); } ``` # 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 ``` <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: 'joe.bloggs@example.com' } ``` `$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 ajv.validator@gmail.com - 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) 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> 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) # 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 <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 <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> # 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. # `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/). # 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/yargs-parser@19.0.0/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 # 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) # 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
esaminu_test-rs-boilerplate-8
.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>`.
meghaa105_near-stackoverflow-64378144
Cargo.toml build.sh src lib.rs
PotLock_next-app
.github ISSUE_TEMPLATE bug_report.md enhancement.md feature_request.md README.md
# next-app NextJS application built for PotLock (on NEAR)
IgnacioMolinaPortoles_NCD--Memonear
README.md as-pect.config.js asconfig.json package.json src as_types.d.ts singleton __tests__ as-pect.d.ts index.unit.spec.ts asconfig.json assembly index.ts models.ts tsconfig.json utils.ts
# NCD Project Memonear 🎬 [Loom demo](https://www.loom.com/share/6f72b278a5fa4dbe8ba460a530bb06a7) 🎨 [Figma design](https://www.figma.com/file/CysKjUzYeDr2qUTBw5UohU/Memonear?node-id=0%3A1) ## Install dependencies ``` yarn ``` ## Build and Deploy the contract ``` yarn build near dev-deploy ./build/debug/singleton.wasm # Save the contract dev name (<dev-123-456>) ``` ## Guide 1. You need to create a new game with `createGame` function and send 1 near tokens 2. Player can start playing by checking different combinations, sending the position (x, y) to `checkCombination` of the 2 items to match. To add some difficulty to the game, when 2 items don't match, it won't tell you what items they are. 5. The player need to match all 6 items to win 4. The player can view the board at any moment by using `printBoard(gameId)` 6. If some player doesn't want to play anymore, the owner can call `mockGame` and finish the game 7. When 6 items are matched, the attached deposit when the game was created will be transferred to the wallet of the winner if the player completes the game in less than 8 plays, otherwise it will receive 0.5 near tokens. ## Run the game **Create a game** ``` # Save the game id to play near call <dev-123-456> createGame --account_id <account-id> --amount 1 ``` **View board for the first time** ``` near call <dev-123-456> printBoard '{"gameId": <game-id>}' --account_id <account-id> ``` **Start matching items** ``` near call <dev-123-456> checkCombination '{"gameId": <game-id>, "x1": <x-first-item>, "y1":<y-first-item>, "x2":<x-second-item>, "y2":<y-second-item>}' --accountId <account-id> ``` ## Owner functions **Get game info (playerId, Game state, Game deposit, Game board, Match count and User tries)** ``` near call <dev-123-456> getGameInfo '{"gameId": <game-id>}' --account_id <account-id> ``` **Hardcode game board to have only 2 items left to match** ``` near call <dev-123-456> mockGame '{"gameId": <game-id>, "userPlays": <amount-of-tries>}' --account_id <account-id> ```
JIC1816_Car-Near-Me
README.md as-pect.config.js asconfig.json neardev dev-account.env node_modules .bin sha.js .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 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 binaryen README.md index.d.ts package-lock.json package.json wasm.d.ts 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 @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 README.md 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.js tsconfig.json errors README.md lib-es helpers.d.ts helpers.js index.d.ts index.js lib helpers.d.ts helpers.js index.d.ts index.js package.json src helpers.ts index.ts tsconfig.json hw-transport-node-hid-noevents README.md lib-es TransportNodeHid.d.ts TransportNodeHid.js lib TransportNodeHid.d.ts TransportNodeHid.js package.json src TransportNodeHid.ts tsconfig.json hw-transport-node-hid README.md 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 README.md lib-es Transport.d.ts Transport.js lib Transport.d.ts Transport.js package.json src Transport.ts tsconfig.json logs README.md lib-es index.d.ts index.js lib index.d.ts index.js package.json src index.ts tsconfig.json @sindresorhus is dist index.d.ts index.js package.json readme.md @sinonjs commons CHANGES.md 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.js function.js index.js index.test.js map.js object.js set.js string.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.d.ts function.d.ts index.d.ts map.d.ts object.d.ts set.d.ts string.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 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 repl.d.ts stream.d.ts stream consumers.d.ts promises.d.ts web.d.ts string_decoder.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 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 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 agent-base README.md dist src index.d.ts index.js promisify.d.ts promisify.js package.json src index.ts promisify.ts 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-align CHANGELOG.md README.md index.js 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 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 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 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 binaryen README.md index.d.ts package-lock.json package.json wasm.d.ts 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 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 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 node_modules long README.md 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 runtime.ts target.ts tsconfig.json typeinfo.ts staticarray.ts string.ts symbol.ts table.ts tsconfig.json typedarray.ts uri.ts util bytes.ts 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 base64-js README.md base64js.min.js index.d.ts index.js package.json 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 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 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 boxen index.d.ts index.js node_modules camelcase index.d.ts index.js package.json readme.md 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-from index.js package.json readme.md 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 callsites index.d.ts index.js package.json readme.md 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 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 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 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 cross-spawn CHANGELOG.md README.md index.js lib enoent.js parse.js util escape.js readShebang.js resolveCommand.js package.json crypto-random-string index.d.ts index.js package.json readme.md 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 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 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 bin detect-libc.js lib detect-libc.js package.json 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 dot-prop index.d.ts index.js package.json readme.md duplexer3 LICENSE.md README.md index.js package.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 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 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 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 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-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 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.d.ts index.js package.json readme.md flagged-respawn README.md index.js lib is-v8flags.js remover.js reorder.js respawn.js package.json 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-constants README.md browser.js index.js 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 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-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.d.ts 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 hash-base README.md index.js package.json hasurl 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 https-proxy-agent README.md dist agent.d.ts agent.js index.d.ts index.js parse-proxy-response.d.ts parse-proxy-response.js package.json ieee754 README.md index.d.ts 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 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-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-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-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-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.js package.json tests.js 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 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 node_modules @babel code-frame README.md lib index.js package.json 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 js-base64 LICENSE.md README.md base64.d.ts base64.js package.json 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 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 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 keyv README.md package.json src index.js latest-version index.d.ts index.js package.json readme.md 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 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 long README.md dist long.js index.js package.json src long.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 micromatch 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 .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 mixpanel .travis.yml example.js history.md lib groups.js mixpanel-node.d.ts mixpanel-node.js people.js profile_helpers.js utils.js package.json readme.md test alias.js config.js groups.js import.js people.js send_request.js track.js utils.js mkdirp-classic README.md 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 mustache CHANGELOG.md README.md mustache.js mustache.min.js package.json napi-build-utils README.md index.js index.md package.json natural-compare README.md index.js 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 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-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 node_modules 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 binaryen README.md index.d.ts package-lock.json package.json wasm.d.ts 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-seed-phrase .eslintrc.yml .fossa.yml .travis.yml index.js package.json test index.test.js 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 node-abi .github workflows update-abi.yml .travis.yml CODE_OF_CONDUCT.md CONTRIBUTING.md README.md abi_registry.json index.js node_modules semver CHANGELOG.md README.md package.json semver.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 node_modules tr46 index.js lib mappingTable.json 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 package.json node-gyp-build README.md bin.js build-test.js index.js optional.js package.json 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 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 optionator CHANGELOG.md README.md lib help.js index.js util.js package.json p-cancelable 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-try 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 parent-module index.js package.json readme.md parse-passwd README.md index.js package.json 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 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 prelude-ls CHANGELOG.md README.md lib Func.js List.js Num.js Obj.js Str.js index.js package.json 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 progress CHANGELOG.md Readme.md index.js lib node-progress.js package.json pump .travis.yml README.md index.js package.json test-browser.js test-node.js punycode LICENSE-MIT.txt README.md package.json punycode.es6.js punycode.js pupa index.d.ts index.js package.json readme.md 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 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 node_modules strip-json-comments index.js package.json readme.md 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 regexpp README.md index.d.ts index.js package.json 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 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 responselike README.md package.json src index.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 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 shebang-command index.js package.json readme.md shebang-regex index.d.ts index.js package.json readme.md 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 README.md index.js package.json slash index.d.ts index.js package.json readme.md slice-ansi index.js package.json readme.md source-map-support LICENSE.md README.md browser-source-map-support.js package.json register-hook-require.js register.js source-map-support.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.d.ts source-map.js 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 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-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-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 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 tcp-port-used README.md index.js node_modules debug README.md package.json src browser.js common.js index.js node.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 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 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 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 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-check README.md lib check.js index.js parse-type.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 universal-url README.md browser.js index.js package.json update-notifier check.js index.js package.json readme.md 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 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 v8-compile-cache CHANGELOG.md README.md package.json v8-compile-cache.js v8flags README.md config-path.js index.js package.json 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 wide-align README.md align.js package.json widest-line index.d.ts index.js package.json readme.md 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 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 | Inspector mode only ----------- features not yet implemented issues with the tests differences between PCRE and JS regex | | | | | nested-env-vars 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 tsconfig.json utils.ts
# 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) 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 <!-- -- 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 `uuid@3.x`?** Your code is probably okay, but check out [Upgrading From `uuid@3.x`](#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 `uuid@8.3` | | [`uuid.parse()`](#uuidparsestr) | Convert UUID string to array of bytes | New in `uuid@8.3` | | [`uuid.stringify()`](#uuidstringifyarr-offset) | Convert array of bytes to UUID string | New in `uuid@8.3` | | [`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 `uuid@8.3` | | [`uuid.version()`](#uuidversionstr) | Detect RFC version of a UUID | New in `uuid@8.3` | ## 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 `react-native-get-random-values@1.5.0` and `expo@39.0.0`. ### 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 `uuid@7.x` ### Only Named Exports Supported When Using with Node.js ESM `uuid@7.x` 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 `uuid@7.x`](#deep-requires-now-deprecated) are no longer supported. ## Upgrading From `uuid@3.x` "_Wait... what happened to `uuid@4.x` - `uuid@6.x`?!?_" 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 `uuid@3.x` 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 `uuid@7.x` 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 `uuid@3.x` was exporting the Version 4 UUID method as a default export: ```javascript const uuid = require('uuid'); // <== REMOVED! ``` This usage pattern was already discouraged in `uuid@3.x` and has been removed in `uuid@7.x`. ---- Markdown generated from [README_js.md](README_js.md) by [![RunMD Logo](http://i.imgur.com/h0FVyzU.png)](https://github.com/broofa/runmd) # 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' ``` 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 # 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 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. https-proxy-agent ================ ### An HTTP(s) proxy `http.Agent` implementation for HTTPS [![Build Status](https://github.com/TooTallNate/node-https-proxy-agent/workflows/Node%20CI/badge.svg)](https://github.com/TooTallNate/node-https-proxy-agent/actions?workflow=Node+CI) This module provides an `http.Agent` implementation that connects to a specified HTTP or HTTPS proxy server, and can be used with the built-in `https` module. Specifically, this `Agent` implementation connects to an intermediary "proxy" server and issues the [CONNECT HTTP method][CONNECT], which tells the proxy to open a direct TCP connection to the destination server. Since this agent implements the CONNECT HTTP method, it also works with other protocols that use this method when connecting over proxies (i.e. WebSockets). See the "Examples" section below for more. Installation ------------ Install with `npm`: ``` bash $ npm install https-proxy-agent ``` Examples -------- #### `https` module example ``` js var url = require('url'); var https = require('https'); var HttpsProxyAgent = require('https-proxy-agent'); // HTTP/HTTPS proxy to connect to var proxy = process.env.http_proxy || 'http://168.63.76.32:3128'; console.log('using proxy server %j', proxy); // HTTPS endpoint for the proxy to connect to var endpoint = process.argv[2] || 'https://graph.facebook.com/tootallnate'; console.log('attempting to GET %j', endpoint); var options = url.parse(endpoint); // create an instance of the `HttpsProxyAgent` class with the proxy server information var agent = new HttpsProxyAgent(proxy); options.agent = agent; https.get(options, function (res) { console.log('"response" event!', res.headers); res.pipe(process.stdout); }); ``` #### `ws` WebSocket connection example ``` js var url = require('url'); var WebSocket = require('ws'); var HttpsProxyAgent = require('https-proxy-agent'); // HTTP/HTTPS proxy to connect to var proxy = process.env.http_proxy || 'http://168.63.76.32:3128'; console.log('using proxy server %j', proxy); // WebSocket endpoint for the proxy to connect to var endpoint = process.argv[2] || 'ws://echo.websocket.org'; var parsed = url.parse(endpoint); console.log('attempting to connect to WebSocket %j', endpoint); // create an instance of the `HttpsProxyAgent` class with the proxy server information var options = url.parse(proxy); var agent = new HttpsProxyAgent(options); // finally, initiate the WebSocket connection var socket = new WebSocket(endpoint, { agent: agent }); socket.on('open', function () { console.log('"open" event!'); socket.send('hello world'); }); socket.on('message', function (data, flags) { console.log('"message" event! %j %j', data, flags); socket.close(); }); ``` API --- ### new HttpsProxyAgent(Object options) The `HttpsProxyAgent` class implements an `http.Agent` subclass that connects to the specified "HTTP(s) proxy server" in order to proxy HTTPS and/or WebSocket requests. This is achieved by using the [HTTP `CONNECT` method][CONNECT]. The `options` argument may either be a string URI of the proxy server to use, or an "options" object with more specific properties: * `host` - String - Proxy host to connect to (may use `hostname` as well). Required. * `port` - Number - Proxy port to connect to. Required. * `protocol` - String - If `https:`, then use TLS to connect to the proxy. * `headers` - Object - Additional HTTP headers to be sent on the HTTP CONNECT method. * Any other options given are passed to the `net.connect()`/`tls.connect()` functions. License ------- (The MIT License) Copyright (c) 2013 Nathan Rajlich &lt;nathan@tootallnate.net&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. [CONNECT]: http://en.wikipedia.org/wiki/HTTP_tunnel#HTTP_CONNECT_Tunneling [![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. 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) # 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) # 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 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` [![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) # 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) # 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. 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. 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/main?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 main/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/main/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/main/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. ## 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. # 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._ 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)); ``` # 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) # 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 # 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' ``` # 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 # 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). # 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. 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`. 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 # 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) # 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 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`. 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) # 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/yargs-parser@19.0.0/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 # 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' ``` # 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 # 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 # 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. <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 # 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) * [Keyboards and Mice](#keyboards-and-mice) * [Mac notes](#mac-notes) * [Windows notes](#windows-notes) * [Xbox 360 Controller on Windows 10](#xbox-360-controller-on-windows-10) * [Linux notes](#linux-notes) * [Selecting driver type](#selecting-driver-type) * [udev device permissions](#udev-device-permissions) * [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 v14 ### Supported Electron versions ### * Electron v3 to * Electron v11 #### Any newer version of Electron or Node MAY NOT WORK Native modules like `node-hid` require upstream dependencies to be updated to work with newer Node and Electron versions. Unless you need the features in the most recent Electron or Node, use a supported version. ## Installation For most "standard" use cases (node v4.x on mac, linux, windows on a x86 or x64 processor), `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. ### Keyboards and Mice 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. There are non-standard work-arounds for this, but in general you cannot use `node-hid` to access keyboard-like devices. ## 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 `node-hid@0.7.0`, the [hidraw](https://www.kernel.org/doc/Documentation/hid/hidraw.txt) driver is used to talk to HID devices. Before `node-hid@0.7.0`, 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 node-hid@0.5.7 ``` 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` * gcc-4.8+: `apt install gcc-4.8 g++-4.8 && export CXX=g++-4.8` * libusb-1.0-0 w/headers:`apt install libusb-1.0-0 libusb-1.0-0-dev` * libudev-dev: `apt install libudev-dev` (Debian/Ubuntu) / `yum install libusbx-devel` (Fedora) ### 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 * 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-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. # 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 # 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. # 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;tj@vision-media.ca&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. # 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. ### 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. # 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 # 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. <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 # simple-get [![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-get/master.svg [travis-url]: https://travis-ci.org/feross/simple-get [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) {}) ``` ### 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). [![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). # 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 ### 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. 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. # 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`. 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). ## 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. 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. <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 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). # 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 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 }); }); ... ``` # 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). # 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 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 }); }); ... ``` # 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 # 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 # 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. # 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. # 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')` # 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 # 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 # 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_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. # 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://github.com/prebuild/prebuild-install/actions/workflows/test.yml/badge.svg)](https://github.com/prebuild/prebuild-install/actions/workflows/test.yml) [![david](https://david-dm.org/prebuild/prebuild-install.svg)](https://david-dm.org/prebuild/prebuild-install) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/) ## 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" } } ``` ### 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` and `--platform` 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` and `npm_config_runtime`. ### 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 `leveldown@1.2.3` 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` ## License MIT ### 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. # 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 ``` [![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 # 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 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) # 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** # core-util-is The `util.is*` functions introduced in Node v0.12. # 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) ``` <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 ajv.validator@gmail.com - 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) # 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. # 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 <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/main?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/main?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 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> 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> 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 <nathan@tootallnate.net> 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. # 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 (emn178@gmail.com) # 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 ``` 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 }); ``` # 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. 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 ``` 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 `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value components are invalid (`9999999999999999.4.7.4` is likely invalid). 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` # 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 # 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/ # 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 tslib@1.6.1 ``` ## yarn ```sh # TypeScript 2.3.3 or later yarn add tslib # TypeScript 2.3.2 or earlier yarn add tslib@1.6.1 ``` ## bower ```sh # TypeScript 2.3.3 or later bower install tslib # TypeScript 2.3.2 or earlier bower install tslib@1.6.1 ``` ## JSPM ```sh # TypeScript 2.3.3 or later jspm install tslib # TypeScript 2.3.2 or earlier jspm install tslib@1.6.1 ``` # 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/) 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;nathan@tootallnate.net&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. # 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;tj@vision-media.ca&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. # 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. 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` # 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. # <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 # 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._ # 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._ # 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. # 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. # 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 # 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. # 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. # 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 # 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 <tannerntannern@gmail.com> * Website - [tannernielsen.com](http://tannernielsen.com) * Github - [tannerntannern](https://github.com/tannerntannern) # 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 # 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. # 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. # 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) Like `chown -R`. Takes the same arguments as `fs.chown()` # `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/). 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. [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;lauri@rooden.ee&gt; [The MIT License](http://lauri.rooden.ee/mit-license.txt) # 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_BUILD` | 🚫 | | [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` | 🚫 | | [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` | ✅ | | [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` | ✅ | | [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` | 🚫 | ## 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) # 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. # 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) # 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. # 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. # 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) # 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. # 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 # 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. # 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 # 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). # 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. # 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 # duplexer3 [![Build Status](https://travis-ci.org/floatdrop/duplexer3.svg?branch=master)](https://travis-ci.org/floatdrop/duplexer3) [![Coverage Status](https://coveralls.io/repos/floatdrop/duplexer3/badge.svg?branch=master&service=github)](https://coveralls.io/github/floatdrop/duplexer3?branch=master) Like [duplexer2](https://github.com/deoxxa/duplexer2) but using Streams3 without readable-stream dependency ```javascript var stream = require("stream"); var duplexer3 = require("duplexer3"); var writable = new stream.Writable({objectMode: true}), readable = new stream.Readable({objectMode: true}); writable._write = function _write(input, encoding, done) { if (readable.push(input)) { return done(); } else { readable.once("drain", done); } }; readable._read = function _read(n) { // no-op }; // simulate the readable thing closing after a bit writable.once("finish", function() { setTimeout(function() { readable.push(null); }, 500); }); var duplex = duplexer3(writable, readable); duplex.on("data", function(e) { console.log("got data", JSON.stringify(e)); }); duplex.on("finish", function() { console.log("got finish event"); }); duplex.on("end", function() { console.log("got end event"); }); duplex.write("oh, hi there", function() { console.log("finished writing"); }); duplex.end(function() { console.log("finished ending"); }); ``` ``` got data "oh, hi there" finished writing got finish event finished ending got end event ``` ## Overview This is a reimplementation of [duplexer](https://www.npmjs.com/package/duplexer) using the Streams3 API which is standard in Node as of v4. Everything largely works the same. ## Installation [Available via `npm`](https://docs.npmjs.com/cli/install): ``` $ npm i duplexer3 ``` ## API ### duplexer3 Creates a new `DuplexWrapper` object, which is the actual class that implements most of the fun stuff. All that fun stuff is hidden. DON'T LOOK. ```javascript duplexer3([options], writable, readable) ``` ```javascript const duplex = duplexer3(new stream.Writable(), new stream.Readable()); ``` Arguments * __options__ - an object specifying the regular `stream.Duplex` options, as well as the properties described below. * __writable__ - a writable stream * __readable__ - a readable stream Options * __bubbleErrors__ - a boolean value that specifies whether to bubble errors from the underlying readable/writable streams. Default is `true`. ## License 3-clause BSD. [A copy](./LICENSE) is included with the source. ## Contact * GitHub ([deoxxa](http://github.com/deoxxa)) * Twitter ([@deoxxa](http://twitter.com/deoxxa)) * Email ([deoxxa@fknsrs.biz](mailto:deoxxa@fknsrs.biz)) 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) # 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. # 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;julian@juliangruber.com&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. # 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/become_a_patron_button@2x.png" 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._ # 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' ``` # 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;christopher.s.dickinson@gmail.com&gt; - Release GPG key: 9554F04D7259F04124DE6B476D5A82AC7E37093B * **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) &lt;calvin.metcalf@gmail.com&gt; - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 * **Rod Vagg** ([@rvagg](https://github.com/rvagg)) &lt;rod@vagg.org&gt; - Release GPG key: DD8F2338BAE7501E3DD5AC78C273792F7D83545D * **Sam Newman** ([@sonewman](https://github.com/sonewman)) &lt;newmansam@outlook.com&gt; * **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) &lt;mathiasbuus@gmail.com&gt; * **Domenic Denicola** ([@domenic](https://github.com/domenic)) &lt;d@domenic.me&gt; * **Matteo Collina** ([@mcollina](https://github.com/mcollina)) &lt;matteo.collina@gmail.com&gt; - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E * **Irina Shestak** ([@lrlna](https://github.com/lrlna)) &lt;shestak.irina@gmail.com&gt; [![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 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. 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. # 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 # 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 <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 # 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 # 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. # 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. ## 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. # 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) # [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} } ``` <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 ``` <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). <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 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 # 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) # 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._ # 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. # 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._ # 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 # 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 # 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. # 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;julian@juliangruber.com&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. # 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) # 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). # `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 ``` # 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() ``` ### 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. # 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 `acorn-jsx@3.0`. 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). # 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 # 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) 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 # 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], } */ ``` # 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)) ``` # 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._ # 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 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. # 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._ 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. # 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. # 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. 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. <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 [![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/js-base64@3.7.2/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/js-base64@3.7.2/base64.mjs'; </script> ``` ```html <script type="module"> // or if you prefer no Base64 namespace import { encode, decode } from 'https://cdn.jsdelivr.net/npm/js-base64@3.7.2/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) 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) <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 `ignore@2.x` 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* # 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._ # 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 }); } ``` # 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). # 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 ![](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) # 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;tj@vision-media.ca&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. # 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). # 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() } } ``` # 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. # 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). tunnel-agent ============ HTTP proxy tunneling agent. Formerly part of mikeal/request, now a standalone module. # 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) ## 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 ``` # 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) 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;nathan@tootallnate.net&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. 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) 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` <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: 'joe.bloggs@example.com' } ``` `$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 ajv.validator@gmail.com - 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) 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) # <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 <hdegoede@redhat.com> - Xiaofan Chen <xiaofanc@gmail.com> - Ludovic Rousseau <ludovic.rousseau@gmail.com> - Nathan Hjelm <hjelmn@cs.unm.edu> - Chris Dickens <christopher.a.dickens@gmail.com> (Please use the mailing list rather than mailing developers directly) # 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_ # 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. # 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. # 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. 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 (olalonde@gmail.com) - James Talmage (james@talmage.io) - [Ruben Verborgh](https://ruben.verborgh.org/) ## License [https://github.com/follow-redirects/follow-redirects/blob/master/LICENSE](MIT License) # 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;calvin.metcalf@gmail.com&gt; - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 * **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) &lt;mathiasbuus@gmail.com&gt; * **Matteo Collina** ([@mcollina](https://github.com/mcollina)) &lt;matteo.collina@gmail.com&gt; - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E * **Irina Shestak** ([@lrlna](https://github.com/lrlna)) &lt;shestak.irina@gmail.com&gt; * **Yoshua Wyuts** ([@yoshuawuyts](https://github.com/yoshuawuyts)) &lt;yoshuawuyts@gmail.com&gt; [sauce]: https://saucelabs.com # 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._ 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**. 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. # 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). 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. 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 # 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. # <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/ 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) # 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. # 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.) [![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). 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 # 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 # 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.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. Shims used when bundling asc for browser usage. 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://img.shields.io/github/workflow/status/dcodeIO/long.js/Test/main?label=test&logo=github)](https://github.com/dcodeIO/long.js/actions?query=workflow%3ATest) [![Publish Status](https://img.shields.io/github/workflow/status/dcodeIO/long.js/Publish/main?label=publish&logo=github)](https://github.com/dcodeIO/long.js/actions?query=workflow%3APublish) [![npm](https://img.shields.io/npm/v/long.svg?label=npm&color=007acc&logo=npm)](https://www.npmjs.com/package/long) 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 package exports an ECMAScript module with an UMD fallback. ``` $> npm install long ``` ```js import Long from "long"; var value = new Long(0xFFFFFFFF, 0x7FFFFFFF); console.log(value.toString()); ... ``` Note that mixing ESM and CommonJS is not recommended as it yields different classes, albeit with the same functionality. ### Usage with a CDN * From GitHub via [jsDelivr](https://www.jsdelivr.com):<br /> `https://cdn.jsdelivr.net/gh/dcodeIO/long.js@TAG/index.js` (ESM) * From npm via [jsDelivr](https://www.jsdelivr.com):<br /> `https://cdn.jsdelivr.net/npm/long@VERSION/index.js` (ESM)<br /> `https://cdn.jsdelivr.net/npm/long@VERSION/umd/index.js` (UMD) * From npm via [unpkg](https://unpkg.com):<br /> `https://unpkg.com/long@VERSION/index.js` (ESM)<br /> `https://unpkg.com/long@VERSION/umd/index.js` (UMD) Replace `TAG` respectively `VERSION` with a [specific version](https://github.com/dcodeIO/long.js/releases) or omit it (not recommended in production) to use main/latest. 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 or zero. * 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#**countLeadingZeros**/**clz**(): `number`<br /> Returns count leading zeros of this Long. * Long#**countTrailingZeros**/**ctz**(): `number`<br /> Returns count trailing zeros 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#**rotateLeft**/**rotl**(numBits: `Long | number | string`): `Long`<br /> Returns this Long with bits rotated to the left by the given amount. * Long#**rotateRight**/**rotr**(numBits: `Long | number | string`): `Long`<br /> Returns this Long with bits rotated 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. WebAssembly support ------------------- [WebAssembly](http://webassembly.org) supports 64-bit integer arithmetic out of the box, hence a [tiny WebAssembly module](./wasm.wat) is used to compute operations like multiplication, division and remainder more efficiently (slow operations like division are around twice as fast), falling back to floating point based computations in JavaScript where WebAssembly is not yet supported, e.g., in older versions of node. Building -------- Building the UMD fallback: ``` $> npm run build ``` Running the [tests](./tests): ``` $> npm test ``` # AssemblyScript Starter Esta es una plantilla que puedes usar como punto de inicio para tu proyecto. ## Contenido Este repositorio contiene un contrato inteligente con los siguientes métodos: ### Escritura: * `setParticipante` * `setCertificado` ### Lectura: * `getParticipante` * `getParticipantes` El contrato se encuentra previamente desplegado en la cuenta `as.ncdsamples.testnet`. Puedes hacer llamadas al mismo de la siguiente manera: ```sh near view as.ncdsamples.testnet getParticipantes ``` ## Uso ### Compilando y desplegando Lo primero que debemos hacer es instalar las dependencias necesarias para que el proyecto funcione. ```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 `AssemblyScript/build/release/`. Ahora solo es necesario desplegarlo en una cuenta de desarrollo. ```sh near dev-deploy build/release/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 `AssemblyScript/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 ``` ### Métodos Lo primero que debemos hacer es registrar al menos un usuario en el contrato. Para esto utilizamos el método `setParticipante`. Este método requiere que se pague 1 NEAR para poder ser ejecutado. El método registra a la persona que lo está ejecutando como participante. ```sh near call $CONTRATO setParticipante '{"nombre":"Nombre Participante","edad":18}' --accountId tucuenta.testnet --amount 1 ``` Ahora que tenemos al menos 1 participante, podemos utilizar los métodos de lectura. `getParticipante` nos traerá la información específica de un participante dependiendo la cuenta que le enviemos como parámetro. Por otro lado, `getParticipantes` nos trae la lista de todos los participantes registrados. ```sh near view $CONTRATO getParticipante '{"cuenta":"cuenta.testnet"}' ``` ```sh near view $CONTRATO getParticipantes ``` Por último, si queremos marcar como certificado a uno de los participantes registrados, podemos hacer uso del método `setCertificado`. Este método tiene una restricción en la que, si tu cuenta no es `aklassen.testnet` especificamente no te permitirá ejecutarlo. Esta es una forma de agregar una restricción a cuentas específicas. Puedes modificar esta cuenta en el código del contrato. Además, el método transfiere una compensación de 5 NEAR al participante por haber logrado su certificación. ```sh near call $CONTRATO setCertificado '{"cuenta":"cuenta.testnet"}' --accountId cuenta.testnet ``` 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. # 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. # 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] } ``` # 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) # 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"`. # 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. # 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). # 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 # 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 # 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). # 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) ``` 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')` # 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) # 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/become_a_patron_button@2x.png" 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._ # 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`. 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 }); }); ... ``` # 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._ 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. # 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 # 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:pass@example.com: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:alpha@example.com,bravo@example.com?subject=SUBSCRIBE&body=Sign%20me%20up!"); //returns: //{ // scheme : "mailto", // to : ["alpha@example.com", "bravo@example.com"], // subject : "SUBSCRIBE", // body : "Sign me up!" //} URI.serialize({ scheme : "mailto", to : ["alpha@example.com"], subject : "REMOVE", body : "Please remove me", headers : { cc : "charlie@example.com" } }) === "mailto:alpha@example.com?cc=charlie@example.com&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. # 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) 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 # 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. # 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 ### 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. # 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 # 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 # 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`. # 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 <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 # 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) # 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. # 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 # 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. # 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 # 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;julian@juliangruber.com&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. Shims used when bundling asc for browser usage. # 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. # 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. 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. <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'); ``` <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> # 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 # <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/ [![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) # <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/ # 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). ## 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). agent-base ========== ### Turn a function into an [`http.Agent`][http.Agent] instance [![Build Status](https://github.com/TooTallNate/node-agent-base/workflows/Node%20CI/badge.svg)](https://github.com/TooTallNate/node-agent-base/actions?workflow=Node+CI) This module provides an `http.Agent` generator. That is, you pass it an async callback function, and it returns a new `http.Agent` instance that will invoke the given callback function when sending outbound HTTP requests. #### Some subclasses: Here's some more interesting uses of `agent-base`. Send a pull request to list yours! * [`http-proxy-agent`][http-proxy-agent]: An HTTP(s) proxy `http.Agent` implementation for HTTP endpoints * [`https-proxy-agent`][https-proxy-agent]: An HTTP(s) proxy `http.Agent` implementation for HTTPS endpoints * [`pac-proxy-agent`][pac-proxy-agent]: A PAC file proxy `http.Agent` implementation for HTTP and HTTPS * [`socks-proxy-agent`][socks-proxy-agent]: A SOCKS proxy `http.Agent` implementation for HTTP and HTTPS Installation ------------ Install with `npm`: ``` bash $ npm install agent-base ``` Example ------- Here's a minimal example that creates a new `net.Socket` connection to the server for every HTTP request (i.e. the equivalent of `agent: false` option): ```js var net = require('net'); var tls = require('tls'); var url = require('url'); var http = require('http'); var agent = require('agent-base'); var endpoint = 'http://nodejs.org/api/'; var parsed = url.parse(endpoint); // This is the important part! parsed.agent = agent(function (req, opts) { var socket; // `secureEndpoint` is true when using the https module if (opts.secureEndpoint) { socket = tls.connect(opts); } else { socket = net.connect(opts); } return socket; }); // Everything else works just like normal... http.get(parsed, function (res) { console.log('"response" event!', res.headers); res.pipe(process.stdout); }); ``` Returning a Promise or using an `async` function is also supported: ```js agent(async function (req, opts) { await sleep(1000); // etc… }); ``` Return another `http.Agent` instance to "pass through" the responsibility for that HTTP request to that agent: ```js agent(function (req, opts) { return opts.secureEndpoint ? https.globalAgent : http.globalAgent; }); ``` API --- ## Agent(Function callback[, Object options]) → [http.Agent][] Creates a base `http.Agent` that will execute the callback function `callback` for every HTTP request that it is used as the `agent` for. The callback function is responsible for creating a `stream.Duplex` instance of some kind that will be used as the underlying socket in the HTTP request. The `options` object accepts the following properties: * `timeout` - Number - Timeout for the `callback()` function in milliseconds. Defaults to Infinity (optional). The callback function should have the following signature: ### callback(http.ClientRequest req, Object options, Function cb) → undefined The ClientRequest `req` can be accessed to read request headers and and the path, etc. The `options` object contains the options passed to the `http.request()`/`https.request()` function call, and is formatted to be directly passed to `net.connect()`/`tls.connect()`, or however else you want a Socket to be created. Pass the created socket to the callback function `cb` once created, and the HTTP request will continue to proceed. If the `https` module is used to invoke the HTTP request, then the `secureEndpoint` property on `options` _will be set to `true`_. License ------- (The MIT License) Copyright (c) 2013 Nathan Rajlich &lt;nathan@tootallnate.net&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. [http-proxy-agent]: https://github.com/TooTallNate/node-http-proxy-agent [https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent [pac-proxy-agent]: https://github.com/TooTallNate/node-pac-proxy-agent [socks-proxy-agent]: https://github.com/TooTallNate/node-socks-proxy-agent [http.Agent]: https://nodejs.org/api/http.html#http_class_http_agent # 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) 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.
khanhhuy-bkdn_even-odd-rust
Cargo.toml build.sh flags.sh src lib.rs test.sh tests sim first_tests.rs main.rs utils.rs
jasperdg_near-collection-behaviour
Cargo.toml scripts build.sh create_account.sh delete.sh deploy.sh test.sh src lib.rs
K-dizzled_lab1-k-dizzled-sokoban-rust
Cargo.toml build.sh neardev dev-account.env rust_near_sokoban Cargo.toml src auxiliary.rs board.rs lib.rs sb_token Cargo.toml src lib.rs
HoBocPhat_voting_app
contract Cargo.toml README.md build.js src lib.rs package.json src assets gray_near_logo.svg near.svg config.js index.html main.js wallet login index.html
# Voting App Allow voting upon a specific item on NEAR. ## Testing To test run: ```bash cargo test --package voting-app -- --nocapture ```
near-mezze_NCD--reading-library
README.md as-pect.config.js asconfig.json package-lock.json package.json scripts 1.dev-deploy.sh 2.use-contract.sh 3.cleanup.sh README.md src as_types.d.ts library __test__ as-pect.d.ts index.unit.spec.ts asconfig.json assembly index.ts models.ts tsconfig.json utils.ts
📑 Exploring the NEAR library smart contract methods ================== The following commands allow you to interact with the smart contract methods using the NEAR CLI (for this you need to have a provisional smart contract deployed). Information: the command for rate will require especific data (AccountId, Rate) Rate values: - The value 0 represents a bad rate. - The value 1 represents a regular rate. - The value 2 represents a awesome rate. Read the documents in order: -`dev-deploy.sh` -`use-contract.sh` # `NEAR Library` Starter Kit 📄 Introduction ================== NEAR Library is a smart contract where you can to create, rate, comment, store and transfer books using the NEAR protocol, making a library online where you can request one book and change the owner. The following are the main functionalities of this smart contract: 1. Add a Book to the library. 2. Get all the list of Books. 3. Get only the books that you added. 4. Rate a book. 5. Add a comment where you describe why do you liked... or not. 6. Transfer the book to another Owner. 📦 Installation ================ To run this project locally you need to follow the next steps: Step 1: Prerequisites ------------------------------ 1. Make sure you've installed [Node.js] ≥ 12 (we recommend use [nvm]) 2. Make sure you've installed yarn: `npm install -g yarn` 3. Install dependencies: `yarn install` 4. Create a test near account [NEAR test account] 5. Install the NEAR CLI globally: [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain yarn install --global near-cli Step 2: Configure your NEAR CLI ------------------------------- Configure your near-cli to authorize your test account recently created: near login Step 3: Build and make a smart contract development deploy -------------------------------- Build the NEAR library smart contract code and deploy the local development server: `yarn build:release` (see `package.json` for a full list of `scripts` you can run with `yarn`). This script return to you a provisional smart contract deployed (save it to use later). You can also follow the instructions on the folder *scripts*. 📑 Exploring the NEAR library smart contract methods ================== The following commands allow you to interact with the smart contract methods using the NEAR CLI (for this you need to have a provisional smart contract deployed). Information: the command for rate will require especific data (AccountId, Rate) Rate values: - The value 0 represents a bad rate. - The value 1 represents a regular rate. - The value 2 represents a awesome rate. Command to add a book: -------------------------------------------- ```bash near call $CONTRACT AddBook '{"isbn": "string","name":"string","description":"string","numpage":"number","author":"string","datepublished":"date","editions":"number"}' --account-id <your test account> ``` Command to get all the books on the library: -------------------------------------------- ```bash near view $CONTRACT getBooks ``` Command to get a specific book in the library: -------------------------------------------- ```bash near view $CONTRACT getBook '{"id":int}' ``` Command to get the number of Books added: -------------------------------------------- ```bash near view <your deployed contract> getNBooks ``` **Thing that we can add in the future** Command to rate a book: -------------------------------------------- ```bash near call $CONTRACT rate '{"id":3,"valor":2}' --accountId joehank.testnet ``` Command to see the rates of a book: -------------------------------------------- ```bash near call $CONTRACT rate '{"id":3}' --accountId joehank.testnet ``` Command to comment a book: -------------------------------------------- ```bash near call $CONTRACT comment '{"id":3,"comment":"i love it"}' --accountId joehank.testnet ``` Command to see the rates of a book: -------------------------------------------- ```bash near call $CONTRACT getComments '{"id":3}' --accountId joehank.testnet ``` WireFraming ================ ```bash https://www.figma.com/file/I7oewIevwZP5LAAsPOUel0/Untitled?node-id=7%3A49 ```
near-everything_gigs-board
.vscode settings.json NOTES.txt README.md firebase.json package.json public index.html manifest.json robots.txt src App.css hooks useTypedNavigator.ts index.css logo.svg react-app-env.d.ts routes NavigationProps.ts services addCard.ts deleteCard.ts getCards.ts moveCardAcrossLanes.ts setupProxy.js utils truncate.ts tsconfig.json
# Gigs Board Just a simple react app with [react-trello](https://github.com/rcdexta/react-trello), served from the [Gig.Board Widget](https://near.org/near/widget/ComponentDetailsPage?src=efiz.near/widget/Gigs.Board), hooked up via [near-social-bridge](https://github.com/wpdas/near-social-bridge); ```json "scripts": { "dev": "pnpm start", "start": "react-scripts start", "build": "react-scripts build && cp -rf build /build && rm -rf build", "test": "react-scripts test", "eject": "react-scripts eject" }, ``` ## Development * Make changes here * Build and deploy or use [ngrok](https://ngrok.com/)
lunafromthemoon_almostThere
.cache 01 52781c4b348f711d27b03d2292bcd9.json 9dc95d0576f2bd87633c777953be1b.json 9e133f0b6efb58d1119d6741ecc338.json 02 972b2e56e14bedb928b0e2102dd45b.json 04 7bd5fb3115f10649d6a476076c8b61.json 07 e97d301dc9c94c56ca437e8a2ab9c3.json 09 948310eece710523372998da46a103.json 0a a13c1c5b61824905f64485c299fc3a.json d3effc1a141b8350ce60c8ca5c7b10.json 10 afaa4b4de8e931e8d1dd355b36f3ed.json 11 a40d58d3ff0d8744b535e198cf4f8d.json 12 9a9a1f1f7642deb0c75e069a668f99.json b3c605760a5cc072fec68ced749962.json 13 1dde0d308340a4d3d75c217c3f0bee.json ca59bbc37445193c1e9b3322e8a3ca.json 15 0ae62a3a0f0f039e1f7324da455a6f.json 16 32c7879a5ed71c95f5cfa6ee33ad0c.json ebb63e65092a293de6f2f8e98e8628.json 18 33309c0cd2f46c0f7fbe7a48225831.json 1d a2755f0531de2e62fe72110ce87984.json 20 040c2153861e71b4c8c9f31c6bf498.json 21 2ffc54bcf7e8ede6d36d303bad71e6.json 22 407c756f21f8632ee6cb8123f69ac2.json 26 c63f005c3737a39ca4d83214a69022.json 29 56a24fe574bf3c276c65a68f98336c.json 8ec99765e8279248c3876fe419a15e.json 2c 8b91a36c7faf05dfc32e9a51b38d98.json 2d 5ecc551d30df35142547f3b18b1764.json 30 36f1380a6d70118d89ab57de5bb494.json 31 610a67f54ef2b3b2314bef0e66fb88.json 33 2ea843b5cc898bdd3ad6ba197bdf98.json 34 e5efee32577785496d28d069eb7e62.json 35 9c11a8262529bbca38fcc4a08ac1cd.json 9f7a7b75af317100bafbbdd431eca4.json f7faf87437d7977c5b929634b7daf3.json 36 b0247687fa7c1f65c95d9ab9f3c4fb.json 37 e6722d827d06efa87a3e71d74d4841.json 3d 74ddd57fa00270b39cfbdb593a3d98.json 40 a5e3c51bc10e7774f3ea627e1e716d.json 41 d72b4123fb0347ee01098553bbd179.json 42 95680fbbc2576adff9b7a345bd9b12.json 43 47ab111adfb937fff32c26bf001886.json 45 5fdbffe9c3c3da988f33dc3705df8f.json 8f285a525ee491822797cc1ccf1145.json da346c84e1fa0fcb3107ef1e8e2ee6.json 47 61405e27fc90df548db0ff413c3dcf.json 48 f6bf4ebd9986579cafb0a1bdb10c1b.json 4a fb09466c36b62363b136c2c8382de8.json 4b c78f239d0304cb801492aedc3e407a.json f208e90d351b48473ae3010699f5b2.json 4d b8344604591208222753a74d581f4d.json 4f 87a83479050b5ec0a5324832c57b7c.json 50 1a2ae21898c435cd31a6267992b7a7.json 2da5a72b5f3cb206f70e1a3e4f85be.json 51 41bc9941beff139dbe3f68c752041a.json 52 4b8b8dd2312727d0254d62182cb69a.json 55 70399cb2f629c05ae49a47a8c22d94.json 57 0a8bdc991f04d95023d4a443ec36b5.json 868cbc3436681edb39bc5f0384e18d.json 58 f291a8c73345b24b6b250dbdb863d8.json 5a 5fd2f84b72319b2ca3aa7e4c3ccbac.json f5d066c0b16f833d6ab358ebaa5efa.json 5b a45459bb9a013283e292de8e8f2112.json 5e f095e8250705605941e6283f858584.json 5f a70a9172c554d5e18f8673c82250b3.json 65 1cd79e4c516846e86f7f12f299c3b1.json 67 7213f500e64fba147917b9a33a6bd5.json 68 ba52d8735306ae4c00d4a439a6d6a2.json 6d 6e06b44555b4b6644f69526d5242e9.json 6f a2e09cbfa99a386f823379df2bbedd.json dadb72745176b70c6a95200a3801f7.json 70 f61e17443f442e906027100dac23fd.json 73 61507f8fcdabfd913dac59dc12cc18.json 75 69453fadfdbffa8ac180681b827bca.json 76 8113442f4faac4046fada423e24c78.json 7b c0e12694c0c026bcde17b75bbac501.json 7c 7c0036033c9b808ad4c115970cb8f9.json 7f 52f4cd6c49520d8b21463eba3f13b7.json 80 22f4dd8f7f73ee539768bb99384037.json 83 016ec5a25a25ee5be5f9d0ddfd7cf2.json 84 677133b8a04691ecceab2a013c85f6.json eb3600dc61d7a1f1028e0ddb936d27.json 87 05ad2f0a3f3f225bb002b1b55bea6a.json 88 e8a504716a712bffb7e05bd0d80af7.json edf3cb4c0122731d29c01815670021.json 8a e2fadec2dcfbb3897531955bad2038.json 8c 8d20023216ccfff6883101a509458a.json 8f 66500676850565cb01f9e6e613a6f0.json ce68e2c2904a1a660657698c840d83.json 90 a410e28748b0c708adafeee00ec363.json 91 426b0f2672af147663ba3487f5d3ed.json 93 cb88ff1827a6f999dde1c159e63865.json 95 33e6a185e4afd8013d3d7ada057f79.json 96 b547ced5914b086068ad776670d9cc.json 97 76845f690c0e7abdf3731d4b43688f.json c26ed28e62afcae81a3cb81a100fbf.json 9c b8d4d0ebd34044b0f1f3dec06f4126.json 9e aaa8a33253f10429be63968df9551e.json 9f 0b4910bcc392b59a26ce2da076c268.json a0 4e2168eb4c1cdceca7c21b300b79ab.json a5 3174353b72608f1d33387dd2efb5fc.json a6 7458c1059ab1e01809272d539cb0ab.json b0 6180ce5c2de2e2a07f1e4823168a0c.json b4 c3f7e95012292fc3e38b23a2443c09.json b9 649734b5839f8c57add65a4697bcea.json ba 68ee98a627ee5e939871de48549540.json bc 5f1297b8505ee11b0dc3d417b9aeb1.json bd a605c73da9b1825b4517671350118c.json be d3271354e20753f1daa57e55f3ba98.json c1 160e8bf5a8bebaa3b0ac721a0cf898.json c9 417c98037e8515576ecad3cdbb0646.json d1 02cf64efd5556f8834d86440250307.json dfca44363999ccd7904fbf20ffd2cd.json d3 38c1d0689ad52f47f7e647baeefe95.json d5 ded0e7a98a2927b7bbb3cf13aaa271.json d6 e8c42b5bd7ac1b621ddcf7d8a12fb8.json d8 b457969df618020846a2b7f5d0a490.json df 2a53b60ecc02ab4872f33d774402c0.json e1 a65ab9feabe79ce16f5b7ea0b1314e.json a69d7adf82e73817cd1834367cf728.json e3 d5a135845b159bdeaacf1fb266e09e.json e5 f10aebbfa2280e691960f20fd56cc2.json e6 f65509acbf921d749ed7bea75daa32.json e7 d6b2c5e577cf1cbc4ace625682eec2.json f2 1632d3762d7168b80e2c3a0c9d6bc5.json f3 620a72114144b1b2db0779e75a34c9.json fa d742b874aded387cd6df256a38b751.json fc 1cb5199c74182c31043c84ac2b8b46.json 887a1a464a22554d5ee55df41cb79c.json 969888902ddd5084c894751ba55ad7.json ff f094f4c5d7967ae4b3e5c5f50efaea.json README.md as-pect.config.js asconfig.json assembly as_types.d.ts main.ts model.ts tsconfig.json neardev dev-account.env node_modules .bin sha.js @as-pect assembly README.md assembly index.ts internal Actual.ts Expectation.ts Expected.ts RTrace.ts Reflect.ts ReflectedValueType.ts Test.ts assert.ts call.ts comparison toIncludeComparison.ts toIncludeEqualComparison.ts log.ts noOp.ts runtime.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 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 @babel code-frame README.md lib index.js package.json compat-data 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 node_modules semver CHANGELOG.md README.md package.json semver.js overlapping-plugins.js package.json plugin-bugfixes.js plugins.js core README.md lib config caching.js config-chain.js config-descriptors.js files configuration.js import.js index-browser.js index.js module-types.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 printer.js util.js validation option-assertions.js options.js plugins.js removed.js gensync-utils async.js fs.js resolve.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 node_modules semver CHANGELOG.md README.md package.json semver.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 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 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.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-experimental lib index.js package.json src index.js helper-builder-react-jsx README.md lib index.js package.json helper-compilation-targets lib debug.js filter-items.js index.js options.js pretty.js targets.js types.js utils.js node_modules semver CHANGELOG.md README.md 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-create-regexp-features-plugin README.md lib features.js index.js util.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 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-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-skip-transparent-expression-wrappers README.md lib index.js package.json helper-split-export-declaration 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-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 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 plugin-proposal-async-generator-functions README.md lib for-await.js index.js package.json plugin-proposal-class-properties README.md lib index.js package.json plugin-proposal-dynamic-import README.md lib index.js package.json plugin-proposal-export-namespace-from README.md lib index.js package.json plugin-proposal-json-strings README.md lib index.js package.json plugin-proposal-logical-assignment-operators README.md lib index.js package.json plugin-proposal-nullish-coalescing-operator README.md lib index.js package.json plugin-proposal-numeric-separator 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-optional-chaining README.md lib index.js package.json plugin-proposal-private-methods README.md lib index.js package.json plugin-proposal-unicode-property-regex README.md lib index.js package.json plugin-syntax-async-generators README.md lib index.js package.json plugin-syntax-bigint README.md lib index.js package.json plugin-syntax-class-properties README.md lib index.js package.json plugin-syntax-dynamic-import README.md lib index.js package.json plugin-syntax-export-namespace-from README.md lib index.js package.json plugin-syntax-flow README.md lib index.js package.json plugin-syntax-import-meta 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-logical-assignment-operators README.md lib index.js package.json plugin-syntax-nullish-coalescing-operator README.md lib index.js package.json plugin-syntax-numeric-separator 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-syntax-optional-chaining README.md lib index.js package.json plugin-syntax-top-level-await 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 inline-createSuper-helpers.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 plugin-transform-duplicate-keys README.md lib index.js package.json plugin-transform-exponentiation-operator README.md lib index.js package.json plugin-transform-flow-strip-types README.md lib index.js package.json plugin-transform-for-of README.md lib index.js no-helper-implementation.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-jsx README.md lib index.js transform-automatic.js transform-classic.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-escapes README.md lib index.js package.json plugin-transform-unicode-regex README.md lib index.js package.json preset-env README.md data built-in-modules.js built-in-modules.json.js built-ins.js built-ins.json.js corejs2-built-ins.js corejs2-built-ins.json.js plugins.js plugins.json.js 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 plugins-compat-data.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 usage-plugin.js regenerator entry-plugin.js usage-plugin.js targets-parser.js utils.js node_modules semver CHANGELOG.md README.md package.json semver.js package.json preset-modules README.md lib index.js plugins transform-async-arrows-in-class index.js transform-edge-default-parameters index.js transform-edge-function-name index.js transform-jsx-spread index.js transform-safari-block-shadowing index.js transform-safari-for-shadowing index.js transform-tagged-template-caching index.js package.json src index.js plugins transform-async-arrows-in-class index.js transform-edge-default-parameters index.js transform-edge-function-name index.js transform-jsx-spread index.js transform-safari-block-shadowing index.js transform-safari-for-shadowing index.js transform-tagged-template-caching index.js runtime README.md helpers AsyncGenerator.js AwaitValue.js applyDecoratedDescriptor.js arrayLikeToArray.js arrayWithHoles.js arrayWithoutHoles.js assertThisInitialized.js asyncGeneratorDelegate.js asyncIterator.js asyncToGenerator.js awaitAsyncGenerator.js classCallCheck.js classNameTDZError.js classPrivateFieldDestructureSet.js classPrivateFieldGet.js classPrivateFieldLooseBase.js classPrivateFieldLooseKey.js classPrivateFieldSet.js classPrivateMethodGet.js classPrivateMethodSet.js classStaticPrivateFieldSpecGet.js classStaticPrivateFieldSpecSet.js classStaticPrivateMethodGet.js classStaticPrivateMethodSet.js construct.js createClass.js createForOfIteratorHelper.js createForOfIteratorHelperLoose.js createSuper.js decorate.js defaults.js defineEnumerableProperties.js defineProperty.js esm AsyncGenerator.js AwaitValue.js applyDecoratedDescriptor.js arrayLikeToArray.js arrayWithHoles.js arrayWithoutHoles.js assertThisInitialized.js asyncGeneratorDelegate.js asyncIterator.js asyncToGenerator.js awaitAsyncGenerator.js classCallCheck.js classNameTDZError.js classPrivateFieldDestructureSet.js classPrivateFieldGet.js classPrivateFieldLooseBase.js classPrivateFieldLooseKey.js classPrivateFieldSet.js classPrivateMethodGet.js classPrivateMethodSet.js classStaticPrivateFieldSpecGet.js classStaticPrivateFieldSpecSet.js classStaticPrivateMethodGet.js classStaticPrivateMethodSet.js construct.js createClass.js createForOfIteratorHelper.js createForOfIteratorHelperLoose.js createSuper.js decorate.js defaults.js defineEnumerableProperties.js defineProperty.js extends.js get.js getPrototypeOf.js inherits.js inheritsLoose.js initializerDefineProperty.js initializerWarningHelper.js instanceof.js interopRequireDefault.js interopRequireWildcard.js isNativeFunction.js isNativeReflectConstruct.js iterableToArray.js iterableToArrayLimit.js iterableToArrayLimitLoose.js jsx.js maybeArrayLike.js newArrowCheck.js nonIterableRest.js nonIterableSpread.js objectDestructuringEmpty.js objectSpread.js objectSpread2.js objectWithoutProperties.js objectWithoutPropertiesLoose.js package.json possibleConstructorReturn.js readOnlyError.js set.js setPrototypeOf.js skipFirstGeneratorNext.js slicedToArray.js slicedToArrayLoose.js superPropBase.js taggedTemplateLiteral.js taggedTemplateLiteralLoose.js tdz.js temporalRef.js temporalUndefined.js toArray.js toConsumableArray.js toPrimitive.js toPropertyKey.js typeof.js unsupportedIterableToArray.js wrapAsyncGenerator.js wrapNativeSuper.js wrapRegExp.js extends.js get.js getPrototypeOf.js inherits.js inheritsLoose.js initializerDefineProperty.js initializerWarningHelper.js instanceof.js interopRequireDefault.js interopRequireWildcard.js isNativeFunction.js isNativeReflectConstruct.js iterableToArray.js iterableToArrayLimit.js iterableToArrayLimitLoose.js jsx.js maybeArrayLike.js newArrowCheck.js nonIterableRest.js nonIterableSpread.js objectDestructuringEmpty.js objectSpread.js objectSpread2.js objectWithoutProperties.js objectWithoutPropertiesLoose.js possibleConstructorReturn.js readOnlyError.js set.js setPrototypeOf.js skipFirstGeneratorNext.js slicedToArray.js slicedToArrayLoose.js superPropBase.js taggedTemplateLiteral.js taggedTemplateLiteralLoose.js tdz.js temporalRef.js temporalUndefined.js toArray.js toConsumableArray.js toPrimitive.js toPropertyKey.js typeof.js unsupportedIterableToArray.js wrapAsyncGenerator.js wrapNativeSuper.js wrapRegExp.js package.json regenerator index.js 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 package.json types README.md lib asserts assertNode.js generated index.js builders builder.js flow createFlowUnionType.js createTypeAnnotationBasedOnTypeof.js generated index.js react buildChildren.js typescript createTSUnionType.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.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 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 @bcoe v8-coverage CHANGELOG.md LICENSE.md LICENSE.txt README.md dist lib CHANGELOG.md LICENSE.md README.md _src ascii.ts clone.ts compare.ts index.ts merge.ts normalize.ts range-tree.ts types.ts ascii.d.ts ascii.js clone.d.ts clone.js compare.d.ts compare.js index.d.ts index.js merge.d.ts merge.js normalize.d.ts normalize.js package.json range-tree.d.ts range-tree.js tsconfig.json types.d.ts types.js gulpfile.ts package.json src lib ascii.ts clone.ts compare.ts index.ts merge.ts normalize.ts range-tree.ts types.ts test merge.spec.ts tsconfig.json @cnakazawa watch README.md cli.js main.js package.json scripts release.sh @iarna toml CHANGELOG.md README.md index.d.ts lib create-date.js create-datetime-float.js create-datetime.js create-time.js format-num.js parser-debug.js parser.js toml-parser.js package.json parse-async.js parse-pretty-error.js parse-stream.js parse-string.js parse.js stringify.js toml.js @istanbuljs load-nyc-config CHANGELOG.md README.md index.js load-esm.js package.json schema CHANGELOG.md README.md default-exclude.js index.js package.json @jest console build BufferedConsole.d.ts BufferedConsole.js CustomConsole.d.ts CustomConsole.js NullConsole.d.ts NullConsole.js getConsoleOutput.d.ts getConsoleOutput.js index.d.ts index.js types.d.ts types.js package.json core README.md build FailedTestsCache.d.ts FailedTestsCache.js ReporterDispatcher.d.ts ReporterDispatcher.js SearchSource.d.ts SearchSource.js SnapshotInteractiveMode.d.ts SnapshotInteractiveMode.js TestNamePatternPrompt.d.ts TestNamePatternPrompt.js TestPathPatternPrompt.d.ts TestPathPatternPrompt.js TestScheduler.d.ts TestScheduler.js TestWatcher.d.ts TestWatcher.js cli index.d.ts index.js collectHandles.d.ts collectHandles.js getChangedFilesPromise.d.ts getChangedFilesPromise.js getConfigsOfProjectsToRun.d.ts getConfigsOfProjectsToRun.js getNoTestFound.d.ts getNoTestFound.js getNoTestFoundFailed.d.ts getNoTestFoundFailed.js getNoTestFoundPassWithNoTests.d.ts getNoTestFoundPassWithNoTests.js getNoTestFoundRelatedToChangedFiles.d.ts getNoTestFoundRelatedToChangedFiles.js getNoTestFoundVerbose.d.ts getNoTestFoundVerbose.js getNoTestsFoundMessage.d.ts getNoTestsFoundMessage.js getProjectDisplayName.d.ts getProjectDisplayName.js getProjectNamesMissingWarning.d.ts getProjectNamesMissingWarning.js getSelectProjectsMessage.d.ts getSelectProjectsMessage.js jest.d.ts jest.js lib active_filters_message.d.ts active_filters_message.js create_context.d.ts create_context.js handle_deprecation_warnings.d.ts handle_deprecation_warnings.js is_valid_path.d.ts is_valid_path.js log_debug_messages.d.ts log_debug_messages.js update_global_config.d.ts update_global_config.js watch_plugins_helpers.d.ts watch_plugins_helpers.js plugins quit.d.ts quit.js test_name_pattern.d.ts test_name_pattern.js test_path_pattern.d.ts test_path_pattern.js update_snapshots.d.ts update_snapshots.js update_snapshots_interactive.d.ts update_snapshots_interactive.js pluralize.d.ts pluralize.js runGlobalHook.d.ts runGlobalHook.js runJest.d.ts runJest.js testSchedulerHelper.d.ts testSchedulerHelper.js types.d.ts types.js version.d.ts version.js watch.d.ts watch.js package.json 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 globals build index.d.ts index.js package.json reporters build Status.d.ts Status.js base_reporter.d.ts base_reporter.js coverage_reporter.d.ts coverage_reporter.js coverage_worker.d.ts coverage_worker.js default_reporter.d.ts default_reporter.js generateEmptyCoverage.d.ts generateEmptyCoverage.js get_result_header.d.ts get_result_header.js get_snapshot_status.d.ts get_snapshot_status.js get_snapshot_summary.d.ts get_snapshot_summary.js get_watermarks.d.ts get_watermarks.js index.d.ts index.js notify_reporter.d.ts notify_reporter.js summary_reporter.d.ts summary_reporter.js types.d.ts types.js utils.d.ts utils.js verbose_reporter.d.ts verbose_reporter.js package.json source-map build getCallsite.d.ts getCallsite.js index.d.ts index.js types.d.ts types.js package.json test-result build formatTestResults.d.ts formatTestResults.js helpers.d.ts helpers.js index.d.ts index.js types.d.ts types.js package.json test-sequencer build index.d.ts index.js package.json transform build ScriptTransformer.d.ts ScriptTransformer.js enhanceUnexpectedTokenMessage.d.ts enhanceUnexpectedTokenMessage.js index.d.ts index.js shouldInstrument.d.ts shouldInstrument.js types.d.ts types.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 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-node-hid-noevents README.md lib-es TransportNodeHid.js lib TransportNodeHid.js package.json src TransportNodeHid.js hw-transport-node-hid README.md cli-test.js lib-es TransportNodeHid.js listenDevices.js lib TransportNodeHid.js listenDevices.js package.json src TransportNodeHid.js listenDevices.js 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 @mrmlnc readdir-enhanced CHANGELOG.md README.md lib async for-each.js index.js call.js directory-reader.js index.js normalize-options.js stat.js stream index.js sync for-each.js fs.js index.js package.json types.d.ts @nodelib fs.stat README.md out adapters fs.d.ts fs.js index.d.ts index.js managers options.d.ts options.js providers stat.d.ts stat.js package.json @parcel fs index.js node_modules rimraf README.md bin.js package.json rimraf.js package.json src .eslintrc.json fs.js logger index.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 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 strip-ansi index.js package.json readme.md supports-color browser.js index.js package.json readme.md package.json src .eslintrc.json Logger.js emoji.js prettyError.js test .eslintrc.json logger.js prettyError.js utils index.js package.json src .eslintrc.json errorUtils.js promisify.js watcher index.js lib Watcher.js child.js options.js node_modules anymatch README.md index.js node_modules normalize-path README.md index.js package.json package.json binary-extensions binary-extensions.json package.json readme.md 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 chokidar CHANGELOG.md README.md index.js lib fsevents-handler.js nodefs-handler.js package.json types index.d.ts fill-range README.md index.js node_modules extend-shallow README.md index.js package.json package.json glob-parent README.md index.js node_modules is-glob README.md index.js package.json package.json is-binary-path index.js package.json readme.md is-number README.md index.js node_modules kind-of README.md index.js package.json package.json micromatch CHANGELOG.md README.md index.js lib cache.js compilers.js parsers.js utils.js package.json readdirp README.md package.json readdirp.js stream-api.js to-regex-range README.md index.js package.json package.json src Watcher.js child.js options.js test .eslintrc.json changeEvent.js errorHandling.js fswatcher.js options.js tmp config.json file1.txt watched.js workers index.js package.json src .eslintrc.json Worker.js WorkerFarm.js child.js cpuCount.js test .eslintrc.json integration workerfarm echo.js init.js ipc-pid.js ipc.js master-process-id.js master-sum.js ping.js workerfarm.js @sindresorhus is dist index.d.ts index.js package.json readme.md @sinonjs commons CHANGES.md 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.js function.js index.js index.test.js map.js object.js set.js string.js type-of.js type-of.test.js value-to-string.js value-to-string.test.js package.json fake-timers CHANGELOG.md README.md fake-timers.js package.json src fake-timers-src.js @szmarczak http-timer README.md package.json source index.js @types babel__core README.md index.d.ts package.json babel__generator README.md index.d.ts package.json babel__template README.md index.d.ts package.json babel__traverse README.md index.d.ts package.json bn.js README.md index.d.ts package.json color-name README.md index.d.ts package.json graceful-fs 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 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 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 repl.d.ts stream.d.ts string_decoder.d.ts timers.d.ts tls.d.ts trace_events.d.ts ts3.4 assert.d.ts base.d.ts globals.global.d.ts index.d.ts ts3.6 base.d.ts index.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 normalize-package-data README.md index.d.ts package.json prettier README.md index.d.ts package.json parser-angular.d.ts parser-babel.d.ts parser-flow.d.ts parser-graphql.d.ts parser-html.d.ts parser-markdown.d.ts parser-postcss.d.ts parser-typescript.d.ts parser-yaml.d.ts standalone.d.ts q 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 index.d.ts package.json yargs.d.ts abab CHANGELOG.md LICENSE.md README.md index.d.ts index.js lib atob.js btoa.js package.json abbrev README.md abbrev.js package.json acorn-globals README.md index.js 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 agent-base .travis.yml History.md README.md index.d.ts index.js package.json patch-core.js test test.js 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 alphanum-sort README.md lib compare.js index.js package.json ansi-align CHANGELOG.md README.md index.js node_modules ansi-regex 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.js package.json readme.md string-width index.js package.json readme.md strip-ansi index.d.ts index.js package.json readme.md package.json ansi-escapes index.d.ts index.js node_modules 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 tsconfig-json.d.ts 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 ansi-to-html LICENSE-MIT.txt README.md lib ansi_to_html.js cli.js package.json test ansi_to_html.js cli.js anymatch README.md index.d.ts index.js 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 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 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-equal README.md component.json index.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 as-bignum .travis.yml README.md as-pect.config.js assembly __tests__ as-pect.d.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 u128.ts u256.ts u64.ts u128.ts u256.ts tsconfig.json utils.ts index.js package.json tsconfig.json asbuild README.md dist cli.d.ts cli.js index.d.ts index.js main.d.ts main.js index.js package.json 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 asn1.js .eslintrc.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 node_modules bn.js README.md lib bn.js package.json util genCombMulTo.js genCombMulTo10.js package.json asn1 README.md lib ber errors.js index.js reader.js types.js writer.js index.js package.json assemblyscript-json .travis.yml README.md as-pect.config.js assembly JSON.ts __tests__ as-pect.d.ts roundtrip.spec.ts decoder.ts encoder.ts index.ts tsconfig.json util index.ts index.js package.json 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 rtrace README.md 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 dataview.ts date.ts diagnostics.ts error.ts function.ts gc.ts heap.ts index.d.ts iterator.ts map.ts math.ts memory.ts number.ts object.ts polyfills.ts reference.ts regexp.ts rt.ts rt README.md common.ts index-full.ts index-half.ts index-none.ts index-stub.ts index.d.ts pure.ts rtrace.ts stub.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 util casemap.ts error.ts hash.ts math.ts memory.ts number.ts sort.ts string.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 assert-plus CHANGES.md README.md assert.js package.json assert .travis.yml .zuul.yml CHANGELOG.md 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 README.md index.js package.json async-limiter .travis.yml index.js package.json readme.md async CHANGELOG.md README.md all.js allLimit.js allSeries.js any.js anyLimit.js anySeries.js apply.js applyEach.js applyEachSeries.js asyncify.js auto.js autoInject.js bower.json cargo.js compose.js concat.js concatLimit.js concatSeries.js constant.js detect.js detectLimit.js detectSeries.js dir.js dist async.js async.min.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 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 index.js inject.js internal DoublyLinkedList.js applyEach.js breakLoop.js consoleFunc.js createTester.js doLimit.js doParallel.js doParallelLimit.js eachOfLimit.js filter.js findGetResult.js getIterator.js initialParams.js iterator.js map.js notId.js once.js onlyOnce.js parallel.js queue.js reject.js setImmediate.js slice.js withoutIndex.js wrapAsync.js log.js map.js mapLimit.js mapSeries.js mapValues.js mapValuesLimit.js mapValuesSeries.js memoize.js nextTick.js package.json parallel.js parallelLimit.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 select.js selectLimit.js selectSeries.js seq.js series.js setImmediate.js some.js someLimit.js someSeries.js sortBy.js timeout.js times.js timesLimit.js timesSeries.js transform.js tryEach.js unmemoize.js until.js waterfall.js whilst.js wrapSync.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 aws-sign2 README.md index.js package.json aws4 .github FUNDING.yml .travis.yml README.md aws4.js lru.js package.json 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 babel-jest README.md build index.d.ts index.js loadBabelConfig.d.ts loadBabelConfig.js package.json babel-plugin-dynamic-import-node .travis.yml CHANGELOG.md README.md lib index.js utils.js package.json utils.js babel-plugin-istanbul CHANGELOG.md README.md lib index.js load-nyc-config-sync.js package.json babel-plugin-jest-hoist README.md build index.d.ts index.js package.json babel-preset-current-node-syntax README.md package.json src index.js babel-preset-jest README.md index.js package.json babel-runtime README.md core-js.js core-js array concat.js copy-within.js entries.js every.js fill.js filter.js find-index.js find.js for-each.js from.js includes.js index-of.js join.js keys.js last-index-of.js map.js of.js pop.js push.js reduce-right.js reduce.js reverse.js shift.js slice.js some.js sort.js splice.js unshift.js values.js asap.js clear-immediate.js error is-error.js get-iterator.js is-iterable.js json stringify.js map.js math acosh.js asinh.js atanh.js cbrt.js clz32.js cosh.js expm1.js fround.js hypot.js iaddh.js imul.js imulh.js isubh.js log10.js log1p.js log2.js sign.js sinh.js tanh.js trunc.js umulh.js number epsilon.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 object assign.js create.js define-properties.js define-property.js entries.js freeze.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 is-extensible.js is-frozen.js is-sealed.js is.js keys.js prevent-extensions.js seal.js set-prototype-of.js values.js observable.js promise.js reflect apply.js construct.js define-metadata.js define-property.js delete-metadata.js delete-property.js enumerate.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 is-extensible.js metadata.js own-keys.js prevent-extensions.js set-prototype-of.js set.js regexp escape.js set-immediate.js set.js string at.js code-point-at.js ends-with.js from-code-point.js includes.js match-all.js pad-end.js pad-left.js pad-right.js pad-start.js raw.js repeat.js starts-with.js trim-end.js trim-left.js trim-right.js trim-start.js trim.js symbol.js symbol async-iterator.js for.js has-instance.js is-concat-spreadable.js iterator.js key-for.js match.js observable.js replace.js search.js species.js split.js to-primitive.js to-string-tag.js unscopables.js system global.js weak-map.js weak-set.js helpers _async-generator-delegate.js _async-generator.js _async-iterator.js _async-to-generator.js _class-call-check.js _create-class.js _defaults.js _define-enumerable-properties.js _define-property.js _extends.js _get.js _inherits.js _instanceof.js _interop-require-default.js _interop-require-wildcard.js _jsx.js _new-arrow-check.js _object-destructuring-empty.js _object-without-properties.js _possible-constructor-return.js _self-global.js _set.js _sliced-to-array-loose.js _sliced-to-array.js _tagged-template-literal-loose.js _tagged-template-literal.js _temporal-ref.js _temporal-undefined.js _to-array.js _to-consumable-array.js _typeof.js async-generator-delegate.js async-generator.js async-iterator.js async-to-generator.js asyncGenerator.js asyncGeneratorDelegate.js asyncIterator.js asyncToGenerator.js class-call-check.js classCallCheck.js create-class.js createClass.js defaults.js define-enumerable-properties.js define-property.js defineEnumerableProperties.js defineProperty.js extends.js get.js inherits.js instanceof.js interop-require-default.js interop-require-wildcard.js interopRequireDefault.js interopRequireWildcard.js jsx.js new-arrow-check.js newArrowCheck.js object-destructuring-empty.js object-without-properties.js objectDestructuringEmpty.js objectWithoutProperties.js possible-constructor-return.js possibleConstructorReturn.js self-global.js selfGlobal.js set.js sliced-to-array-loose.js sliced-to-array.js slicedToArray.js slicedToArrayLoose.js tagged-template-literal-loose.js tagged-template-literal.js taggedTemplateLiteral.js taggedTemplateLiteralLoose.js temporal-ref.js temporal-undefined.js temporalRef.js temporalUndefined.js to-array.js to-consumable-array.js toArray.js toConsumableArray.js typeof.js node_modules regenerator-runtime README.md package.json path.js runtime-module.js runtime.js package-lock.json package.json regenerator index.js babel-types README.md lib constants.js converters.js definitions core.js es2015.js experimental.js flow.js index.js init.js jsx.js misc.js flow.js index.js react.js retrievers.js validators.js node_modules to-fast-properties index.js package.json readme.md package-lock.json package.json babylon-walk HISTORY.md LICENSE.md README.md lib explode.js index.js package.json src explode.js index.js balanced-match LICENSE.md README.md index.js package.json base-x LICENSE.md README.md package.json src index.d.ts index.js 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 bcrypt-pbkdf CONTRIBUTING.md README.md index.js node_modules 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 package.json binary-extensions binary-extensions.json binary-extensions.json.d.ts index.d.ts index.js package.json readme.md 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 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 .travis.yml README.md index.js package.json test index.js readme.js vectors.json wordlist.json util wordlists.js wordlists chinese_simplified.json chinese_traditional.json english.json french.json italian.json japanese.json spanish.json bl .travis.yml BufferList.js LICENSE.md README.md bl.js node_modules 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 package.json test convert.js indexOf.js isBufferList.js test.js bn.js CHANGELOG.md README.md lib bn.js package.json boolbase README.md index.js package.json boxen index.d.ts index.js node_modules chalk index.d.ts package.json readme.md source index.js templates.js util.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 brfs .travis.yml bin cmd.js usage.txt example async.js main.js robot.html index.js package.json test ag.js async.js buffer.js bundle.js cmd.js dynamic_read_concat.js dynamic_read_no_concat.js encoding.js files ag.js ag.json ag_post.html ag_pre.html async.js async.txt async_encoding.js async_str_encoding.js buffer.js dynamic_read_concat.js dynamic_read_no_concat.js encoding.js hoist.js inline.js main.js multi_var.js non_fs.js path_join.js path_join_other_name.js path_join_single_var.js readdir-sync.js readdir.js robot.html separators.js separators.txt tr.html with_comments.js hoist.js inline.js multi_var.js non_fs.js path_join.js path_join_other_name.js path_join_single_var.js readdir.js require_resolve.js require_resolve main.js node_modules aaa wow.txt separators.js tr.js with_comments.js brorand README.md index.js package.json test api-test.js browser-process-hrtime README.md index.d.ts index.js package.json 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 node_modules bn.js README.md lib bn.js package.json util genCombMulTo.js genCombMulTo10.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 node_modules 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 package.json browserify-zlib .travis.yml README.md karma.conf.js lib binding.js index.js node_modules 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 package.json src binding.js index.js browserslist CHANGELOG.md README.md browser.js cli.js error.js index.js node.js package.json update-db.js bs58 CHANGELOG.md README.md index.js package.json bser README.md index.js package.json buffer-equal .travis.yml example eq.js index.js package.json test eq.js buffer-from index.js package.json readme.md buffer-xor .travis.yml README.md index.js inline.js inplace.js package.json test fixtures.json index.js buffer AUTHORS.md README.md index.d.ts index.js package.json builtin-status-codes browser.js build.js index.js package.json readme.md cache-base README.md 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 normalize-url index.d.ts index.js package.json readme.md package.json src index.js call-me-maybe .travis.yml .zuul.yml README.md index.js package.json test maybeTest.js caller-callsite index.js node_modules callsites index.js package.json readme.md package.json readme.md caller-path index.js package.json readme.md callsites index.d.ts index.js package.json readme.md camelcase index.d.ts index.js package.json readme.md caniuse-api CHANGELOG.md README.md dist index.js utils.js package.json 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 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 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 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-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-color-function.js css-conic-gradients.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-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 date-tolocaledatestring.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 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 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 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 http3.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-v2.js intersectionobserver.js intl-pluralrules.js intrinsic-width.js jpeg2000.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 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 native-filesystem-api.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 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 private-class-fields.js private-methods-and-accessors.js progress.js promise-finally.js promises.js proximity.js proxy.js public-class-fields.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 replace-all.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 sxg.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 text-underline-offset.js textcontent.js textencoder.js tls1-1.js tls1-2.js tls1-3.js token-binding.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 vibration.js video.js videotracks.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-share.js webauthn.js webgl.js webgl2.js webgpu.js webhid.js webm.js webnfc.js webp.js websockets.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 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 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 capture-exit README.md index.js package.json caseless README.md index.js package.json test.js chalk index.d.ts package.json readme.md source index.js templates.js util.js char-regex README.md index.d.ts index.js package.json 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 ci-info CHANGELOG.md README.md index.js package.json vendors.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 cli-boxes boxes.json index.d.ts index.js package.json readme.md cli-cursor index.js package.json readme.md cli-spinners index.js package.json readme.md spinners.json cliui CHANGELOG.md LICENSE.txt README.md index.js package.json clone-response README.md node_modules mimic-response index.js package.json readme.md package.json src index.js clone README.md clone.js package.json co History.md Readme.md index.js package.json coa README.md README.ru.md coa.d.ts index.js lib arg.js cmd.js coaobject.js coaparam.js completion.js completion.sh index.js opt.js shell.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 code-point-at index.js package.json readme.md collect-v8-coverage CHANGELOG.md README.md index.d.ts index.js package.json collection-visit README.md index.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 color-string CHANGELOG.md README.md index.js package.json color README.md index.js node_modules 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 package.json combined-stream Readme.md lib combined_stream.js package.json command-exists .travis.yml README.md appveyor.yml index.js lib command-exists.js package.json test executable-script.cmd executable-script.js non-executable-script.js test.js 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 concat-map .travis.yml example map.js index.js package.json test map.js concat-stream index.js package.json readme.md configstore index.js package.json readme.md console-browserify .testem.json .travis.yml CHANGELOG.md 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 convert-source-map README.md index.js node_modules safe-buffer README.md index.d.ts index.js package.json package.json copy-descriptor index.js package.json core-js-compat README.md compat.js data.json entries.json external.json get-modules-list-for-target-version.js helpers.js index.js modules-by-versions.json modules.json node_modules 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 re.js package.json ranges gtr.js intersects.js ltr.js max-satisfying.js min-satisfying.js min-version.js outside.js to-comparators.js valid.js package.json targets-parser.js core-js CHANGELOG.md Gruntfile.js README.md bower.json build config.js index.js client core.js core.min.js library.js library.min.js shim.js shim.min.js core _.js delay.js dict.js function.js index.js number.js object.js regexp.js string.js es5 index.js es6 array.js date.js function.js index.js map.js math.js number.js object.js parse-float.js parse-int.js promise.js reflect.js regexp.js set.js string.js symbol.js typed.js weak-map.js weak-set.js es7 array.js asap.js error.js global.js index.js map.js math.js object.js observable.js promise.js reflect.js set.js string.js symbol.js system.js weak-map.js weak-set.js fn _.js array concat.js copy-within.js entries.js every.js fill.js filter.js find-index.js find.js flat-map.js flatten.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 pop.js push.js reduce-right.js reduce.js reverse.js shift.js slice.js some.js sort.js splice.js unshift.js values.js virtual copy-within.js entries.js every.js fill.js filter.js find-index.js find.js flat-map.js flatten.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 slice.js some.js sort.js values.js asap.js clear-immediate.js date index.js now.js to-iso-string.js to-json.js to-primitive.js to-string.js delay.js dict.js dom-collections index.js iterator.js error index.js is-error.js function bind.js has-instance.js index.js name.js part.js virtual bind.js index.js part.js get-iterator-method.js get-iterator.js global.js is-iterable.js json index.js stringify.js map.js map from.js index.js of.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 sign.js signbit.js sinh.js tanh.js trunc.js umulh.js number constructor.js epsilon.js index.js is-finite.js is-integer.js is-nan.js is-safe-integer.js iterator.js max-safe-integer.js min-safe-integer.js parse-float.js parse-int.js to-fixed.js to-precision.js virtual index.js iterator.js to-fixed.js to-precision.js object assign.js classof.js create.js define-getter.js define-properties.js define-property.js define-setter.js define.js entries.js freeze.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-object.js is-sealed.js is.js keys.js lookup-getter.js lookup-setter.js make.js prevent-extensions.js seal.js set-prototype-of.js values.js observable.js parse-float.js parse-int.js promise.js promise finally.js index.js try.js reflect apply.js construct.js define-metadata.js define-property.js delete-metadata.js delete-property.js enumerate.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 escape.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.js set from.js index.js of.js string anchor.js at.js big.js blink.js bold.js code-point-at.js ends-with.js escape-html.js fixed.js fontcolor.js fontsize.js from-code-point.js includes.js index.js italics.js iterator.js link.js match-all.js pad-end.js pad-start.js raw.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 unescape-html.js virtual anchor.js at.js big.js blink.js bold.js code-point-at.js ends-with.js escape-html.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 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 unescape-html.js symbol async-iterator.js for.js has-instance.js index.js is-concat-spreadable.js iterator.js key-for.js match.js observable.js replace.js search.js species.js split.js to-primitive.js to-string-tag.js unscopables.js system global.js index.js typed array-buffer.js data-view.js float32-array.js float64-array.js index.js int16-array.js int32-array.js int8-array.js uint16-array.js uint32-array.js uint8-array.js uint8-clamped-array.js weak-map.js weak-map from.js index.js of.js weak-set.js weak-set from.js index.js of.js index.js library core _.js delay.js dict.js function.js index.js number.js object.js regexp.js string.js es5 index.js es6 array.js date.js function.js index.js map.js math.js number.js object.js parse-float.js parse-int.js promise.js reflect.js regexp.js set.js string.js symbol.js typed.js weak-map.js weak-set.js es7 array.js asap.js error.js global.js index.js map.js math.js object.js observable.js promise.js reflect.js set.js string.js symbol.js system.js weak-map.js weak-set.js fn _.js array concat.js copy-within.js entries.js every.js fill.js filter.js find-index.js find.js flat-map.js flatten.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 pop.js push.js reduce-right.js reduce.js reverse.js shift.js slice.js some.js sort.js splice.js unshift.js values.js virtual copy-within.js entries.js every.js fill.js filter.js find-index.js find.js flat-map.js flatten.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 slice.js some.js sort.js values.js asap.js clear-immediate.js date index.js now.js to-iso-string.js to-json.js to-primitive.js to-string.js delay.js dict.js dom-collections index.js iterator.js error index.js is-error.js function bind.js has-instance.js index.js name.js part.js virtual bind.js index.js part.js get-iterator-method.js get-iterator.js global.js is-iterable.js json index.js stringify.js map.js map from.js index.js of.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 sign.js signbit.js sinh.js tanh.js trunc.js umulh.js number constructor.js epsilon.js index.js is-finite.js is-integer.js is-nan.js is-safe-integer.js iterator.js max-safe-integer.js min-safe-integer.js parse-float.js parse-int.js to-fixed.js to-precision.js virtual index.js iterator.js to-fixed.js to-precision.js object assign.js classof.js create.js define-getter.js define-properties.js define-property.js define-setter.js define.js entries.js freeze.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-object.js is-sealed.js is.js keys.js lookup-getter.js lookup-setter.js make.js prevent-extensions.js seal.js set-prototype-of.js values.js observable.js parse-float.js parse-int.js promise.js promise finally.js index.js try.js reflect apply.js construct.js define-metadata.js define-property.js delete-metadata.js delete-property.js enumerate.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 escape.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.js set from.js index.js of.js string anchor.js at.js big.js blink.js bold.js code-point-at.js ends-with.js escape-html.js fixed.js fontcolor.js fontsize.js from-code-point.js includes.js index.js italics.js iterator.js link.js match-all.js pad-end.js pad-start.js raw.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 unescape-html.js virtual anchor.js at.js big.js blink.js bold.js code-point-at.js ends-with.js escape-html.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 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 unescape-html.js symbol async-iterator.js for.js has-instance.js index.js is-concat-spreadable.js iterator.js key-for.js match.js observable.js replace.js search.js species.js split.js to-primitive.js to-string-tag.js unscopables.js system global.js index.js typed array-buffer.js data-view.js float32-array.js float64-array.js index.js int16-array.js int32-array.js int8-array.js uint16-array.js uint32-array.js uint8-array.js uint8-clamped-array.js weak-map.js weak-map from.js index.js of.js weak-set.js weak-set from.js index.js of.js index.js modules _a-function.js _a-number-value.js _add-to-unscopables.js _advance-string-index.js _an-instance.js _an-object.js _array-copy-within.js _array-fill.js _array-from-iterable.js _array-includes.js _array-methods.js _array-reduce.js _array-species-constructor.js _array-species-create.js _bind.js _classof.js _cof.js _collection-strong.js _collection-to-json.js _collection-weak.js _collection.js _core.js _create-property.js _ctx.js _date-to-iso-string.js _date-to-primitive.js _defined.js _descriptors.js _dom-create.js _entry-virtual.js _enum-bug-keys.js _enum-keys.js _export.js _fails-is-regexp.js _fails.js _fix-re-wks.js _flags.js _flatten-into-array.js _for-of.js _function-to-string.js _global.js _has.js _hide.js _html.js _ie8-dom-define.js _inherit-if-required.js _invoke.js _iobject.js _is-array-iter.js _is-array.js _is-integer.js _is-object.js _is-regexp.js _iter-call.js _iter-create.js _iter-define.js _iter-detect.js _iter-step.js _iterators.js _keyof.js _library.js _math-expm1.js _math-fround.js _math-log1p.js _math-scale.js _math-sign.js _meta.js _metadata.js _microtask.js _native-weak-map.js _new-promise-capability.js _object-assign.js _object-create.js _object-define.js _object-dp.js _object-dps.js _object-forced-pam.js _object-gopd.js _object-gopn-ext.js _object-gopn.js _object-gops.js _object-gpo.js _object-keys-internal.js _object-keys.js _object-pie.js _object-sap.js _object-to-array.js _own-keys.js _parse-float.js _parse-int.js _partial.js _path.js _perform.js _promise-resolve.js _property-desc.js _redefine-all.js _redefine.js _regexp-exec-abstract.js _regexp-exec.js _replacer.js _same-value.js _set-collection-from.js _set-collection-of.js _set-proto.js _set-species.js _set-to-string-tag.js _shared-key.js _shared.js _species-constructor.js _strict-method.js _string-at.js _string-context.js _string-html.js _string-pad.js _string-repeat.js _string-trim.js _string-ws.js _task.js _to-absolute-index.js _to-index.js _to-integer.js _to-iobject.js _to-length.js _to-object.js _to-primitive.js _typed-array.js _typed-buffer.js _typed.js _uid.js _user-agent.js _validate-collection.js _wks-define.js _wks-ext.js _wks.js core.delay.js core.dict.js core.function.part.js core.get-iterator-method.js core.get-iterator.js core.is-iterable.js core.number.iterator.js core.object.classof.js core.object.define.js core.object.is-object.js core.object.make.js core.regexp.escape.js core.string.escape-html.js core.string.unescape-html.js es5.js es6.array.copy-within.js es6.array.every.js es6.array.fill.js es6.array.filter.js es6.array.find-index.js es6.array.find.js es6.array.for-each.js es6.array.from.js es6.array.index-of.js es6.array.is-array.js es6.array.iterator.js es6.array.join.js es6.array.last-index-of.js es6.array.map.js es6.array.of.js es6.array.reduce-right.js es6.array.reduce.js es6.array.slice.js es6.array.some.js es6.array.sort.js es6.array.species.js es6.date.now.js es6.date.to-iso-string.js es6.date.to-json.js es6.date.to-primitive.js es6.date.to-string.js es6.function.bind.js es6.function.has-instance.js es6.function.name.js es6.map.js es6.math.acosh.js es6.math.asinh.js es6.math.atanh.js es6.math.cbrt.js es6.math.clz32.js es6.math.cosh.js es6.math.expm1.js es6.math.fround.js es6.math.hypot.js es6.math.imul.js es6.math.log10.js es6.math.log1p.js es6.math.log2.js es6.math.sign.js es6.math.sinh.js es6.math.tanh.js es6.math.trunc.js es6.number.constructor.js es6.number.epsilon.js es6.number.is-finite.js es6.number.is-integer.js es6.number.is-nan.js es6.number.is-safe-integer.js es6.number.max-safe-integer.js es6.number.min-safe-integer.js es6.number.parse-float.js es6.number.parse-int.js es6.number.to-fixed.js es6.number.to-precision.js es6.object.assign.js es6.object.create.js es6.object.define-properties.js es6.object.define-property.js es6.object.freeze.js es6.object.get-own-property-descriptor.js es6.object.get-own-property-names.js es6.object.get-prototype-of.js es6.object.is-extensible.js es6.object.is-frozen.js es6.object.is-sealed.js es6.object.is.js es6.object.keys.js es6.object.prevent-extensions.js es6.object.seal.js es6.object.set-prototype-of.js es6.object.to-string.js es6.parse-float.js es6.parse-int.js es6.promise.js es6.reflect.apply.js es6.reflect.construct.js es6.reflect.define-property.js es6.reflect.delete-property.js es6.reflect.enumerate.js es6.reflect.get-own-property-descriptor.js es6.reflect.get-prototype-of.js es6.reflect.get.js es6.reflect.has.js es6.reflect.is-extensible.js es6.reflect.own-keys.js es6.reflect.prevent-extensions.js es6.reflect.set-prototype-of.js es6.reflect.set.js es6.regexp.constructor.js es6.regexp.exec.js es6.regexp.flags.js es6.regexp.match.js es6.regexp.replace.js es6.regexp.search.js es6.regexp.split.js es6.regexp.to-string.js es6.set.js es6.string.anchor.js es6.string.big.js es6.string.blink.js es6.string.bold.js es6.string.code-point-at.js es6.string.ends-with.js es6.string.fixed.js es6.string.fontcolor.js es6.string.fontsize.js es6.string.from-code-point.js es6.string.includes.js es6.string.italics.js es6.string.iterator.js es6.string.link.js es6.string.raw.js es6.string.repeat.js es6.string.small.js es6.string.starts-with.js es6.string.strike.js es6.string.sub.js es6.string.sup.js es6.string.trim.js es6.symbol.js es6.typed.array-buffer.js es6.typed.data-view.js es6.typed.float32-array.js es6.typed.float64-array.js es6.typed.int16-array.js es6.typed.int32-array.js es6.typed.int8-array.js es6.typed.uint16-array.js es6.typed.uint32-array.js es6.typed.uint8-array.js es6.typed.uint8-clamped-array.js es6.weak-map.js es6.weak-set.js es7.array.flat-map.js es7.array.flatten.js es7.array.includes.js es7.asap.js es7.error.is-error.js es7.global.js es7.map.from.js es7.map.of.js es7.map.to-json.js es7.math.clamp.js es7.math.deg-per-rad.js es7.math.degrees.js es7.math.fscale.js es7.math.iaddh.js es7.math.imulh.js es7.math.isubh.js es7.math.rad-per-deg.js es7.math.radians.js es7.math.scale.js es7.math.signbit.js es7.math.umulh.js es7.object.define-getter.js es7.object.define-setter.js es7.object.entries.js es7.object.get-own-property-descriptors.js es7.object.lookup-getter.js es7.object.lookup-setter.js es7.object.values.js es7.observable.js es7.promise.finally.js es7.promise.try.js es7.reflect.define-metadata.js es7.reflect.delete-metadata.js es7.reflect.get-metadata-keys.js es7.reflect.get-metadata.js es7.reflect.get-own-metadata-keys.js es7.reflect.get-own-metadata.js es7.reflect.has-metadata.js es7.reflect.has-own-metadata.js es7.reflect.metadata.js es7.set.from.js es7.set.of.js es7.set.to-json.js es7.string.at.js es7.string.match-all.js es7.string.pad-end.js es7.string.pad-start.js es7.string.trim-left.js es7.string.trim-right.js es7.symbol.async-iterator.js es7.symbol.observable.js es7.system.global.js es7.weak-map.from.js es7.weak-map.of.js es7.weak-set.from.js es7.weak-set.of.js web.dom.iterable.js web.immediate.js web.timers.js shim.js stage 0.js 1.js 2.js 3.js 4.js index.js pre.js web dom-collections.js immediate.js index.js timers.js modules _a-function.js _a-number-value.js _add-to-unscopables.js _advance-string-index.js _an-instance.js _an-object.js _array-copy-within.js _array-fill.js _array-from-iterable.js _array-includes.js _array-methods.js _array-reduce.js _array-species-constructor.js _array-species-create.js _bind.js _classof.js _cof.js _collection-strong.js _collection-to-json.js _collection-weak.js _collection.js _core.js _create-property.js _ctx.js _date-to-iso-string.js _date-to-primitive.js _defined.js _descriptors.js _dom-create.js _entry-virtual.js _enum-bug-keys.js _enum-keys.js _export.js _fails-is-regexp.js _fails.js _fix-re-wks.js _flags.js _flatten-into-array.js _for-of.js _function-to-string.js _global.js _has.js _hide.js _html.js _ie8-dom-define.js _inherit-if-required.js _invoke.js _iobject.js _is-array-iter.js _is-array.js _is-integer.js _is-object.js _is-regexp.js _iter-call.js _iter-create.js _iter-define.js _iter-detect.js _iter-step.js _iterators.js _keyof.js _library.js _math-expm1.js _math-fround.js _math-log1p.js _math-scale.js _math-sign.js _meta.js _metadata.js _microtask.js _native-weak-map.js _new-promise-capability.js _object-assign.js _object-create.js _object-define.js _object-dp.js _object-dps.js _object-forced-pam.js _object-gopd.js _object-gopn-ext.js _object-gopn.js _object-gops.js _object-gpo.js _object-keys-internal.js _object-keys.js _object-pie.js _object-sap.js _object-to-array.js _own-keys.js _parse-float.js _parse-int.js _partial.js _path.js _perform.js _promise-resolve.js _property-desc.js _redefine-all.js _redefine.js _regexp-exec-abstract.js _regexp-exec.js _replacer.js _same-value.js _set-collection-from.js _set-collection-of.js _set-proto.js _set-species.js _set-to-string-tag.js _shared-key.js _shared.js _species-constructor.js _strict-method.js _string-at.js _string-context.js _string-html.js _string-pad.js _string-repeat.js _string-trim.js _string-ws.js _task.js _to-absolute-index.js _to-index.js _to-integer.js _to-iobject.js _to-length.js _to-object.js _to-primitive.js _typed-array.js _typed-buffer.js _typed.js _uid.js _user-agent.js _validate-collection.js _wks-define.js _wks-ext.js _wks.js core.delay.js core.dict.js core.function.part.js core.get-iterator-method.js core.get-iterator.js core.is-iterable.js core.number.iterator.js core.object.classof.js core.object.define.js core.object.is-object.js core.object.make.js core.regexp.escape.js core.string.escape-html.js core.string.unescape-html.js es5.js es6.array.copy-within.js es6.array.every.js es6.array.fill.js es6.array.filter.js es6.array.find-index.js es6.array.find.js es6.array.for-each.js es6.array.from.js es6.array.index-of.js es6.array.is-array.js es6.array.iterator.js es6.array.join.js es6.array.last-index-of.js es6.array.map.js es6.array.of.js es6.array.reduce-right.js es6.array.reduce.js es6.array.slice.js es6.array.some.js es6.array.sort.js es6.array.species.js es6.date.now.js es6.date.to-iso-string.js es6.date.to-json.js es6.date.to-primitive.js es6.date.to-string.js es6.function.bind.js es6.function.has-instance.js es6.function.name.js es6.map.js es6.math.acosh.js es6.math.asinh.js es6.math.atanh.js es6.math.cbrt.js es6.math.clz32.js es6.math.cosh.js es6.math.expm1.js es6.math.fround.js es6.math.hypot.js es6.math.imul.js es6.math.log10.js es6.math.log1p.js es6.math.log2.js es6.math.sign.js es6.math.sinh.js es6.math.tanh.js es6.math.trunc.js es6.number.constructor.js es6.number.epsilon.js es6.number.is-finite.js es6.number.is-integer.js es6.number.is-nan.js es6.number.is-safe-integer.js es6.number.max-safe-integer.js es6.number.min-safe-integer.js es6.number.parse-float.js es6.number.parse-int.js es6.number.to-fixed.js es6.number.to-precision.js es6.object.assign.js es6.object.create.js es6.object.define-properties.js es6.object.define-property.js es6.object.freeze.js es6.object.get-own-property-descriptor.js es6.object.get-own-property-names.js es6.object.get-prototype-of.js es6.object.is-extensible.js es6.object.is-frozen.js es6.object.is-sealed.js es6.object.is.js es6.object.keys.js es6.object.prevent-extensions.js es6.object.seal.js es6.object.set-prototype-of.js es6.object.to-string.js es6.parse-float.js es6.parse-int.js es6.promise.js es6.reflect.apply.js es6.reflect.construct.js es6.reflect.define-property.js es6.reflect.delete-property.js es6.reflect.enumerate.js es6.reflect.get-own-property-descriptor.js es6.reflect.get-prototype-of.js es6.reflect.get.js es6.reflect.has.js es6.reflect.is-extensible.js es6.reflect.own-keys.js es6.reflect.prevent-extensions.js es6.reflect.set-prototype-of.js es6.reflect.set.js es6.regexp.constructor.js es6.regexp.exec.js es6.regexp.flags.js es6.regexp.match.js es6.regexp.replace.js es6.regexp.search.js es6.regexp.split.js es6.regexp.to-string.js es6.set.js es6.string.anchor.js es6.string.big.js es6.string.blink.js es6.string.bold.js es6.string.code-point-at.js es6.string.ends-with.js es6.string.fixed.js es6.string.fontcolor.js es6.string.fontsize.js es6.string.from-code-point.js es6.string.includes.js es6.string.italics.js es6.string.iterator.js es6.string.link.js es6.string.raw.js es6.string.repeat.js es6.string.small.js es6.string.starts-with.js es6.string.strike.js es6.string.sub.js es6.string.sup.js es6.string.trim.js es6.symbol.js es6.typed.array-buffer.js es6.typed.data-view.js es6.typed.float32-array.js es6.typed.float64-array.js es6.typed.int16-array.js es6.typed.int32-array.js es6.typed.int8-array.js es6.typed.uint16-array.js es6.typed.uint32-array.js es6.typed.uint8-array.js es6.typed.uint8-clamped-array.js es6.weak-map.js es6.weak-set.js es7.array.flat-map.js es7.array.flatten.js es7.array.includes.js es7.asap.js es7.error.is-error.js es7.global.js es7.map.from.js es7.map.of.js es7.map.to-json.js es7.math.clamp.js es7.math.deg-per-rad.js es7.math.degrees.js es7.math.fscale.js es7.math.iaddh.js es7.math.imulh.js es7.math.isubh.js es7.math.rad-per-deg.js es7.math.radians.js es7.math.scale.js es7.math.signbit.js es7.math.umulh.js es7.object.define-getter.js es7.object.define-setter.js es7.object.entries.js es7.object.get-own-property-descriptors.js es7.object.lookup-getter.js es7.object.lookup-setter.js es7.object.values.js es7.observable.js es7.promise.finally.js es7.promise.try.js es7.reflect.define-metadata.js es7.reflect.delete-metadata.js es7.reflect.get-metadata-keys.js es7.reflect.get-metadata.js es7.reflect.get-own-metadata-keys.js es7.reflect.get-own-metadata.js es7.reflect.has-metadata.js es7.reflect.has-own-metadata.js es7.reflect.metadata.js es7.set.from.js es7.set.of.js es7.set.to-json.js es7.string.at.js es7.string.match-all.js es7.string.pad-end.js es7.string.pad-start.js es7.string.trim-left.js es7.string.trim-right.js es7.symbol.async-iterator.js es7.symbol.observable.js es7.system.global.js es7.weak-map.from.js es7.weak-map.of.js es7.weak-set.from.js es7.weak-set.of.js library _add-to-unscopables.js _collection.js _export.js _library.js _path.js _redefine-all.js _redefine.js _regexp-exec-abstract.js _regexp-exec.js _set-species.js es6.date.to-json.js es6.date.to-primitive.js es6.date.to-string.js es6.function.name.js es6.number.constructor.js es6.object.to-string.js es6.regexp.constructor.js es6.regexp.exec.js es6.regexp.flags.js es6.regexp.match.js es6.regexp.replace.js es6.regexp.search.js es6.regexp.split.js es6.regexp.to-string.js web.dom.iterable.js web.dom.iterable.js web.immediate.js web.timers.js package.json postinstall.js shim.js stage 0.js 1.js 2.js 3.js 4.js index.js pre.js web dom-collections.js immediate.js index.js timers.js core-util-is README.md lib util.js package.json test.js cosmiconfig CHANGELOG.md README.md dist cacheWrapper.js createExplorer.js getDirectory.js getPropertyByPath.js index.js loaders.js readFile.js node_modules parse-json index.js package.json readme.md package.json create-ecdh .travis.yml browser.js index.js node_modules bn.js README.md lib bn.js package.json util genCombMulTo.js genCombMulTo10.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 crypto-random-string index.d.ts index.js package.json readme.md css-color-names README.md css-color-names.json package.json css-declaration-sorter changelog.md license.md orders concentric-css.json smacss.json source.json package.json readme.md src index.js css-modules-loader-core README.md lib file-system-loader.js index.js parser.js node_modules ansi-regex index.js package.json readme.md ansi-styles index.js package.json readme.md chalk index.js node_modules supports-color index.js package.json readme.md package.json readme.md has-flag index.js package.json readme.md postcss CHANGELOG.md README.md docs 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 package.json 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 strip-ansi index.js package.json readme.md supports-color browser.js index.js package.json readme.md package.json css-select-base-adapter index.js package.json readme.md test data.js implementation.js index.js css-select README.md index.d.ts index.js lib attributes.js compile.js general.js procedure.json pseudos.js sort.js package.json css-selector-tokenizer README.md lib index.js parse.js parseValues.js stringify.js stringifyValues.js uni-regexp.js package.json css-tree CHANGELOG.md README.md data index.js patch.json dist csstree.js csstree.min.js default-syntax.json lib common List.js OffsetToLocation.js SyntaxError.js TokenStream.js adopt-buffer.js convertor create.js index.js definition-syntax SyntaxError.js generate.js index.js parse.js tokenizer.js walk.js generator create.js index.js sourceMap.js index.js lexer Lexer.js error.js generic-an-plus-b.js generic-urange.js generic.js index.js match-graph.js match.js prepare-tokens.js search.js structure.js trace.js parser create.js index.js sequence.js syntax atrule font-face.js import.js index.js media.js page.js supports.js config lexer.js mix.js parser.js walker.js create.js function element.js expression.js var.js index.js node AnPlusB.js Atrule.js AtrulePrelude.js AttributeSelector.js Block.js Brackets.js CDC.js CDO.js ClassSelector.js Combinator.js Comment.js Declaration.js DeclarationList.js Dimension.js Function.js HexColor.js IdSelector.js Identifier.js MediaFeature.js MediaQuery.js MediaQueryList.js Nth.js Number.js Operator.js Parentheses.js Percentage.js PseudoClassSelector.js PseudoElementSelector.js Ratio.js Raw.js Rule.js Selector.js SelectorList.js String.js StyleSheet.js TypeSelector.js UnicodeRange.js Url.js Value.js WhiteSpace.js index.js pseudo common nth.js nthWithOfClause.js selectorList.js dir.js has.js index.js lang.js matches.js not.js nth-child.js nth-last-child.js nth-last-of-type.js nth-of-type.js slotted.js scope atrulePrelude.js default.js index.js selector.js value.js tokenizer char-code-definitions.js const.js index.js utils.js utils clone.js createCustomError.js names.js walker create.js index.js package.json css-what lib index.d.ts index.js parse.d.ts parse.js stringify.d.ts stringify.js package.json readme.md cssesc LICENSE-MIT.txt README.md cssesc.js package.json cssnano-preset-default README.md dist index.js package.json cssnano-util-get-arguments CHANGELOG.md README.md dist index.js package.json cssnano-util-get-match CHANGELOG.md README.md dist index.js package.json cssnano-util-raw-cache CHANGELOG.md README.md dist index.js package.json cssnano-util-same-parent CHANGELOG.md README.md dist index.js package.json cssnano CHANGELOG.md README.md dist index.js package.json quickstart.js csso CHANGELOG.md README.md dist csso.js csso.min.js lib clean Atrule.js Comment.js Declaration.js Raw.js Rule.js TypeSelector.js WhiteSpace.js index.js utils.js compress.js index.js replace Atrule.js AttributeSelector.js Dimension.js Number.js Percentage.js String.js Url.js Value.js atrule keyframes.js color.js index.js property background.js border.js font-weight.js font.js restructure 1-mergeAtrule.js 2-initialMergeRuleset.js 3-disjoinRuleset.js 4-restructShorthand.js 6-restructBlock.js 7-mergeRuleset.js 8-restructRuleset.js index.js prepare createDeclarationIndexer.js index.js processSelector.js specificity.js utils.js usage.js node_modules css-tree CHANGELOG.md README.md data index.js patch.json dist csstree.js csstree.min.js default-syntax.json lib common List.js OffsetToLocation.js SyntaxError.js TokenStream.js adopt-buffer.js convertor create.js index.js definition-syntax SyntaxError.js generate.js index.js parse.js tokenizer.js walk.js generator create.js index.js sourceMap.js index.js lexer Lexer.js error.js generic-an-plus-b.js generic-urange.js generic.js index.js match-graph.js match.js prepare-tokens.js search.js structure.js trace.js parser create.js index.js sequence.js syntax atrule font-face.js import.js index.js media.js page.js supports.js config lexer.js mix.js parser.js walker.js create.js function element.js expression.js var.js index.js node AnPlusB.js Atrule.js AtrulePrelude.js AttributeSelector.js Block.js Brackets.js CDC.js CDO.js ClassSelector.js Combinator.js Comment.js Declaration.js DeclarationList.js Dimension.js Function.js HexColor.js IdSelector.js Identifier.js MediaFeature.js MediaQuery.js MediaQueryList.js Nth.js Number.js Operator.js Parentheses.js Percentage.js PseudoClassSelector.js PseudoElementSelector.js Ratio.js Raw.js Rule.js Selector.js SelectorList.js String.js StyleSheet.js TypeSelector.js UnicodeRange.js Url.js Value.js WhiteSpace.js index.js pseudo common nth.js nthWithOfClause.js selectorList.js dir.js has.js index.js lang.js matches.js not.js nth-child.js nth-last-child.js nth-last-of-type.js nth-of-type.js slotted.js scope atrulePrelude.js default.js index.js selector.js value.js tokenizer char-code-definitions.js const.js index.js utils.js utils clone.js createCustomError.js names.js walker create.js index.js package.json mdn-data README.md api index.js inheritance.json inheritance.schema.json css at-rules.json at-rules.schema.json definitions.json index.js properties.json properties.schema.json readme.md selectors.json selectors.schema.json syntaxes.json syntaxes.schema.json types.json types.schema.json units.json units.schema.json index.js l10n css.json index.js package.json package.json cssom LICENSE.txt lib CSSDocumentRule.js CSSFontFaceRule.js CSSHostRule.js CSSImportRule.js CSSKeyframeRule.js CSSKeyframesRule.js CSSMediaRule.js CSSOM.js CSSRule.js CSSStyleDeclaration.js CSSStyleRule.js CSSStyleSheet.js CSSSupportsRule.js CSSValue.js CSSValueExpression.js MatcherList.js MediaList.js StyleSheet.js clone.js index.js parse.js package.json cssstyle README.md lib CSSStyleDeclaration.js CSSStyleDeclaration.test.js allExtraProperties.js allProperties.js allWebkitProperties.js constants.js implementedProperties.js named_colors.json parsers.js parsers.test.js properties.js properties azimuth.js background.js backgroundAttachment.js backgroundColor.js backgroundImage.js backgroundPosition.js backgroundRepeat.js border.js borderBottom.js borderBottomColor.js borderBottomStyle.js borderBottomWidth.js borderCollapse.js borderColor.js borderLeft.js borderLeftColor.js borderLeftStyle.js borderLeftWidth.js borderRight.js borderRightColor.js borderRightStyle.js borderRightWidth.js borderSpacing.js borderStyle.js borderTop.js borderTopColor.js borderTopStyle.js borderTopWidth.js borderWidth.js bottom.js clear.js clip.js color.js cssFloat.js flex.js flexBasis.js flexGrow.js flexShrink.js float.js floodColor.js font.js fontFamily.js fontSize.js fontStyle.js fontVariant.js fontWeight.js height.js left.js lightingColor.js lineHeight.js margin.js marginBottom.js marginLeft.js marginRight.js marginTop.js opacity.js outlineColor.js padding.js paddingBottom.js paddingLeft.js paddingRight.js paddingTop.js right.js stopColor.js textLineThroughColor.js textOverlineColor.js textUnderlineColor.js top.js webkitBorderAfterColor.js webkitBorderBeforeColor.js webkitBorderEndColor.js webkitBorderStartColor.js webkitColumnRuleColor.js webkitMatchNearestMailBlockquoteColor.js webkitTapHighlightColor.js webkitTextEmphasisColor.js webkitTextFillColor.js webkitTextStrokeColor.js width.js utils colorSpace.js getBasicPropertyDescriptor.js node_modules cssom LICENSE.txt lib CSSDocumentRule.js CSSFontFaceRule.js CSSHostRule.js CSSImportRule.js CSSKeyframeRule.js CSSKeyframesRule.js CSSMediaRule.js CSSOM.js CSSRule.js CSSStyleDeclaration.js CSSStyleRule.js CSSStyleSheet.js CSSSupportsRule.js CSSValue.js CSSValueExpression.js MatcherList.js MediaList.js StyleSheet.js clone.js index.js parse.js package.json package.json dashdash CHANGES.md LICENSE.txt README.md lib dashdash.js package.json data-urls LICENSE.txt README.md lib parser.js utils.js package.json deasync .github FUNDING.yml .travis.yml README.md build.js index.js package.json quick-test.js spec app exec.js request.js sleep.js worker-threads.js index.js debug README.md package.json src browser.js common.js index.js node.js decamelize index.js package.json readme.md decimal.js CHANGELOG.md LICENCE.md README.md decimal.d.ts decimal.global.d.ts decimal.js decimal.min.js doc API.html package.json 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 defaults README.md index.js node_modules clone README.md clone.js package.json package.json test.js defer-to-connect README.md dist index.d.ts index.js package.json 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 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 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-libc README.md bin detect-libc.js lib detect-libc.js package.json detect-newline index.d.ts index.js package.json readme.md diff-sequences README.md build index.d.ts index.js package.json perf example.md index.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 diffie-hellman .travis.yml browser.js index.js lib dh.js generatePrime.js primes.json node_modules bn.js README.md lib bn.js package.json util genCombMulTo.js genCombMulTo10.js package.json readme.md discontinuous-range .travis.yml README.md index.js package.json test main-test.js dom-serializer README.md foreignNames.json index.d.ts index.js node_modules domelementtype README.md lib index.d.ts index.js package.json entities lib decode.d.ts decode.js decode_codepoint.d.ts decode_codepoint.js encode.d.ts encode.js index.d.ts index.js maps decode.json entities.json legacy.json xml.json package.json readme.md package.json domain-browser HISTORY.md LICENSE.md README.md package.json source index.js domelementtype index.js package.json readme.md domexception LICENSE.txt README.md index.js lib DOMException-impl.js DOMException.js legacy-error-codes.json utils.js node_modules webidl-conversions LICENSE.md README.md lib index.js package.json package.json webidl2js-wrapper.js domhandler .travis.yml index.js lib element.js node.js package.json readme.md test cases 01-basic.json 02-single_tag_1.json 03-single_tag_2.json 04-unescaped_in_script.json 05-tags_in_comment.json 06-comment_in_script.json 07-unescaped_in_style.json 08-extra_spaces_in_tag.json 09-unquoted_attrib.json 10-singular_attribute.json 11-text_outside_tags.json 12-text_only.json 13-comment_in_text.json 14-comment_in_text_in_script.json 15-non-verbose.json 16-normalize_whitespace.json 17-xml_namespace.json 18-enforce_empty_tags.json 19-ignore_empty_tags.json 20-template_script_tags.json 21-conditional_comments.json 22-lowercase_tags.json 23-dom-lvl1.json 24-with-start-indices.json 25-with-end-indices.json tests.js domutils .travis.yml index.js lib helpers.js legacy.js manipulation.js querying.js stringify.js traversal.js package.json readme.md test fixture.js tests helpers.js legacy.js traversal.js utils.js dot-prop index.d.ts index.js package.json readme.md dotenv-expand README.md index.d.ts lib main.js package.json dotenv CHANGELOG.md README.md appveyor.yml config.js lib main.js package.json duplexer2 LICENSE.md README.md index.js package.json duplexer3 LICENSE.md README.md index.js package.json 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 node_modules bn.js README.md lib bn.js package.json util genCombMulTo.js genCombMulTo10.js package.json email-addresses .travis.yml Changes.md README.md bower.json lib email-addresses.d.ts email-addresses.js email-addresses.min.js package.json test email-addresses.js is_email.js tests.xml emittery 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 encodeurl HISTORY.md README.md index.js package.json end-of-stream README.md index.js package.json entities .travis.yml index.js lib decode.js decode_codepoint.js encode.js maps decode.json entities.json legacy.json xml.json package.json readme.md test test.js env-cmd CHANGELOG.md README.md bin env-cmd.js dist env-cmd.d.ts env-cmd.js expand-envs.d.ts expand-envs.js get-env-vars.d.ts get-env-vars.js index.d.ts index.js parse-args.d.ts parse-args.js parse-env-file.d.ts parse-env-file.js parse-rc-file.d.ts parse-rc-file.js signal-termination.d.ts signal-termination.js spawn.d.ts spawn.js types.d.ts types.js utils.d.ts utils.js package.json env-paths index.d.ts index.js package.json readme.md envinfo README.md dist cli.js envinfo.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 es-abstract .github FUNDING.yml workflows codeql-analysis.yml rebase.yml .travis.yml 2015 AbstractEqualityComparison.js AbstractRelationalComparison.js AdvanceStringIndex.js ArrayCreate.js ArraySetLength.js ArraySpeciesCreate.js Call.js CanonicalNumericIndexString.js CompletePropertyDescriptor.js CreateDataProperty.js CreateDataPropertyOrThrow.js CreateHTML.js CreateIterResultObject.js CreateListFromArrayLike.js CreateMethodProperty.js DateFromTime.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js DefinePropertyOrThrow.js DeletePropertyOrThrow.js EnumerableOwnNames.js FromPropertyDescriptor.js Get.js GetIterator.js GetMethod.js GetOwnPropertyKeys.js GetPrototypeFromConstructor.js GetSubstitution.js GetV.js HasOwnProperty.js HasProperty.js HourFromTime.js InLeapYear.js InstanceofOperator.js Invoke.js IsAccessorDescriptor.js IsArray.js IsCallable.js IsConcatSpreadable.js IsConstructor.js IsDataDescriptor.js IsExtensible.js IsGenericDescriptor.js IsInteger.js IsPromise.js IsPropertyDescriptor.js IsPropertyKey.js IsRegExp.js IteratorClose.js IteratorComplete.js IteratorNext.js IteratorStep.js IteratorValue.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js ObjectCreate.js OrdinaryCreateFromConstructor.js OrdinaryDefineOwnProperty.js OrdinaryGetOwnProperty.js OrdinaryHasInstance.js OrdinaryHasProperty.js QuoteJSONString.js RegExpExec.js RequireObjectCoercible.js SameValue.js SameValueZero.js SecFromTime.js Set.js SetFunctionName.js SetIntegrityLevel.js SpeciesConstructor.js StrictEqualityComparison.js SymbolDescriptiveString.js TestIntegrityLevel.js TimeClip.js TimeFromYear.js TimeWithinDay.js ToBoolean.js ToDateString.js ToInt16.js ToInt32.js ToInt8.js ToInteger.js ToLength.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToPropertyKey.js ToString.js ToUint16.js ToUint32.js ToUint8.js ToUint8Clamp.js Type.js ValidateAndApplyPropertyDescriptor.js WeekDay.js YearFromTime.js abs.js floor.js modulo.js msFromTime.js thisBooleanValue.js thisNumberValue.js thisStringValue.js thisTimeValue.js 2016 AbstractEqualityComparison.js AbstractRelationalComparison.js AdvanceStringIndex.js ArrayCreate.js ArraySetLength.js ArraySpeciesCreate.js Call.js CanonicalNumericIndexString.js CompletePropertyDescriptor.js CreateDataProperty.js CreateDataPropertyOrThrow.js CreateHTML.js CreateIterResultObject.js CreateListFromArrayLike.js CreateMethodProperty.js DateFromTime.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js DefinePropertyOrThrow.js DeletePropertyOrThrow.js EnumerableOwnNames.js FromPropertyDescriptor.js Get.js GetIterator.js GetMethod.js GetOwnPropertyKeys.js GetPrototypeFromConstructor.js GetSubstitution.js GetV.js HasOwnProperty.js HasProperty.js HourFromTime.js InLeapYear.js InstanceofOperator.js Invoke.js IsAccessorDescriptor.js IsArray.js IsCallable.js IsConcatSpreadable.js IsConstructor.js IsDataDescriptor.js IsExtensible.js IsGenericDescriptor.js IsInteger.js IsPromise.js IsPropertyDescriptor.js IsPropertyKey.js IsRegExp.js IterableToArrayLike.js IteratorClose.js IteratorComplete.js IteratorNext.js IteratorStep.js IteratorValue.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js ObjectCreate.js OrdinaryCreateFromConstructor.js OrdinaryDefineOwnProperty.js OrdinaryGetOwnProperty.js OrdinaryGetPrototypeOf.js OrdinaryHasInstance.js OrdinaryHasProperty.js OrdinarySetPrototypeOf.js QuoteJSONString.js RegExpExec.js RequireObjectCoercible.js SameValue.js SameValueNonNumber.js SameValueZero.js SecFromTime.js Set.js SetFunctionName.js SetIntegrityLevel.js SpeciesConstructor.js StrictEqualityComparison.js SymbolDescriptiveString.js TestIntegrityLevel.js TimeClip.js TimeFromYear.js TimeWithinDay.js ToBoolean.js ToDateString.js ToInt16.js ToInt32.js ToInt8.js ToInteger.js ToLength.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToPropertyKey.js ToString.js ToUint16.js ToUint32.js ToUint8.js ToUint8Clamp.js Type.js UTF16Encoding.js ValidateAndApplyPropertyDescriptor.js WeekDay.js YearFromTime.js abs.js floor.js modulo.js msFromTime.js thisBooleanValue.js thisNumberValue.js thisStringValue.js thisTimeValue.js 2017 AbstractEqualityComparison.js AbstractRelationalComparison.js AdvanceStringIndex.js ArrayCreate.js ArraySetLength.js ArraySpeciesCreate.js Call.js CanonicalNumericIndexString.js CompletePropertyDescriptor.js CreateDataProperty.js CreateDataPropertyOrThrow.js CreateHTML.js CreateIterResultObject.js CreateListFromArrayLike.js CreateMethodProperty.js DateFromTime.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js DefinePropertyOrThrow.js DeletePropertyOrThrow.js EnumerableOwnProperties.js FromPropertyDescriptor.js Get.js GetIterator.js GetMethod.js GetOwnPropertyKeys.js GetPrototypeFromConstructor.js GetSubstitution.js GetV.js HasOwnProperty.js HasProperty.js HourFromTime.js InLeapYear.js InstanceofOperator.js Invoke.js IsAccessorDescriptor.js IsArray.js IsCallable.js IsConcatSpreadable.js IsConstructor.js IsDataDescriptor.js IsExtensible.js IsGenericDescriptor.js IsInteger.js IsPromise.js IsPropertyDescriptor.js IsPropertyKey.js IsRegExp.js IterableToList.js IteratorClose.js IteratorComplete.js IteratorNext.js IteratorStep.js IteratorValue.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js ObjectCreate.js OrdinaryCreateFromConstructor.js OrdinaryDefineOwnProperty.js OrdinaryGetOwnProperty.js OrdinaryGetPrototypeOf.js OrdinaryHasInstance.js OrdinaryHasProperty.js OrdinarySetPrototypeOf.js QuoteJSONString.js RegExpExec.js RequireObjectCoercible.js SameValue.js SameValueNonNumber.js SameValueZero.js SecFromTime.js Set.js SetFunctionName.js SetIntegrityLevel.js SpeciesConstructor.js StrictEqualityComparison.js StringGetOwnProperty.js SymbolDescriptiveString.js TestIntegrityLevel.js TimeClip.js TimeFromYear.js TimeWithinDay.js ToBoolean.js ToDateString.js ToIndex.js ToInt16.js ToInt32.js ToInt8.js ToInteger.js ToLength.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToPropertyKey.js ToString.js ToUint16.js ToUint32.js ToUint8.js ToUint8Clamp.js Type.js UTF16Encoding.js ValidateAndApplyPropertyDescriptor.js WeekDay.js YearFromTime.js abs.js floor.js modulo.js msFromTime.js thisBooleanValue.js thisNumberValue.js thisStringValue.js thisTimeValue.js 2018 AbstractEqualityComparison.js AbstractRelationalComparison.js AdvanceStringIndex.js ArrayCreate.js ArraySetLength.js ArraySpeciesCreate.js Call.js CanonicalNumericIndexString.js CompletePropertyDescriptor.js CopyDataProperties.js CreateDataProperty.js CreateDataPropertyOrThrow.js CreateHTML.js CreateIterResultObject.js CreateListFromArrayLike.js CreateMethodProperty.js DateFromTime.js DateString.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js DefinePropertyOrThrow.js DeletePropertyOrThrow.js EnumerableOwnPropertyNames.js FromPropertyDescriptor.js Get.js GetIterator.js GetMethod.js GetOwnPropertyKeys.js GetPrototypeFromConstructor.js GetSubstitution.js GetV.js HasOwnProperty.js HasProperty.js HourFromTime.js InLeapYear.js InstanceofOperator.js Invoke.js IsAccessorDescriptor.js IsArray.js IsCallable.js IsConcatSpreadable.js IsConstructor.js IsDataDescriptor.js IsExtensible.js IsGenericDescriptor.js IsInteger.js IsPromise.js IsPropertyKey.js IsRegExp.js IsStringPrefix.js IterableToList.js IteratorClose.js IteratorComplete.js IteratorNext.js IteratorStep.js IteratorValue.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js NumberToString.js ObjectCreate.js OrdinaryCreateFromConstructor.js OrdinaryDefineOwnProperty.js OrdinaryGetOwnProperty.js OrdinaryGetPrototypeOf.js OrdinaryHasInstance.js OrdinaryHasProperty.js OrdinarySetPrototypeOf.js PromiseResolve.js QuoteJSONString.js RegExpExec.js RequireObjectCoercible.js SameValue.js SameValueNonNumber.js SameValueZero.js SecFromTime.js Set.js SetFunctionLength.js SetFunctionName.js SetIntegrityLevel.js SpeciesConstructor.js StrictEqualityComparison.js StringGetOwnProperty.js SymbolDescriptiveString.js TestIntegrityLevel.js TimeClip.js TimeFromYear.js TimeString.js TimeWithinDay.js ToBoolean.js ToDateString.js ToIndex.js ToInt16.js ToInt32.js ToInt8.js ToInteger.js ToLength.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToPropertyKey.js ToString.js ToUint16.js ToUint32.js ToUint8.js ToUint8Clamp.js Type.js UTF16Encoding.js UnicodeEscape.js ValidateAndApplyPropertyDescriptor.js WeekDay.js YearFromTime.js abs.js floor.js modulo.js msFromTime.js thisBooleanValue.js thisNumberValue.js thisStringValue.js thisSymbolValue.js thisTimeValue.js 2019 AbstractEqualityComparison.js AbstractRelationalComparison.js AddEntriesFromIterable.js AdvanceStringIndex.js ArrayCreate.js ArraySetLength.js ArraySpeciesCreate.js Call.js CanonicalNumericIndexString.js CompletePropertyDescriptor.js CopyDataProperties.js CreateDataProperty.js CreateDataPropertyOrThrow.js CreateHTML.js CreateIterResultObject.js CreateListFromArrayLike.js CreateMethodProperty.js DateFromTime.js DateString.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js DefinePropertyOrThrow.js DeletePropertyOrThrow.js EnumerableOwnPropertyNames.js FlattenIntoArray.js FromPropertyDescriptor.js Get.js GetIterator.js GetMethod.js GetOwnPropertyKeys.js GetPrototypeFromConstructor.js GetSubstitution.js GetV.js HasOwnProperty.js HasProperty.js HourFromTime.js InLeapYear.js InstanceofOperator.js Invoke.js IsAccessorDescriptor.js IsArray.js IsCallable.js IsConcatSpreadable.js IsConstructor.js IsDataDescriptor.js IsExtensible.js IsGenericDescriptor.js IsInteger.js IsPromise.js IsPropertyKey.js IsRegExp.js IsStringPrefix.js IterableToList.js IteratorClose.js IteratorComplete.js IteratorNext.js IteratorStep.js IteratorValue.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js NumberToString.js ObjectCreate.js OrdinaryCreateFromConstructor.js OrdinaryDefineOwnProperty.js OrdinaryGetOwnProperty.js OrdinaryGetPrototypeOf.js OrdinaryHasInstance.js OrdinaryHasProperty.js OrdinarySetPrototypeOf.js PromiseResolve.js QuoteJSONString.js RegExpExec.js RequireObjectCoercible.js SameValue.js SameValueNonNumber.js SameValueZero.js SecFromTime.js Set.js SetFunctionLength.js SetFunctionName.js SetIntegrityLevel.js SpeciesConstructor.js StrictEqualityComparison.js StringGetOwnProperty.js SymbolDescriptiveString.js TestIntegrityLevel.js TimeClip.js TimeFromYear.js TimeString.js TimeWithinDay.js ToBoolean.js ToDateString.js ToIndex.js ToInt16.js ToInt32.js ToInt8.js ToInteger.js ToLength.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToPropertyKey.js ToString.js ToUint16.js ToUint32.js ToUint8.js ToUint8Clamp.js TrimString.js Type.js UTF16Encoding.js UnicodeEscape.js ValidateAndApplyPropertyDescriptor.js WeekDay.js YearFromTime.js abs.js floor.js modulo.js msFromTime.js thisBooleanValue.js thisNumberValue.js thisStringValue.js thisSymbolValue.js thisTimeValue.js 2020 AbstractEqualityComparison.js AbstractRelationalComparison.js AddEntriesFromIterable.js AdvanceStringIndex.js ArrayCreate.js ArraySetLength.js ArraySpeciesCreate.js BigIntBitwiseOp.js BinaryAnd.js BinaryOr.js BinaryXor.js Call.js CanonicalNumericIndexString.js CodePointAt.js CompletePropertyDescriptor.js CopyDataProperties.js CreateDataProperty.js CreateDataPropertyOrThrow.js CreateHTML.js CreateIterResultObject.js CreateListFromArrayLike.js CreateMethodProperty.js DateFromTime.js DateString.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js DefinePropertyOrThrow.js DeletePropertyOrThrow.js EnumerableOwnPropertyNames.js FlattenIntoArray.js FromPropertyDescriptor.js Get.js GetIterator.js GetMethod.js GetOwnPropertyKeys.js GetPrototypeFromConstructor.js GetSubstitution.js GetV.js HasOwnProperty.js HasProperty.js HourFromTime.js InLeapYear.js InstanceofOperator.js Invoke.js IsAccessorDescriptor.js IsArray.js IsBigIntElementType.js IsCallable.js IsConcatSpreadable.js IsConstructor.js IsDataDescriptor.js IsExtensible.js IsGenericDescriptor.js IsInteger.js IsNoTearConfiguration.js IsNonNegativeInteger.js IsPromise.js IsPropertyKey.js IsRegExp.js IsStringPrefix.js IsUnclampedIntegerElementType.js IsUnsignedElementType.js IterableToList.js IteratorClose.js IteratorComplete.js IteratorNext.js IteratorStep.js IteratorValue.js LengthOfArrayLike.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js NumberBitwiseOp.js OrdinaryCreateFromConstructor.js OrdinaryDefineOwnProperty.js OrdinaryGetOwnProperty.js OrdinaryGetPrototypeOf.js OrdinaryHasInstance.js OrdinaryHasProperty.js OrdinaryObjectCreate.js OrdinarySetPrototypeOf.js PromiseResolve.js QuoteJSONString.js RegExpExec.js RequireObjectCoercible.js SameValue.js SameValueNonNumeric.js SameValueZero.js SecFromTime.js Set.js SetFunctionLength.js SetFunctionName.js SetIntegrityLevel.js SpeciesConstructor.js StrictEqualityComparison.js StringGetOwnProperty.js StringPad.js SymbolDescriptiveString.js TestIntegrityLevel.js TimeClip.js TimeFromYear.js TimeString.js TimeWithinDay.js ToBoolean.js ToDateString.js ToIndex.js ToInt16.js ToInt32.js ToInt8.js ToInteger.js ToLength.js ToNumber.js ToNumeric.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToPropertyKey.js ToString.js ToUint16.js ToUint32.js ToUint8.js ToUint8Clamp.js TrimString.js Type.js UTF16DecodeString.js UTF16DecodeSurrogatePair.js UTF16Encoding.js UnicodeEscape.js ValidateAndApplyPropertyDescriptor.js WeekDay.js YearFromTime.js abs.js floor.js modulo.js msFromTime.js thisBigIntValue.js thisBooleanValue.js thisNumberValue.js thisStringValue.js thisSymbolValue.js thisTimeValue.js 5 AbstractEqualityComparison.js AbstractRelationalComparison.js CheckObjectCoercible.js DateFromTime.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js FromPropertyDescriptor.js HourFromTime.js InLeapYear.js IsAccessorDescriptor.js IsCallable.js IsDataDescriptor.js IsGenericDescriptor.js IsPropertyDescriptor.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js SameValue.js SecFromTime.js StrictEqualityComparison.js TimeClip.js TimeFromYear.js TimeWithinDay.js ToBoolean.js ToInt32.js ToInteger.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToString.js ToUint16.js ToUint32.js Type.js WeekDay.js YearFromTime.js abs.js floor.js modulo.js msFromTime.js CHANGELOG.md GetIntrinsic.js README.md es2015.js es2016.js es2017.js es2018.js es2019.js es2020.js es5.js es6.js es7.js helpers DefineOwnProperty.js OwnPropertyKeys.js assertRecord.js assign.js callBind.js callBound.js every.js forEach.js getInferredName.js getIteratorMethod.js getOwnPropertyDescriptor.js getProto.js getSymbolDescription.js isFinite.js isLeadingSurrogate.js isNaN.js isPrefixOf.js isPrimitive.js isPropertyDescriptor.js isSamePropertyDescriptor.js isTrailingSurrogate.js maxSafeInteger.js mod.js padTimeComponent.js regexTester.js setProto.js sign.js timeConstants.js index.js operations 2015.js 2016.js 2017.js 2018.js 2019.js package.json test GetIntrinsic.js diffOps.js es2015.js es2016.js es2017.js es2018.js es2019.js es2020.js es5.js es6.js es7.js helpers OwnPropertyKeys.js assertRecord.js createBoundESNamespace.js defineProperty.js getSymbolDescription.js runManifestTest.js values.js index.js tests.js es-to-primitive .github FUNDING.yml .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 es6-promise CHANGELOG.md README.md auto.js dist es6-promise.auto.js es6-promise.auto.min.js es6-promise.js es6-promise.min.js es6-promise.d.ts lib es6-promise.auto.js es6-promise.js es6-promise -internal.js asap.js enumerator.js polyfill.js promise.js promise all.js race.js reject.js resolve.js then.js utils.js package.json es6-promisify README.md dist promise.js promisify.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-html Readme.md index.js package.json escape-string-regexp index.js package.json readme.md escodegen README.md bin escodegen.js esgenerate.js escodegen.js package.json esprima README.md bin esparse.js esvalidate.js dist esprima.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 etag HISTORY.md README.md index.js package.json 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 evp_bytestokey README.md index.js package.json exec-sh .travis.yml README.md example example.js lib exec-sh.js package.json test exec-sh.js execa index.js lib errname.js stdio.js node_modules cross-spawn CHANGELOG.md README.md index.js lib enoent.js parse.js util escape.js readShebang.js resolveCommand.js package.json path-key index.js package.json readme.md semver CHANGELOG.md README.md package.json semver.js shebang-command index.js package.json readme.md shebang-regex index.js package.json readme.md which CHANGELOG.md README.md package.json which.js package.json readme.md exit .travis.yml Gruntfile.js README.md lib exit.js package.json test exit_test.js fixtures 10-stderr.txt 10-stdout-stderr.txt 10-stdout.txt 100-stderr.txt 100-stdout-stderr.txt 100-stdout.txt 1000-stderr.txt 1000-stdout-stderr.txt 1000-stdout.txt create-files.sh log-broken.js log.js expand-brackets README.md changelog.md index.js lib compilers.js parsers.js utils.js node_modules 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 define-property README.md index.js package.json extend-shallow README.md index.js package.json ms index.js license.md package.json readme.md package.json expand-template .travis.yml README.md index.js package.json test.js expect README.md build asymmetricMatchers.d.ts asymmetricMatchers.js extractExpectedAssertionsErrors.d.ts extractExpectedAssertionsErrors.js fakeChalk.d.ts fakeChalk.js index.d.ts index.js jasmineUtils.d.ts jasmineUtils.js jestMatchersObject.d.ts jestMatchersObject.js matchers.d.ts matchers.js print.d.ts print.js spyMatchers.d.ts spyMatchers.js toThrowMatchers.d.ts toThrowMatchers.js types.d.ts types.js utils.d.ts utils.js 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 falafel .github workflows ci.yml example array.js keyword.js prompt.js index.js node_modules isarray README.md index.js package.json package.json test array.js async.js bin run.js custom-parser.js es6.js for.js inspect.js opts.js parent.js 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-glob README.md index.d.ts index.js node_modules 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 fill-range README.md index.js node_modules extend-shallow README.md index.js package.json package.json glob-parent README.md index.js node_modules is-glob README.md index.js package.json package.json is-number README.md index.js node_modules kind-of README.md index.js package.json package.json micromatch CHANGELOG.md README.md index.js lib cache.js compilers.js parsers.js utils.js package.json to-regex-range README.md index.js package.json out adapters fs-stream.d.ts fs-stream.js fs-sync.d.ts fs-sync.js fs.d.ts fs.js index.d.ts index.js managers options.d.ts options.js tasks.d.ts tasks.js providers filters deep.d.ts deep.js entry.d.ts entry.js reader-async.d.ts reader-async.js reader-stream.d.ts reader-stream.js reader-sync.d.ts reader-sync.js reader.d.ts reader.js types entries.d.ts entries.js patterns.d.ts patterns.js utils array.d.ts array.js path.d.ts path.js pattern.d.ts pattern.js stream.d.ts stream.js package.json package out adapters fs-stream.d.ts fs-stream.js fs-sync.d.ts fs-sync.js fs.d.ts fs.js index.d.ts index.js managers options.d.ts options.js tasks.d.ts tasks.js providers filters deep.d.ts deep.js entry.d.ts entry.js reader-async.d.ts reader-async.js reader-stream.d.ts reader-stream.js reader-sync.d.ts reader-sync.js reader.d.ts reader.js types entries.d.ts entries.js patterns.d.ts patterns.js utils array.d.ts array.js path.d.ts path.js pattern.d.ts pattern.js stream.d.ts stream.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 fastparse README.md lib Parser.js package.json fb-watchman README.md index.js package.json file-uri-to-path .travis.yml History.md README.md index.d.ts index.js package.json test test.js tests.json filename-reserved-regex index.js package.json readme.md filenamify-url index.js package.json readme.md filenamify index.js package.json readme.md filesize README.md lib filesize.es6.js filesize.js package.json fill-range README.md index.js package.json find-cache-dir index.js package.json readme.md find-up index.d.ts 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 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 for-in README.md index.js package.json foreach Readme.md component.json index.js package.json test.js forever-agent README.md index.js package.json form-data README.md lib browser.js form_data.js populate.js package.json fragment-cache README.md index.js package.json fresh HISTORY.md README.md index.js package.json fs-constants README.md browser.js index.js package.json fs-extra CHANGELOG.md README.md lib copy-sync copy-sync.js index.js copy 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 mkdirs-sync.js mkdirs.js win32.js move-sync index.js move-sync.js move index.js move.js output index.js path-exists index.js remove index.js rimraf.js util buffer.js stat.js utimes.js 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 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-package-type CHANGELOG.md README.md package.json get-port 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 gh-pages bin gh-pages-clean.js gh-pages.js changelog.md lib git.js index.js util.js node_modules commander CHANGELOG.md Readme.md index.js package.json typings index.d.ts 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 README.md index.js package.json glob-to-regexp .travis.yml README.md index.js package.json test.js glob README.md changelog.md common.js glob.js package.json sync.js global-dirs index.d.ts index.js package.json readme.md globals globals.json index.js package.json readme.md globby 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 grapheme-breaker README.md package.json src GraphemeBreaker.coffee GraphemeBreaker.js classes.json generate_data.coffee generate_data.js test GraphemeBreakTest.txt GraphemeBreaker.coffee growly HISTORY.md README.md example bakery.js simple.js lib gntp.js growly.js package.json 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.d.ts index.js package.json readme.md has-symbols .github FUNDING.yml workflows rebase.yml .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 is-number README.md index.js node_modules kind-of README.md index.js package.json package.json kind-of README.md index.js package.json 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 node_modules 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 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 hasurl README.md index.js package.json hex-color-regex .travis.yml CHANGELOG.md CONTRIBUTING.md LICENSE.md README.md index.js package.json test.js hmac-drbg .travis.yml README.md lib hmac-drbg.js package.json test drbg-test.js fixtures hmac-drbg-nist.json 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 hsl-regex .travis.yml LICENSE.md README.md index.js package.json test test.js hsla-regex .travis.yml LICENSE.md README.md index.js package.json test test.js html-comment-regex README.md index.js package.json html-encoding-sniffer LICENSE.txt README.md lib html-encoding-sniffer.js package.json html-escaper LICENSE.txt README.md cjs index.js package.json esm index.js index.js min.js package.json test index.js package.json html-tags html-tags.json index.js package.json readme.md htmlnano CHANGELOG.md LICENSE.txt README.md github.html index.js lib helpers.js htmlnano.js modules collapseAttributeWhitespace.js collapseBooleanAttributes.js collapseWhitespace.js custom.js deduplicateAttributeValues.js mergeScripts.js mergeStyles.js minifyCss.js minifyJs.js minifyJson.js minifySvg.js removeComments.js removeEmptyAttributes.js removeRedundantAttributes.js removeUnusedCss.js presets ampSafe.js max.js safe.js node_modules commander CHANGELOG.md Readme.md index.js package.json typings index.d.ts posthtml-parser .travis.yml .vscode launch.json README.md changelog.md coverage base.css coverage.json index.html lcov-report base.css index.html posthtml-parser index.html index.js.html prettify.css prettify.js sorter.js posthtml-parser index.html index.js.html prettify.css prettify.js sorter.js index.d.ts index.js package.json posthtml CHANGELOG.md README.md lib api.js index.js package.json types posthtml.d.ts terser CHANGELOG.md PATRONS.md README.md dist bundle.min.js package.json tools colorless-console.js domprops.js exit.js node.js props.html terser.d.ts package.json test.js htmlparser2 README.md lib CollectingHandler.js FeedHandler.js Parser.js ProxyHandler.js Stream.js Tokenizer.js WritableStream.js index.js node_modules 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 package.json 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 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 https-proxy-agent .eslintrc.js History.md README.md index.d.ts 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 package.json human-signals CHANGELOG.md README.md build src core.js main.js realtime.js signals.js package.json humanize-url index.js package.json readme.md 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 icss-replace-symbols README.md lib index.js package.json ieee754 README.md index.js package.json ignore-by-default README.md index.js package.json import-fresh index.js node_modules resolve-from index.js package.json readme.md package.json readme.md import-lazy index.js package.json readme.md import-local fixtures cli.js index.js package.json readme.md imurmurhash README.md imurmurhash.js imurmurhash.min.js package.json indexes-of README.md index.js package.json test.js inflight README.md inflight.js package.json inherits README.md inherits.js inherits_browser.js package.json ini README.md ini.js package.json invariant CHANGELOG.md README.md browser.js invariant.js package.json ip-regex index.js package.json readme.md is-absolute-url index.js package.json readme.md 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.d.ts index.js package.json readme.md is-buffer README.md index.js package.json test basic.js is-callable .github FUNDING.yml workflows rebase.yml .istanbul.yml .travis.yml CHANGELOG.md README.md index.js package.json test index.js is-ci CHANGELOG.md README.md bin.js index.js package.json is-color-stop .travis.yml HISTORY.md README.md index.js lib isCSSColorName.js isCSSLengthUnit.js isHSL.js isHSLA.js isHex.js isRGB.js isRGBA.js isStop.js isTransparent.js package.json test index.test.js unit.test.js util unit.js is-data-descriptor README.md index.js node_modules kind-of README.md index.js package.json package.json is-date-object .github FUNDING.yml workflows rebase.yml .jscs.json .travis.yml CHANGELOG.md README.md index.js package.json test index.js is-descriptor README.md index.js node_modules kind-of README.md index.js package.json package.json is-directory README.md index.js package.json is-docker cli.js index.d.ts index.js package.json readme.md is-extendable README.md index.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-generator-fn index.d.ts index.js package.json readme.md is-glob README.md index.js package.json is-html index.js package.json readme.md is-installed-globally index.d.ts index.js package.json readme.md is-negative-zero .jscs.json .travis.yml README.md index.js package.json test.js 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-plain-obj index.js package.json readme.md is-plain-object README.md index.d.ts index.js package.json is-potential-custom-element-name LICENSE-MIT.txt index.js package.json is-regex .github workflows rebase.yml .travis.yml CHANGELOG.md README.md index.js package.json test index.js is-resolvable README.md index.js package.json is-stream index.js package.json readme.md is-svg index.js package.json readme.md is-symbol .github FUNDING.yml workflows rebase.yml .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-url .travis.yml History.md Readme.md index.js package.json test index.js is-windows README.md index.js package.json 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.js package.json tests.js 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 istanbul-lib-coverage CHANGELOG.md README.md index.js lib coverage-map.js coverage-summary.js data-properties.js file-coverage.js percent.js package.json istanbul-lib-instrument CHANGELOG.md README.md dist constants.js index.js instrumenter.js read-coverage.js source-coverage.js visitor.js package.json istanbul-lib-report CHANGELOG.md README.md index.js lib context.js file-writer.js path.js report-base.js summarizer-factory.js tree.js watermarks.js xml-writer.js package.json istanbul-lib-source-maps CHANGELOG.md README.md index.js lib get-mapping.js map-store.js mapped.js pathutils.js transform-utils.js transformer.js package.json istanbul-reports CHANGELOG.md README.md index.js lib clover index.js cobertura index.js html-spa assets bundle.js spa.css index.js src fileBreadcrumbs.js filterToggle.js flattenToggle.js getChildData.js index.js routing.js summaryHeader.js summaryTableHeader.js summaryTableLine.js webpack.config.js html annotator.js assets base.css block-navigation.js sorter.js vendor prettify.css prettify.js index.js insertion-text.js json-summary index.js json index.js lcov index.js lcovonly index.js none index.js teamcity index.js text-lcov index.js text-summary index.js text index.js package.json jest-changed-files README.md build git.d.ts git.js hg.d.ts hg.js index.d.ts index.js types.d.ts types.js node_modules execa index.d.ts index.js lib command.js error.js kill.js promise.js stdio.js stream.js package.json readme.md get-stream buffer-stream.js index.d.ts index.js package.json readme.md is-stream index.d.ts index.js package.json readme.md npm-run-path index.d.ts index.js package.json readme.md package.json jest-config build Defaults.d.ts Defaults.js Deprecated.d.ts Deprecated.js Descriptions.d.ts Descriptions.js ReporterValidationErrors.d.ts ReporterValidationErrors.js ValidConfig.d.ts ValidConfig.js color.d.ts color.js constants.d.ts constants.js getCacheDirectory.d.ts getCacheDirectory.js getMaxWorkers.d.ts getMaxWorkers.js index.d.ts index.js normalize.d.ts normalize.js readConfigFileAndSetRootDir.d.ts readConfigFileAndSetRootDir.js resolveConfigPath.d.ts resolveConfigPath.js setFromArgv.d.ts setFromArgv.js utils.d.ts utils.js validatePattern.d.ts validatePattern.js vendor jsonlint.js package.json jest-diff README.md build cleanupSemantic.d.ts cleanupSemantic.js constants.d.ts constants.js diffLines.d.ts diffLines.js diffStrings.d.ts diffStrings.js getAlignedDiffs.d.ts getAlignedDiffs.js index.d.ts index.js joinAlignedDiffs.d.ts joinAlignedDiffs.js normalizeDiffOptions.d.ts normalizeDiffOptions.js printDiffs.d.ts printDiffs.js types.d.ts types.js package.json jest-docblock README.md build index.d.ts index.js package.json jest-each README.md build bind.d.ts bind.js index.d.ts index.js table array.d.ts array.js template.d.ts template.js validation.d.ts validation.js package.json jest-environment-jsdom build index.d.ts index.js package.json jest-environment-node build index.d.ts index.js package.json jest-get-type build index.d.ts index.js package.json jest-haste-map build HasteFS.d.ts HasteFS.js ModuleMap.d.ts ModuleMap.js blacklist.d.ts blacklist.js constants.d.ts constants.js crawlers node.d.ts node.js watchman.d.ts watchman.js getMockName.d.ts getMockName.js index.d.ts index.js lib FSEventsWatcher.d.ts FSEventsWatcher.js WatchmanWatcher.js dependencyExtractor.d.ts dependencyExtractor.js fast_path.d.ts fast_path.js getPlatformExtension.d.ts getPlatformExtension.js isRegExpSupported.d.ts isRegExpSupported.js normalizePathSep.d.ts normalizePathSep.js types.d.ts types.js worker.d.ts worker.js package.json jest-jasmine2 build ExpectationFailed.d.ts ExpectationFailed.js PCancelable.d.ts PCancelable.js assertionErrorMessage.d.ts assertionErrorMessage.js each.d.ts each.js errorOnPrivate.d.ts errorOnPrivate.js expectationResultFactory.d.ts expectationResultFactory.js index.d.ts index.js isError.d.ts isError.js jasmine CallTracker.d.ts CallTracker.js Env.d.ts Env.js JsApiReporter.d.ts JsApiReporter.js ReportDispatcher.d.ts ReportDispatcher.js Spec.d.ts Spec.js SpyStrategy.d.ts SpyStrategy.js Suite.d.ts Suite.js Timer.d.ts Timer.js createSpy.d.ts createSpy.js jasmineLight.d.ts jasmineLight.js spyRegistry.d.ts spyRegistry.js jasmineAsyncInstall.d.ts jasmineAsyncInstall.js jestExpect.d.ts jestExpect.js pTimeout.d.ts pTimeout.js queueRunner.d.ts queueRunner.js reporter.d.ts reporter.js setup_jest_globals.d.ts setup_jest_globals.js treeProcessor.d.ts treeProcessor.js types.d.ts types.js package.json jest-leak-detector README.md build index.d.ts index.js package.json jest-matcher-utils build Replaceable.d.ts Replaceable.js deepCyclicCopyReplaceable.d.ts deepCyclicCopyReplaceable.js 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-pnp-resolver README.md createRequire.js getDefaultResolver.js index.d.ts index.js package.json jest-regex-util build index.d.ts index.js package.json jest-resolve-dependencies build index.d.ts index.js package.json jest-resolve build ModuleNotFoundError.d.ts ModuleNotFoundError.js defaultResolver.d.ts defaultResolver.js index.d.ts index.js isBuiltinModule.d.ts isBuiltinModule.js nodeModulesPaths.d.ts nodeModulesPaths.js shouldLoadAsEsm.d.ts shouldLoadAsEsm.js types.d.ts types.js package.json jest-runner build index.d.ts index.js runTest.d.ts runTest.js testWorker.d.ts testWorker.js types.d.ts types.js package.json jest-runtime bin jest-runtime.js build cli args.d.ts args.js index.d.ts index.js helpers.d.ts helpers.js index.d.ts index.js types.d.ts types.js version.d.ts version.js package.json jest-serializer README.md build index.d.ts index.js package.json v8.d.ts jest-snapshot build State.d.ts State.js colors.d.ts colors.js dedentLines.d.ts dedentLines.js index.d.ts index.js inline_snapshots.d.ts inline_snapshots.js mock_serializer.d.ts mock_serializer.js plugins.d.ts plugins.js printSnapshot.d.ts printSnapshot.js snapshot_resolver.d.ts snapshot_resolver.js types.d.ts types.js utils.d.ts utils.js node_modules 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 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 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 setGlobal.d.ts setGlobal.js specialChars.d.ts specialChars.js testPathPatternToRegExp.d.ts testPathPatternToRegExp.js tryRealpath.d.ts tryRealpath.js package.json jest-validate README.md build condition.d.ts condition.js defaultConfig.d.ts defaultConfig.js deprecated.d.ts deprecated.js errors.d.ts errors.js exampleConfig.d.ts exampleConfig.js index.d.ts index.js types.d.ts types.js utils.d.ts utils.js validate.d.ts validate.js validateCLIOptions.d.ts validateCLIOptions.js warnings.d.ts warnings.js node_modules camelcase index.d.ts index.js package.json readme.md package.json jest-watcher build BaseWatchPlugin.d.ts BaseWatchPlugin.js JestHooks.d.ts JestHooks.js PatternPrompt.d.ts PatternPrompt.js constants.d.ts constants.js index.d.ts index.js lib Prompt.d.ts Prompt.js colorize.d.ts colorize.js formatTestNameByPattern.d.ts formatTestNameByPattern.js patternModeHelpers.d.ts patternModeHelpers.js scroll.d.ts scroll.js types.d.ts types.js package.json jest-worker README.md build Farm.d.ts Farm.js WorkerPool.d.ts WorkerPool.js base BaseWorkerPool.d.ts BaseWorkerPool.js index.d.ts index.js types.d.ts types.js workers ChildProcessWorker.d.ts ChildProcessWorker.js NodeThreadsWorker.d.ts NodeThreadsWorker.js messageParent.d.ts messageParent.js processChild.d.ts processChild.js threadChild.d.ts threadChild.js package.json jest README.md bin jest.js build jest.d.ts jest.js node_modules jest-cli README.md bin jest.js build cli args.d.ts args.js index.d.ts index.js index.d.ts index.js init errors.d.ts errors.js generate_config_file.d.ts generate_config_file.js index.d.ts index.js modify_package_json.d.ts modify_package_json.js questions.d.ts questions.js types.d.ts types.js package.json package.json js-base64 LICENSE.md README.md base64.d.ts base64.js package.json 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 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 jsbn README.md example.html example.js index.js package.json jsdom Changelog.md LICENSE.txt README.md lib api.js jsdom browser Window.js default-stylesheet.js js-globals.json not-implemented.js parser html.js index.js xml.js resources async-resource-queue.js no-op-resource-loader.js per-document-resource-loader.js request-manager.js resource-loader.js resource-queue.js level2 style.js level3 xpath.js living aborting AbortController-impl.js AbortSignal-impl.js attributes.js attributes Attr-impl.js NamedNodeMap-impl.js constraint-validation DefaultConstraintValidation-impl.js ValidityState-impl.js cssom StyleSheetList-impl.js custom-elements CustomElementRegistry-impl.js documents.js domparsing DOMParser-impl.js XMLSerializer-impl.js parse5-adapter-serialization.js serialization.js events CloseEvent-impl.js CompositionEvent-impl.js CustomEvent-impl.js ErrorEvent-impl.js Event-impl.js EventModifierMixin-impl.js EventTarget-impl.js FocusEvent-impl.js HashChangeEvent-impl.js InputEvent-impl.js KeyboardEvent-impl.js MessageEvent-impl.js MouseEvent-impl.js PageTransitionEvent-impl.js PopStateEvent-impl.js ProgressEvent-impl.js StorageEvent-impl.js TouchEvent-impl.js UIEvent-impl.js WheelEvent-impl.js fetch Headers-impl.js header-list.js header-types.js file-api Blob-impl.js File-impl.js FileList-impl.js FileReader-impl.js generated AbortController.js AbortSignal.js AbstractRange.js AddEventListenerOptions.js AssignedNodesOptions.js Attr.js BarProp.js BinaryType.js Blob.js BlobPropertyBag.js CDATASection.js CanPlayTypeResult.js CharacterData.js CloseEvent.js CloseEventInit.js Comment.js CompositionEvent.js CompositionEventInit.js CustomElementRegistry.js CustomEvent.js CustomEventInit.js DOMImplementation.js DOMParser.js DOMStringMap.js DOMTokenList.js Document.js DocumentFragment.js DocumentReadyState.js DocumentType.js Element.js ElementCreationOptions.js ElementDefinitionOptions.js EndingType.js ErrorEvent.js ErrorEventInit.js Event.js EventInit.js EventListener.js EventListenerOptions.js EventModifierInit.js EventTarget.js External.js File.js FileList.js FilePropertyBag.js FileReader.js FocusEvent.js FocusEventInit.js FormData.js GetRootNodeOptions.js HTMLAnchorElement.js HTMLAreaElement.js HTMLAudioElement.js HTMLBRElement.js HTMLBaseElement.js HTMLBodyElement.js HTMLButtonElement.js HTMLCanvasElement.js HTMLCollection.js HTMLDListElement.js HTMLDataElement.js HTMLDataListElement.js HTMLDetailsElement.js HTMLDialogElement.js HTMLDirectoryElement.js HTMLDivElement.js HTMLElement.js HTMLEmbedElement.js HTMLFieldSetElement.js HTMLFontElement.js HTMLFormElement.js HTMLFrameElement.js HTMLFrameSetElement.js HTMLHRElement.js HTMLHeadElement.js HTMLHeadingElement.js HTMLHtmlElement.js HTMLIFrameElement.js HTMLImageElement.js HTMLInputElement.js HTMLLIElement.js HTMLLabelElement.js HTMLLegendElement.js HTMLLinkElement.js HTMLMapElement.js HTMLMarqueeElement.js HTMLMediaElement.js HTMLMenuElement.js HTMLMetaElement.js HTMLMeterElement.js HTMLModElement.js HTMLOListElement.js HTMLObjectElement.js HTMLOptGroupElement.js HTMLOptionElement.js HTMLOptionsCollection.js HTMLOutputElement.js HTMLParagraphElement.js HTMLParamElement.js HTMLPictureElement.js HTMLPreElement.js HTMLProgressElement.js HTMLQuoteElement.js HTMLScriptElement.js HTMLSelectElement.js HTMLSlotElement.js HTMLSourceElement.js HTMLSpanElement.js HTMLStyleElement.js HTMLTableCaptionElement.js HTMLTableCellElement.js HTMLTableColElement.js HTMLTableElement.js HTMLTableRowElement.js HTMLTableSectionElement.js HTMLTemplateElement.js HTMLTextAreaElement.js HTMLTimeElement.js HTMLTitleElement.js HTMLTrackElement.js HTMLUListElement.js HTMLUnknownElement.js HTMLVideoElement.js HashChangeEvent.js HashChangeEventInit.js Headers.js History.js InputEvent.js InputEventInit.js KeyboardEvent.js KeyboardEventInit.js Location.js MessageEvent.js MessageEventInit.js MimeType.js MimeTypeArray.js MouseEvent.js MouseEventInit.js MutationObserver.js MutationObserverInit.js MutationRecord.js NamedNodeMap.js Navigator.js Node.js NodeFilter.js NodeIterator.js NodeList.js PageTransitionEvent.js PageTransitionEventInit.js Performance.js Plugin.js PluginArray.js PopStateEvent.js PopStateEventInit.js ProcessingInstruction.js ProgressEvent.js ProgressEventInit.js Range.js SVGAnimatedString.js SVGBoundingBoxOptions.js SVGElement.js SVGGraphicsElement.js SVGNumber.js SVGSVGElement.js SVGStringList.js SVGTitleElement.js Screen.js ScrollBehavior.js ScrollIntoViewOptions.js ScrollLogicalPosition.js ScrollOptions.js ScrollRestoration.js Selection.js SelectionMode.js ShadowRoot.js ShadowRootInit.js ShadowRootMode.js StaticRange.js StaticRangeInit.js Storage.js StorageEvent.js StorageEventInit.js StyleSheetList.js SupportedType.js Text.js TextTrackKind.js TouchEvent.js TouchEventInit.js TreeWalker.js UIEvent.js UIEventInit.js ValidityState.js VisibilityState.js WebSocket.js WheelEvent.js WheelEventInit.js XMLDocument.js XMLHttpRequest.js XMLHttpRequestEventTarget.js XMLHttpRequestResponseType.js XMLHttpRequestUpload.js XMLSerializer.js utils.js helpers binary-data.js create-element.js create-event-accessor.js custom-elements.js dates-and-times.js details.js document-base-url.js events.js focusing.js form-controls.js html-constructor.js internal-constants.js json.js mutation-observers.js namespaces.js node.js number-and-date-inputs.js ordered-set.js runtime-script-errors.js selectors.js shadow-dom.js strings.js style-rules.js stylesheets.js svg basic-types.js render.js text.js traversal.js validate-names.js wrap-cookie-jar-for-request.js hr-time Performance-impl.js interfaces.js mutation-observer MutationObserver-impl.js MutationRecord-impl.js named-properties-window.js navigator MimeType-impl.js MimeTypeArray-impl.js Navigator-impl.js NavigatorConcurrentHardware-impl.js NavigatorCookies-impl.js NavigatorID-impl.js NavigatorLanguage-impl.js NavigatorOnLine-impl.js NavigatorPlugins-impl.js Plugin-impl.js PluginArray-impl.js node-document-position.js node-type.js node.js nodes CDATASection-impl.js CharacterData-impl.js ChildNode-impl.js Comment-impl.js DOMImplementation-impl.js DOMStringMap-impl.js DOMTokenList-impl.js Document-impl.js DocumentFragment-impl.js DocumentOrShadowRoot-impl.js DocumentType-impl.js Element-impl.js ElementCSSInlineStyle-impl.js ElementContentEditable-impl.js GlobalEventHandlers-impl.js HTMLAnchorElement-impl.js HTMLAreaElement-impl.js HTMLAudioElement-impl.js HTMLBRElement-impl.js HTMLBaseElement-impl.js HTMLBodyElement-impl.js HTMLButtonElement-impl.js HTMLCanvasElement-impl.js HTMLCollection-impl.js HTMLDListElement-impl.js HTMLDataElement-impl.js HTMLDataListElement-impl.js HTMLDetailsElement-impl.js HTMLDialogElement-impl.js HTMLDirectoryElement-impl.js HTMLDivElement-impl.js HTMLElement-impl.js HTMLEmbedElement-impl.js HTMLFieldSetElement-impl.js HTMLFontElement-impl.js HTMLFormElement-impl.js HTMLFrameElement-impl.js HTMLFrameSetElement-impl.js HTMLHRElement-impl.js HTMLHeadElement-impl.js HTMLHeadingElement-impl.js HTMLHtmlElement-impl.js HTMLHyperlinkElementUtils-impl.js HTMLIFrameElement-impl.js HTMLImageElement-impl.js HTMLInputElement-impl.js HTMLLIElement-impl.js HTMLLabelElement-impl.js HTMLLegendElement-impl.js HTMLLinkElement-impl.js HTMLMapElement-impl.js HTMLMarqueeElement-impl.js HTMLMediaElement-impl.js HTMLMenuElement-impl.js HTMLMetaElement-impl.js HTMLMeterElement-impl.js HTMLModElement-impl.js HTMLOListElement-impl.js HTMLObjectElement-impl.js HTMLOptGroupElement-impl.js HTMLOptionElement-impl.js HTMLOptionsCollection-impl.js HTMLOrSVGElement-impl.js HTMLOutputElement-impl.js HTMLParagraphElement-impl.js HTMLParamElement-impl.js HTMLPictureElement-impl.js HTMLPreElement-impl.js HTMLProgressElement-impl.js HTMLQuoteElement-impl.js HTMLScriptElement-impl.js HTMLSelectElement-impl.js HTMLSlotElement-impl.js HTMLSourceElement-impl.js HTMLSpanElement-impl.js HTMLStyleElement-impl.js HTMLTableCaptionElement-impl.js HTMLTableCellElement-impl.js HTMLTableColElement-impl.js HTMLTableElement-impl.js HTMLTableRowElement-impl.js HTMLTableSectionElement-impl.js HTMLTemplateElement-impl.js HTMLTextAreaElement-impl.js HTMLTimeElement-impl.js HTMLTitleElement-impl.js HTMLTrackElement-impl.js HTMLUListElement-impl.js HTMLUnknownElement-impl.js HTMLVideoElement-impl.js LinkStyle-impl.js Node-impl.js NodeList-impl.js NonDocumentTypeChildNode-impl.js NonElementParentNode-impl.js ParentNode-impl.js ProcessingInstruction-impl.js SVGElement-impl.js SVGGraphicsElement-impl.js SVGSVGElement-impl.js SVGTests-impl.js SVGTitleElement-impl.js ShadowRoot-impl.js Slotable-impl.js Text-impl.js WindowEventHandlers-impl.js XMLDocument-impl.js post-message.js range AbstractRange-impl.js Range-impl.js StaticRange-impl.js boundary-point.js selection Selection-impl.js svg SVGAnimatedString-impl.js SVGListBase.js SVGNumber-impl.js SVGStringList-impl.js traversal NodeIterator-impl.js TreeWalker-impl.js helpers.js websockets WebSocket-impl-browser.js WebSocket-impl.js webstorage Storage-impl.js window BarProp-impl.js External-impl.js History-impl.js Location-impl.js Screen-impl.js SessionHistory.js navigation.js xhr FormData-impl.js XMLHttpRequest-impl.js XMLHttpRequestEventTarget-impl.js XMLHttpRequestUpload-impl.js xhr-sync-worker.js xhr-utils.js named-properties-tracker.js utils.js virtual-console.js vm-shim.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 json-parse-even-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 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 jsonfile CHANGELOG.md README.md index.js package.json jsprim CHANGES.md CONTRIBUTING.md README.md lib jsprim.js package.json keyv README.md package.json src index.js kind-of CHANGELOG.md README.md index.js package.json kleur index.js kleur.d.ts package.json readme.md latest-version index.d.ts index.js package.json readme.md leven index.d.ts index.js package.json readme.md levenary README.md index.d.ts index.flow.js index.js package.json levn README.md lib cast.js coerce.js index.js parse-string.js parse.js package.json lines-and-columns README.md dist index.d.ts index.js package.json locate-path index.d.ts index.js package.json readme.md lodash.clone README.md index.js package.json lodash.clonedeep README.md index.js package.json lodash.memoize README.md index.js package.json lodash.sortby README.md index.js package.json lodash.uniq 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 log-symbols browser.js 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 readme.md long README.md dist long.js index.js package.json src long.js loose-envify README.md cli.js custom.js index.js loose-envify.js package.json replace.js lowercase-keys index.js package.json readme.md magic-string CHANGELOG.md 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 package.json readme.md makeerror .travis.yml lib makeerror.js package.json readme.md map-cache README.md index.js package.json map-visit README.md index.js package.json md5.js README.md index.js package.json mdn-data README.md api index.js inheritance.json inheritance.schema.json css at-rules.json at-rules.schema.json definitions.json index.js properties.json properties.schema.json readme.md selectors.json selectors.schema.json syntaxes.json syntaxes.schema.json types.json types.schema.json units.json units.schema.json index.js l10n css.json index.js package.json merge-source-map README.md 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.js package.json merge-stream README.md index.js package.json merge2 README.md index.js package.json micromatch CHANGELOG.md README.md index.js package.json miller-rabin 1.js README.md lib mr.js node_modules bn.js README.md lib bn.js package.json util genCombMulTo.js genCombMulTo10.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 CHANGELOG.md README.md cli.js mime.js package.json src build.js test.js types.json mimic-fn index.d.ts index.js package.json readme.md mimic-response index.d.ts index.js package.json readme.md 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 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 mixin-deep README.md index.js node_modules is-extendable README.md index.d.ts index.js package.json package.json mixpanel .travis.yml example.js history.md lib groups.js mixpanel-node.d.ts mixpanel-node.js people.js profile_helpers.js utils.js package.json readme.md test alias.js config.js groups.js import.js people.js send_request.js track.js utils.js mkdirp-classic README.md 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 mustache CHANGELOG.md README.md mustache.js mustache.min.js package.json 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 napi-build-utils README.md index.js index.md package.json natural-compare README.md index.js package.json ncp .travis.yml LICENSE.md README.md lib ncp.js package.json test ncp.js near-api-js .eslintrc.yml .github ISSUE_TEMPLATE bug_report.md feature_request.md workflows docs.yml .gitpod.yml .nyc_output cov.json .travis.yml CODE_OF_CONDUCT.md CONTRIBUTING.md README.md browser-exports.js dist near-api-js.js near-api-js.min.js gen_error_types.js lib account.d.ts account.js account_creator.d.ts account_creator.js browser-index.d.ts browser-index.js common-index.d.ts common-index.js connection.d.ts connection.js contract.d.ts contract.js generated rpc_error_schema.d.ts rpc_error_schema.json rpc_error_types.d.ts rpc_error_types.js 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 web.d.ts web.js validators.d.ts validators.js wallet-account.d.ts wallet-account.js package.json src .eslintrc.yml account.ts account_creator.ts browser-index.ts common-index.ts connection.ts contract.ts generated rpc_error_schema.json rpc_error_types.ts index.ts key_stores browser-index.ts browser_local_storage_key_store.ts in_memory_key_store.ts index.ts keystore.ts merge_key_store.ts unencrypted_file_system_keystore.ts near.ts providers index.ts json-rpc-provider.ts provider.ts res error_messages.json signer.ts transaction.ts utils enums.ts errors.ts exponential-backoff.ts format.ts index.ts key_pair.ts network.ts rpc_errors.ts serialize.ts web.ts validators.ts wallet-account.ts test .eslintrc.yml account.access_key.test.js account.test.js config.js contract.test.js data signed_transaction1.json transaction1.json fuzz borsh-roundtrip.js key_pair.test.js key_stores browser_keystore.test.js in_memory_keystore.test.js keystore_common.js merge_keystore.test.js unencrypted_file_system_keystore.test.js promise.test.js providers.test.js serialize.test.js signer.test.js test-utils.js transaction.test.js utils format.test.js rpc-errors.test.js validator.test.js wallet-account.test.js tsconfig.json near-cli .dependabot config.yml .eslintrc.yml .github ISSUE_TEMPLATE bug_report.md feature_request.md .gitpod.yml .travis.yml CODE_OF_CONDUCT.md CONTRIBUTING.md README.md bin near-cli.js commands add-key.js call.js create-account.js delete-key.js dev-deploy.js generate-key.js proposals.js repl.js tx-status.js validators.js config.js get-config.js index.js middleware initial-balance.js key-store.js ledger.js print-options.js seed-phrase.js package.json test index.sh test_account_creation.sh test_account_operations.sh test_contract.sh test_deploy_init_contract.sh test_generate_key.sh unit explorer.test.js inspect-response.test.js test_environment.js tmp-project neardev shared-test-staging test.near.json shared-test test.near.json utils capture-login-success.js check-version.js connect.js eventtracking.js exit-on-error.js explorer.js implicit-accountid.js inspect-response.js log-event.js settings.js validators-info.js verify-account.js near-hd-key README.md dist index.d.ts index.js utils.d.ts utils.js node_modules create-hmac README.md browser.js index.js legacy.js package.json package.json near-ledger-js demo demo.js index.html index.js package.json near-mock-vm bin bin.js 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 vm.d.ts vm.js node_modules js-base64 LICENSE.md README.md base64.js base64.min.js package.json package.json pkg near_mock_vm.d.ts near_mock_vm.js near_mock_vm_bg.d.ts package.json near-sdk-as .github ISSUE_TEMPLATE bug_report.md feature_request.md question.md workflows docs.yml test.yml .gitpod.yml README.md as-pect.config.js as_types.d.ts asconfig.json asp.asconfig.json assembly as_types.d.ts bindgen.ts index.ts sdk base58.ts base64.ts collections avlTree.ts index.ts persistentDeque.ts persistentMap.ts persistentSet.ts persistentUnorderedMap.ts persistentVector.ts util.ts contract.ts env env.ts imports.ts index.ts runtime_api.ts index.ts logging.ts math.ts near.ts promise.ts storage.ts util.ts vm context.ts index.ts outcome.ts vm.include.ts vm.ts bindgen README.md asconfig.json compiler.js dist JSONBuilder.d.ts JSONBuilder.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 compiler.js imports.js jest.config.js package.json runtime asconfig.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 package.json src bin.ts context.ts index.ts runtime.ts types.ts utils.ts near-seed-phrase .eslintrc.yml .travis.yml index.js package.json test index.test.js 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 node_modules commander CHANGELOG.md Readme.md index.js package.json typings index.d.ts semver CHANGELOG.md README.md package.json semver.js package.json nice-try CHANGELOG.md README.md package.json src index.js node-abi .github workflows update-abi.yml .travis.yml CODE_OF_CONDUCT.md CONTRIBUTING.md README.md abi_registry.json index.js node_modules semver CHANGELOG.md README.md package.json semver.js package.json scripts update-abi-registry.js test index.js node-addon-api .travis.yml CHANGELOG.md CODE_OF_CONDUCT.md CONTRIBUTING.md LICENSE.md README.md appveyor.yml doc array_buffer.md async_context.md async_operations.md async_worker.md basic_types.md bigint.md boolean.md buffer.md callback_scope.md callbackinfo.md checker-tool.md class_property_descriptor.md cmake-js.md conversion-tool.md creating_a_release.md dataview.md env.md error.md error_handling.md escapable_handle_scope.md external.md function.md function_reference.md generator.md handle_scope.md memory_management.md node-gyp.md number.md object.md object_lifetime_management.md object_reference.md object_wrap.md prebuild_tools.md promises.md property_descriptor.md range_error.md reference.md setup.md string.md symbol.md threadsafe_function.md type_error.md typed_array.md typed_array_of.md value.md version_management.md working_with_javascript_values.md external-napi node_api.h index.js napi-inl.deprecated.h napi-inl.h napi.h package.json src node_api.h node_api_types.h node_internals.h nothing.c util-inl.h util.h tools README.md check-napi.js conversion.js node-fetch CHANGELOG.md LICENSE.md README.md browser.js lib index.es.js index.js package.json 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-hid Publishing.md README.md hidapi .appveyor.yml .builds alpine.yml archlinux.yml fedora-mingw.yml freebsd.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 nwjs-old-install.sh 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-int64 Int64.js README.md package.json test.js 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 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 punycode LICENSE-MIT.txt README.md package.json punycode.js package.json node-modules-regexp index.js package.json readme.md node-notifier CHANGELOG.md README.md index.js lib checkGrowl.js utils.js node_modules 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 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 notifiers balloon.js growl.js notificationcenter.js notifysend.js toaster.js package.json node-releases .github workflows nightly-sync.yml README.md data processed envs.json raw iojs.json nodejs.json release-schedule release-schedule.json package.json nodemon .travis.yml README.md bin nodemon.js postinstall.js commitlint.config.js doc cli authors.txt config.txt help.txt logo.txt options.txt topics.txt usage.txt whoami.txt lib cli index.js parse.js config command.js defaults.js exec.js index.js load.js help index.js index.js monitor index.js match.js run.js signals.js watch.js nodemon.js rules add.js index.js parse.js spawn.js utils bus.js clone.js colour.js index.js log.js merge.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 has-flag index.js package.json readme.md semver CHANGELOG.md README.md package.json semver.js supports-color browser.js index.js package.json readme.md package.json noop-logger History.md Readme.md circle.yml lib index.js package.json test index.js nopt README.md bin nopt.js examples my-program.js lib nopt.js package.json normalize-html-whitespace README.md index-es5.js index.js package.json normalize-package-data README.md lib extract_description.js fixer.js make_warning.js normalize.js safe_format.js typos.json warning_messages.json node_modules semver CHANGELOG.md README.md package.json semver.js package.json normalize-path README.md index.js package.json normalize-url index.js package.json readme.md npm-run-path index.js node_modules path-key index.js package.json readme.md package.json readme.md npmlog CHANGELOG.md README.md log.js package.json nth-check README.md compile.js index.js package.json parse.js number-is-nan index.js package.json readme.md nwsapi README.md package.json src modules nwsapi-jquery.js nwsapi-traversal.js nwsapi.js o3 README.md index.js lib Class.js abstractMethod.js index.js package.json 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-inspect .github workflows rebase.yml .travis.yml example all.js circular.js fn.js inspect.js index.js package.json test-core-js.js test bigint.js browser dom.js circular.js deep.js element.js err.js fn.js has.js holes.js indent-option.js inspect.js lowbyte.js number.js quoteStyle.js undef.js values.js util.inspect.js 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.assign .github FUNDING.yml workflows rebase.yml require-allow-edits.yml CHANGELOG.md README.md auto.js dist browser.js hasSymbols.js implementation.js index.js package.json polyfill.js shim.js test index.js native.js ses-compat.js shimmed.js tests.js object.getownpropertydescriptors .github workflows rebase.yml .travis.yml CHANGELOG.md README.md auto.js implementation.js index.js node_modules es-abstract .github FUNDING.yml workflows codeql-analysis.yml rebase.yml .travis.yml 2015 AbstractEqualityComparison.js AbstractRelationalComparison.js AdvanceStringIndex.js ArrayCreate.js ArraySetLength.js ArraySpeciesCreate.js Call.js CanonicalNumericIndexString.js CompletePropertyDescriptor.js CreateDataProperty.js CreateDataPropertyOrThrow.js CreateHTML.js CreateIterResultObject.js CreateListFromArrayLike.js CreateMethodProperty.js DateFromTime.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js DefinePropertyOrThrow.js DeletePropertyOrThrow.js EnumerableOwnNames.js FromPropertyDescriptor.js Get.js GetIterator.js GetMethod.js GetOwnPropertyKeys.js GetPrototypeFromConstructor.js GetSubstitution.js GetV.js HasOwnProperty.js HasProperty.js HourFromTime.js InLeapYear.js InstanceofOperator.js Invoke.js IsAccessorDescriptor.js IsArray.js IsCallable.js IsConcatSpreadable.js IsConstructor.js IsDataDescriptor.js IsExtensible.js IsGenericDescriptor.js IsInteger.js IsPromise.js IsPropertyDescriptor.js IsPropertyKey.js IsRegExp.js IteratorClose.js IteratorComplete.js IteratorNext.js IteratorStep.js IteratorValue.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js ObjectCreate.js OrdinaryDefineOwnProperty.js OrdinaryGetOwnProperty.js OrdinaryHasInstance.js OrdinaryHasProperty.js RegExpExec.js RequireObjectCoercible.js SameValue.js SameValueZero.js SecFromTime.js Set.js SetFunctionName.js SetIntegrityLevel.js SpeciesConstructor.js StrictEqualityComparison.js SymbolDescriptiveString.js TestIntegrityLevel.js TimeClip.js TimeFromYear.js TimeWithinDay.js ToBoolean.js ToDateString.js ToInt16.js ToInt32.js ToInt8.js ToInteger.js ToLength.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToPropertyKey.js ToString.js ToUint16.js ToUint32.js ToUint8.js ToUint8Clamp.js Type.js ValidateAndApplyPropertyDescriptor.js WeekDay.js YearFromTime.js modulo.js msFromTime.js thisBooleanValue.js thisNumberValue.js thisStringValue.js thisTimeValue.js 2016 AbstractEqualityComparison.js AbstractRelationalComparison.js AdvanceStringIndex.js ArrayCreate.js ArraySetLength.js ArraySpeciesCreate.js Call.js CanonicalNumericIndexString.js CompletePropertyDescriptor.js CreateDataProperty.js CreateDataPropertyOrThrow.js CreateHTML.js CreateIterResultObject.js CreateListFromArrayLike.js CreateMethodProperty.js DateFromTime.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js DefinePropertyOrThrow.js DeletePropertyOrThrow.js EnumerableOwnNames.js FromPropertyDescriptor.js Get.js GetIterator.js GetMethod.js GetOwnPropertyKeys.js GetPrototypeFromConstructor.js GetSubstitution.js GetV.js HasOwnProperty.js HasProperty.js HourFromTime.js InLeapYear.js InstanceofOperator.js Invoke.js IsAccessorDescriptor.js IsArray.js IsCallable.js IsConcatSpreadable.js IsConstructor.js IsDataDescriptor.js IsExtensible.js IsGenericDescriptor.js IsInteger.js IsPromise.js IsPropertyDescriptor.js IsPropertyKey.js IsRegExp.js IterableToArrayLike.js IteratorClose.js IteratorComplete.js IteratorNext.js IteratorStep.js IteratorValue.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js ObjectCreate.js OrdinaryDefineOwnProperty.js OrdinaryGetOwnProperty.js OrdinaryGetPrototypeOf.js OrdinaryHasInstance.js OrdinaryHasProperty.js OrdinarySetPrototypeOf.js RegExpExec.js RequireObjectCoercible.js SameValue.js SameValueNonNumber.js SameValueZero.js SecFromTime.js Set.js SetFunctionName.js SetIntegrityLevel.js SpeciesConstructor.js StrictEqualityComparison.js SymbolDescriptiveString.js TestIntegrityLevel.js TimeClip.js TimeFromYear.js TimeWithinDay.js ToBoolean.js ToDateString.js ToInt16.js ToInt32.js ToInt8.js ToInteger.js ToLength.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToPropertyKey.js ToString.js ToUint16.js ToUint32.js ToUint8.js ToUint8Clamp.js Type.js ValidateAndApplyPropertyDescriptor.js WeekDay.js YearFromTime.js modulo.js msFromTime.js thisBooleanValue.js thisNumberValue.js thisStringValue.js thisTimeValue.js 2017 AbstractEqualityComparison.js AbstractRelationalComparison.js AdvanceStringIndex.js ArrayCreate.js ArraySetLength.js ArraySpeciesCreate.js Call.js CanonicalNumericIndexString.js CompletePropertyDescriptor.js CreateDataProperty.js CreateDataPropertyOrThrow.js CreateHTML.js CreateIterResultObject.js CreateListFromArrayLike.js CreateMethodProperty.js DateFromTime.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js DefinePropertyOrThrow.js DeletePropertyOrThrow.js EnumerableOwnProperties.js FromPropertyDescriptor.js Get.js GetIterator.js GetMethod.js GetOwnPropertyKeys.js GetPrototypeFromConstructor.js GetSubstitution.js GetV.js HasOwnProperty.js HasProperty.js HourFromTime.js InLeapYear.js InstanceofOperator.js Invoke.js IsAccessorDescriptor.js IsArray.js IsCallable.js IsConcatSpreadable.js IsConstructor.js IsDataDescriptor.js IsExtensible.js IsGenericDescriptor.js IsInteger.js IsPromise.js IsPropertyDescriptor.js IsPropertyKey.js IsRegExp.js IterableToList.js IteratorClose.js IteratorComplete.js IteratorNext.js IteratorStep.js IteratorValue.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js ObjectCreate.js OrdinaryDefineOwnProperty.js OrdinaryGetOwnProperty.js OrdinaryGetPrototypeOf.js OrdinaryHasInstance.js OrdinaryHasProperty.js OrdinarySetPrototypeOf.js RegExpExec.js RequireObjectCoercible.js SameValue.js SameValueNonNumber.js SameValueZero.js SecFromTime.js Set.js SetFunctionName.js SetIntegrityLevel.js SpeciesConstructor.js StrictEqualityComparison.js SymbolDescriptiveString.js TestIntegrityLevel.js TimeClip.js TimeFromYear.js TimeWithinDay.js ToBoolean.js ToDateString.js ToIndex.js ToInt16.js ToInt32.js ToInt8.js ToInteger.js ToLength.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToPropertyKey.js ToString.js ToUint16.js ToUint32.js ToUint8.js ToUint8Clamp.js Type.js ValidateAndApplyPropertyDescriptor.js WeekDay.js YearFromTime.js modulo.js msFromTime.js thisBooleanValue.js thisNumberValue.js thisStringValue.js thisTimeValue.js 2018 AbstractEqualityComparison.js AbstractRelationalComparison.js AdvanceStringIndex.js ArrayCreate.js ArraySetLength.js ArraySpeciesCreate.js Call.js CanonicalNumericIndexString.js CompletePropertyDescriptor.js CopyDataProperties.js CreateDataProperty.js CreateDataPropertyOrThrow.js CreateHTML.js CreateIterResultObject.js CreateListFromArrayLike.js CreateMethodProperty.js DateFromTime.js DateString.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js DefinePropertyOrThrow.js DeletePropertyOrThrow.js EnumerableOwnPropertyNames.js FromPropertyDescriptor.js Get.js GetIterator.js GetMethod.js GetOwnPropertyKeys.js GetPrototypeFromConstructor.js GetSubstitution.js GetV.js HasOwnProperty.js HasProperty.js HourFromTime.js InLeapYear.js InstanceofOperator.js Invoke.js IsAccessorDescriptor.js IsArray.js IsCallable.js IsConcatSpreadable.js IsConstructor.js IsDataDescriptor.js IsExtensible.js IsGenericDescriptor.js IsInteger.js IsPromise.js IsPropertyKey.js IsRegExp.js IsStringPrefix.js IterableToList.js IteratorClose.js IteratorComplete.js IteratorNext.js IteratorStep.js IteratorValue.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js NumberToString.js ObjectCreate.js OrdinaryDefineOwnProperty.js OrdinaryGetOwnProperty.js OrdinaryGetPrototypeOf.js OrdinaryHasInstance.js OrdinaryHasProperty.js OrdinarySetPrototypeOf.js PromiseResolve.js RegExpExec.js RequireObjectCoercible.js SameValue.js SameValueNonNumber.js SameValueZero.js SecFromTime.js Set.js SetFunctionName.js SetIntegrityLevel.js SpeciesConstructor.js StrictEqualityComparison.js SymbolDescriptiveString.js TestIntegrityLevel.js TimeClip.js TimeFromYear.js TimeString.js TimeWithinDay.js ToBoolean.js ToDateString.js ToIndex.js ToInt16.js ToInt32.js ToInt8.js ToInteger.js ToLength.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToPropertyKey.js ToString.js ToUint16.js ToUint32.js ToUint8.js ToUint8Clamp.js Type.js ValidateAndApplyPropertyDescriptor.js WeekDay.js YearFromTime.js modulo.js msFromTime.js thisBooleanValue.js thisNumberValue.js thisStringValue.js thisSymbolValue.js thisTimeValue.js 2019 AbstractEqualityComparison.js AbstractRelationalComparison.js AddEntriesFromIterable.js AdvanceStringIndex.js ArrayCreate.js ArraySetLength.js ArraySpeciesCreate.js Call.js CanonicalNumericIndexString.js CompletePropertyDescriptor.js CopyDataProperties.js CreateDataProperty.js CreateDataPropertyOrThrow.js CreateHTML.js CreateIterResultObject.js CreateListFromArrayLike.js CreateMethodProperty.js DateFromTime.js DateString.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js DefinePropertyOrThrow.js DeletePropertyOrThrow.js EnumerableOwnPropertyNames.js FlattenIntoArray.js FromPropertyDescriptor.js Get.js GetIterator.js GetMethod.js GetOwnPropertyKeys.js GetPrototypeFromConstructor.js GetSubstitution.js GetV.js HasOwnProperty.js HasProperty.js HourFromTime.js InLeapYear.js InstanceofOperator.js Invoke.js IsAccessorDescriptor.js IsArray.js IsCallable.js IsConcatSpreadable.js IsConstructor.js IsDataDescriptor.js IsExtensible.js IsGenericDescriptor.js IsInteger.js IsPromise.js IsPropertyKey.js IsRegExp.js IsStringPrefix.js IterableToList.js IteratorClose.js IteratorComplete.js IteratorNext.js IteratorStep.js IteratorValue.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js NumberToString.js ObjectCreate.js OrdinaryDefineOwnProperty.js OrdinaryGetOwnProperty.js OrdinaryGetPrototypeOf.js OrdinaryHasInstance.js OrdinaryHasProperty.js OrdinarySetPrototypeOf.js PromiseResolve.js RegExpExec.js RequireObjectCoercible.js SameValue.js SameValueNonNumber.js SameValueZero.js SecFromTime.js Set.js SetFunctionName.js SetIntegrityLevel.js SpeciesConstructor.js StrictEqualityComparison.js SymbolDescriptiveString.js TestIntegrityLevel.js TimeClip.js TimeFromYear.js TimeString.js TimeWithinDay.js ToBoolean.js ToDateString.js ToIndex.js ToInt16.js ToInt32.js ToInt8.js ToInteger.js ToLength.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToPropertyKey.js ToString.js ToUint16.js ToUint32.js ToUint8.js ToUint8Clamp.js TrimString.js Type.js ValidateAndApplyPropertyDescriptor.js WeekDay.js YearFromTime.js modulo.js msFromTime.js thisBooleanValue.js thisNumberValue.js thisStringValue.js thisSymbolValue.js thisTimeValue.js 5 AbstractEqualityComparison.js AbstractRelationalComparison.js CheckObjectCoercible.js DateFromTime.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js FromPropertyDescriptor.js HourFromTime.js InLeapYear.js IsAccessorDescriptor.js IsCallable.js IsDataDescriptor.js IsGenericDescriptor.js IsPropertyDescriptor.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js SameValue.js SecFromTime.js StrictEqualityComparison.js TimeClip.js TimeFromYear.js TimeWithinDay.js ToBoolean.js ToInt32.js ToInteger.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToString.js ToUint16.js ToUint32.js Type.js WeekDay.js YearFromTime.js modulo.js msFromTime.js CHANGELOG.md GetIntrinsic.js README.md es2015.js es2016.js es2017.js es2018.js es2019.js es5.js es6.js es7.js helpers DefineOwnProperty.js OwnPropertyKeys.js assertRecord.js assign.js callBind.js callBound.js every.js forEach.js getInferredName.js getIteratorMethod.js getOwnPropertyDescriptor.js getProto.js getSymbolDescription.js isFinite.js isNaN.js isPrefixOf.js isPrimitive.js isPropertyDescriptor.js isSamePropertyDescriptor.js maxSafeInteger.js mod.js padTimeComponent.js regexTester.js setProto.js sign.js timeConstants.js index.js operations 2015.js 2016.js 2017.js 2018.js 2019.js package.json test GetIntrinsic.js diffOps.js es2015.js es2016.js es2017.js es2018.js es2019.js es5.js es6.js es7.js helpers OwnPropertyKeys.js assertRecord.js createBoundESNamespace.js defineProperty.js getSymbolDescription.js runManifestTest.js values.js index.js tests.js package.json polyfill.js shim.js test index.js shimmed.js tests.js object.pick README.md index.js package.json object.values .github workflows rebase.yml .travis.yml CHANGELOG.md README.md auto.js implementation.js index.js node_modules es-abstract .github FUNDING.yml workflows codeql-analysis.yml rebase.yml .travis.yml 2015 AbstractEqualityComparison.js AbstractRelationalComparison.js AdvanceStringIndex.js ArrayCreate.js ArraySetLength.js ArraySpeciesCreate.js Call.js CanonicalNumericIndexString.js CompletePropertyDescriptor.js CreateDataProperty.js CreateDataPropertyOrThrow.js CreateHTML.js CreateIterResultObject.js CreateListFromArrayLike.js CreateMethodProperty.js DateFromTime.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js DefinePropertyOrThrow.js DeletePropertyOrThrow.js EnumerableOwnNames.js FromPropertyDescriptor.js Get.js GetIterator.js GetMethod.js GetOwnPropertyKeys.js GetPrototypeFromConstructor.js GetSubstitution.js GetV.js HasOwnProperty.js HasProperty.js HourFromTime.js InLeapYear.js InstanceofOperator.js Invoke.js IsAccessorDescriptor.js IsArray.js IsCallable.js IsConcatSpreadable.js IsConstructor.js IsDataDescriptor.js IsExtensible.js IsGenericDescriptor.js IsInteger.js IsPromise.js IsPropertyDescriptor.js IsPropertyKey.js IsRegExp.js IteratorClose.js IteratorComplete.js IteratorNext.js IteratorStep.js IteratorValue.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js ObjectCreate.js OrdinaryDefineOwnProperty.js OrdinaryGetOwnProperty.js OrdinaryHasInstance.js OrdinaryHasProperty.js RegExpExec.js RequireObjectCoercible.js SameValue.js SameValueZero.js SecFromTime.js Set.js SetFunctionName.js SetIntegrityLevel.js SpeciesConstructor.js StrictEqualityComparison.js SymbolDescriptiveString.js TestIntegrityLevel.js TimeClip.js TimeFromYear.js TimeWithinDay.js ToBoolean.js ToDateString.js ToInt16.js ToInt32.js ToInt8.js ToInteger.js ToLength.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToPropertyKey.js ToString.js ToUint16.js ToUint32.js ToUint8.js ToUint8Clamp.js Type.js ValidateAndApplyPropertyDescriptor.js WeekDay.js YearFromTime.js modulo.js msFromTime.js thisBooleanValue.js thisNumberValue.js thisStringValue.js thisTimeValue.js 2016 AbstractEqualityComparison.js AbstractRelationalComparison.js AdvanceStringIndex.js ArrayCreate.js ArraySetLength.js ArraySpeciesCreate.js Call.js CanonicalNumericIndexString.js CompletePropertyDescriptor.js CreateDataProperty.js CreateDataPropertyOrThrow.js CreateHTML.js CreateIterResultObject.js CreateListFromArrayLike.js CreateMethodProperty.js DateFromTime.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js DefinePropertyOrThrow.js DeletePropertyOrThrow.js EnumerableOwnNames.js FromPropertyDescriptor.js Get.js GetIterator.js GetMethod.js GetOwnPropertyKeys.js GetPrototypeFromConstructor.js GetSubstitution.js GetV.js HasOwnProperty.js HasProperty.js HourFromTime.js InLeapYear.js InstanceofOperator.js Invoke.js IsAccessorDescriptor.js IsArray.js IsCallable.js IsConcatSpreadable.js IsConstructor.js IsDataDescriptor.js IsExtensible.js IsGenericDescriptor.js IsInteger.js IsPromise.js IsPropertyDescriptor.js IsPropertyKey.js IsRegExp.js IterableToArrayLike.js IteratorClose.js IteratorComplete.js IteratorNext.js IteratorStep.js IteratorValue.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js ObjectCreate.js OrdinaryDefineOwnProperty.js OrdinaryGetOwnProperty.js OrdinaryGetPrototypeOf.js OrdinaryHasInstance.js OrdinaryHasProperty.js OrdinarySetPrototypeOf.js RegExpExec.js RequireObjectCoercible.js SameValue.js SameValueNonNumber.js SameValueZero.js SecFromTime.js Set.js SetFunctionName.js SetIntegrityLevel.js SpeciesConstructor.js StrictEqualityComparison.js SymbolDescriptiveString.js TestIntegrityLevel.js TimeClip.js TimeFromYear.js TimeWithinDay.js ToBoolean.js ToDateString.js ToInt16.js ToInt32.js ToInt8.js ToInteger.js ToLength.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToPropertyKey.js ToString.js ToUint16.js ToUint32.js ToUint8.js ToUint8Clamp.js Type.js ValidateAndApplyPropertyDescriptor.js WeekDay.js YearFromTime.js modulo.js msFromTime.js thisBooleanValue.js thisNumberValue.js thisStringValue.js thisTimeValue.js 2017 AbstractEqualityComparison.js AbstractRelationalComparison.js AdvanceStringIndex.js ArrayCreate.js ArraySetLength.js ArraySpeciesCreate.js Call.js CanonicalNumericIndexString.js CompletePropertyDescriptor.js CreateDataProperty.js CreateDataPropertyOrThrow.js CreateHTML.js CreateIterResultObject.js CreateListFromArrayLike.js CreateMethodProperty.js DateFromTime.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js DefinePropertyOrThrow.js DeletePropertyOrThrow.js EnumerableOwnProperties.js FromPropertyDescriptor.js Get.js GetIterator.js GetMethod.js GetOwnPropertyKeys.js GetPrototypeFromConstructor.js GetSubstitution.js GetV.js HasOwnProperty.js HasProperty.js HourFromTime.js InLeapYear.js InstanceofOperator.js Invoke.js IsAccessorDescriptor.js IsArray.js IsCallable.js IsConcatSpreadable.js IsConstructor.js IsDataDescriptor.js IsExtensible.js IsGenericDescriptor.js IsInteger.js IsPromise.js IsPropertyDescriptor.js IsPropertyKey.js IsRegExp.js IterableToList.js IteratorClose.js IteratorComplete.js IteratorNext.js IteratorStep.js IteratorValue.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js ObjectCreate.js OrdinaryDefineOwnProperty.js OrdinaryGetOwnProperty.js OrdinaryGetPrototypeOf.js OrdinaryHasInstance.js OrdinaryHasProperty.js OrdinarySetPrototypeOf.js RegExpExec.js RequireObjectCoercible.js SameValue.js SameValueNonNumber.js SameValueZero.js SecFromTime.js Set.js SetFunctionName.js SetIntegrityLevel.js SpeciesConstructor.js StrictEqualityComparison.js SymbolDescriptiveString.js TestIntegrityLevel.js TimeClip.js TimeFromYear.js TimeWithinDay.js ToBoolean.js ToDateString.js ToIndex.js ToInt16.js ToInt32.js ToInt8.js ToInteger.js ToLength.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToPropertyKey.js ToString.js ToUint16.js ToUint32.js ToUint8.js ToUint8Clamp.js Type.js ValidateAndApplyPropertyDescriptor.js WeekDay.js YearFromTime.js modulo.js msFromTime.js thisBooleanValue.js thisNumberValue.js thisStringValue.js thisTimeValue.js 2018 AbstractEqualityComparison.js AbstractRelationalComparison.js AdvanceStringIndex.js ArrayCreate.js ArraySetLength.js ArraySpeciesCreate.js Call.js CanonicalNumericIndexString.js CompletePropertyDescriptor.js CopyDataProperties.js CreateDataProperty.js CreateDataPropertyOrThrow.js CreateHTML.js CreateIterResultObject.js CreateListFromArrayLike.js CreateMethodProperty.js DateFromTime.js DateString.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js DefinePropertyOrThrow.js DeletePropertyOrThrow.js EnumerableOwnPropertyNames.js FromPropertyDescriptor.js Get.js GetIterator.js GetMethod.js GetOwnPropertyKeys.js GetPrototypeFromConstructor.js GetSubstitution.js GetV.js HasOwnProperty.js HasProperty.js HourFromTime.js InLeapYear.js InstanceofOperator.js Invoke.js IsAccessorDescriptor.js IsArray.js IsCallable.js IsConcatSpreadable.js IsConstructor.js IsDataDescriptor.js IsExtensible.js IsGenericDescriptor.js IsInteger.js IsPromise.js IsPropertyKey.js IsRegExp.js IsStringPrefix.js IterableToList.js IteratorClose.js IteratorComplete.js IteratorNext.js IteratorStep.js IteratorValue.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js NumberToString.js ObjectCreate.js OrdinaryDefineOwnProperty.js OrdinaryGetOwnProperty.js OrdinaryGetPrototypeOf.js OrdinaryHasInstance.js OrdinaryHasProperty.js OrdinarySetPrototypeOf.js PromiseResolve.js RegExpExec.js RequireObjectCoercible.js SameValue.js SameValueNonNumber.js SameValueZero.js SecFromTime.js Set.js SetFunctionName.js SetIntegrityLevel.js SpeciesConstructor.js StrictEqualityComparison.js SymbolDescriptiveString.js TestIntegrityLevel.js TimeClip.js TimeFromYear.js TimeString.js TimeWithinDay.js ToBoolean.js ToDateString.js ToIndex.js ToInt16.js ToInt32.js ToInt8.js ToInteger.js ToLength.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToPropertyKey.js ToString.js ToUint16.js ToUint32.js ToUint8.js ToUint8Clamp.js Type.js ValidateAndApplyPropertyDescriptor.js WeekDay.js YearFromTime.js modulo.js msFromTime.js thisBooleanValue.js thisNumberValue.js thisStringValue.js thisSymbolValue.js thisTimeValue.js 2019 AbstractEqualityComparison.js AbstractRelationalComparison.js AddEntriesFromIterable.js AdvanceStringIndex.js ArrayCreate.js ArraySetLength.js ArraySpeciesCreate.js Call.js CanonicalNumericIndexString.js CompletePropertyDescriptor.js CopyDataProperties.js CreateDataProperty.js CreateDataPropertyOrThrow.js CreateHTML.js CreateIterResultObject.js CreateListFromArrayLike.js CreateMethodProperty.js DateFromTime.js DateString.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js DefinePropertyOrThrow.js DeletePropertyOrThrow.js EnumerableOwnPropertyNames.js FlattenIntoArray.js FromPropertyDescriptor.js Get.js GetIterator.js GetMethod.js GetOwnPropertyKeys.js GetPrototypeFromConstructor.js GetSubstitution.js GetV.js HasOwnProperty.js HasProperty.js HourFromTime.js InLeapYear.js InstanceofOperator.js Invoke.js IsAccessorDescriptor.js IsArray.js IsCallable.js IsConcatSpreadable.js IsConstructor.js IsDataDescriptor.js IsExtensible.js IsGenericDescriptor.js IsInteger.js IsPromise.js IsPropertyKey.js IsRegExp.js IsStringPrefix.js IterableToList.js IteratorClose.js IteratorComplete.js IteratorNext.js IteratorStep.js IteratorValue.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js NumberToString.js ObjectCreate.js OrdinaryDefineOwnProperty.js OrdinaryGetOwnProperty.js OrdinaryGetPrototypeOf.js OrdinaryHasInstance.js OrdinaryHasProperty.js OrdinarySetPrototypeOf.js PromiseResolve.js RegExpExec.js RequireObjectCoercible.js SameValue.js SameValueNonNumber.js SameValueZero.js SecFromTime.js Set.js SetFunctionName.js SetIntegrityLevel.js SpeciesConstructor.js StrictEqualityComparison.js SymbolDescriptiveString.js TestIntegrityLevel.js TimeClip.js TimeFromYear.js TimeString.js TimeWithinDay.js ToBoolean.js ToDateString.js ToIndex.js ToInt16.js ToInt32.js ToInt8.js ToInteger.js ToLength.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToPropertyKey.js ToString.js ToUint16.js ToUint32.js ToUint8.js ToUint8Clamp.js TrimString.js Type.js ValidateAndApplyPropertyDescriptor.js WeekDay.js YearFromTime.js modulo.js msFromTime.js thisBooleanValue.js thisNumberValue.js thisStringValue.js thisSymbolValue.js thisTimeValue.js 5 AbstractEqualityComparison.js AbstractRelationalComparison.js CheckObjectCoercible.js DateFromTime.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js FromPropertyDescriptor.js HourFromTime.js InLeapYear.js IsAccessorDescriptor.js IsCallable.js IsDataDescriptor.js IsGenericDescriptor.js IsPropertyDescriptor.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js SameValue.js SecFromTime.js StrictEqualityComparison.js TimeClip.js TimeFromYear.js TimeWithinDay.js ToBoolean.js ToInt32.js ToInteger.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToString.js ToUint16.js ToUint32.js Type.js WeekDay.js YearFromTime.js modulo.js msFromTime.js CHANGELOG.md GetIntrinsic.js README.md es2015.js es2016.js es2017.js es2018.js es2019.js es5.js es6.js es7.js helpers DefineOwnProperty.js OwnPropertyKeys.js assertRecord.js assign.js callBind.js callBound.js every.js forEach.js getInferredName.js getIteratorMethod.js getOwnPropertyDescriptor.js getProto.js getSymbolDescription.js isFinite.js isNaN.js isPrefixOf.js isPrimitive.js isPropertyDescriptor.js isSamePropertyDescriptor.js maxSafeInteger.js mod.js padTimeComponent.js regexTester.js setProto.js sign.js timeConstants.js index.js operations 2015.js 2016.js 2017.js 2018.js 2019.js package.json test GetIntrinsic.js diffOps.js es2015.js es2016.js es2017.js es2018.js es2019.js es5.js es6.js es7.js helpers OwnPropertyKeys.js assertRecord.js createBoundESNamespace.js defineProperty.js getSymbolDescription.js runManifestTest.js values.js index.js tests.js package.json polyfill.js shim.js test index.js shimmed.js tests.js on-finished HISTORY.md README.md index.js package.json once README.md once.js package.json onetime index.d.ts index.js package.json readme.md open index.d.ts index.js package.json readme.md opn index.js node_modules is-wsl index.js package.json readme.md package.json readme.md optionator CHANGELOG.md README.md lib help.js index.js util.js package.json ora index.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 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 strip-ansi index.js package.json readme.md supports-color browser.js index.js package.json readme.md package.json readme.md os-browserify README.md browser.js main.js package.json p-cancelable index.d.ts index.js package.json readme.md p-each-series index.d.ts index.js package.json readme.md p-finally 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-try index.d.ts index.js package.json readme.md package-json 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 parcel-bundler bin .eslintrc.json cli.js index.js lib Asset.js Bundle.js Bundler.js FSCache.js HMRServer.js Parser.js Pipeline.js Resolver.js Server.js SourceMap.js assets CSSAsset.js CoffeeScriptAsset.js ElmAsset.js GLSLAsset.js GlobAsset.js GraphqlAsset.js HTMLAsset.js JSAsset.js JSONAsset.js JSONLDAsset.js KotlinAsset.js LESSAsset.js MarkdownAsset.js PugAsset.js RawAsset.js ReasonAsset.js RustAsset.js SASSAsset.js SSSAsset.js StylusAsset.js TOMLAsset.js TypeScriptAsset.js VueAsset.js WebManifestAsset.js YAMLAsset.js builtins .eslintrc.json _empty.js bundle-loader.js bundle-url.js css-loader.js helpers.js hmr-runtime.js index.js loaders browser css-loader.js html-loader.js js-loader.js wasm-loader.js node css-loader.js html-loader.js js-loader.js wasm-loader.js prelude.js prelude.min.js prelude2.js prelude2.min.js cli.js packagers CSSPackager.js HTMLPackager.js JSConcatPackager.js JSPackager.js Packager.js RawPackager.js SourceMapPackager.js index.js scope-hoisting concat.js hoist.js mangler.js renamer.js shake.js utils.js transforms babel astConverter.js babel6.js babel7.js babelrc.js config.js env.js flow.js jsx.js transform.js htmlnano.js postcss.js posthtml.js terser.js utils PromiseQueue.js bundleReport.js config.js customErrors.js env.js generateCertificate.js getCertificate.js getExisting.js getModuleParts.js getRootDir.js getTargetEngines.js glob.js installPackage.js is-url.js isAccessedVarChanged.js lineCounter.js loadPlugins.js loadSourceMap.js localRequire.js md5.js objectHash.js openInBrowser.js parseCSSImport.js pipeSpawn.js prettifyTime.js serializeObject.js syncPromise.js urlJoin.js visitors dependencies.js env.js fs.js globals.js process.js worker.js node_modules ansi-styles index.js package.json readme.md 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 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 commander CHANGELOG.md Readme.md index.js package.json typings index.d.ts cross-spawn CHANGELOG.md README.md index.js lib enoent.js parse.js util escape.js readShebang.js resolveCommand.js package.json fill-range README.md index.js node_modules extend-shallow README.md index.js package.json package.json has-flag index.js package.json readme.md is-number README.md index.js node_modules kind-of README.md index.js package.json 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 micromatch CHANGELOG.md README.md index.js lib cache.js compilers.js parsers.js utils.js package.json path-key index.js package.json readme.md semver CHANGELOG.md README.md package.json semver.js shebang-command index.js package.json readme.md shebang-regex index.js package.json readme.md supports-color browser.js index.js package.json readme.md to-regex-range README.md index.js package.json which CHANGELOG.md README.md package.json which.js ws README.md index.js lib buffer-util.js constants.js event-target.js extension.js permessage-deflate.js receiver.js sender.js validation.js websocket-server.js websocket.js package.json package.json src .eslintrc.json Asset.js Bundle.js Bundler.js FSCache.js HMRServer.js Parser.js Pipeline.js Resolver.js Server.js SourceMap.js assets CSSAsset.js CoffeeScriptAsset.js ElmAsset.js GLSLAsset.js GlobAsset.js GraphqlAsset.js HTMLAsset.js JSAsset.js JSONAsset.js JSONLDAsset.js KotlinAsset.js LESSAsset.js MarkdownAsset.js PugAsset.js RawAsset.js ReasonAsset.js RustAsset.js SASSAsset.js SSSAsset.js StylusAsset.js TOMLAsset.js TypeScriptAsset.js VueAsset.js WebManifestAsset.js YAMLAsset.js builtins .eslintrc.json _empty.js bundle-loader.js bundle-url.js css-loader.js helpers.js hmr-runtime.js index.js loaders browser css-loader.js html-loader.js js-loader.js wasm-loader.js node css-loader.js html-loader.js js-loader.js wasm-loader.js prelude.js prelude.min.js prelude2.js prelude2.min.js cli.js packagers CSSPackager.js HTMLPackager.js JSConcatPackager.js JSPackager.js Packager.js RawPackager.js SourceMapPackager.js index.js scope-hoisting concat.js hoist.js mangler.js renamer.js shake.js utils.js transforms babel astConverter.js babel6.js babel7.js babelrc.js config.js env.js flow.js jsx.js transform.js htmlnano.js postcss.js posthtml.js terser.js utils PromiseQueue.js bundleReport.js config.js customErrors.js env.js generateCertificate.js getCertificate.js getExisting.js getModuleParts.js getRootDir.js getTargetEngines.js glob.js installPackage.js is-url.js isAccessedVarChanged.js lineCounter.js loadPlugins.js loadSourceMap.js localRequire.js md5.js objectHash.js openInBrowser.js parseCSSImport.js pipeSpawn.js prettifyTime.js serializeObject.js syncPromise.js urlJoin.js visitors dependencies.js env.js fs.js globals.js process.js worker.js parse-asn1 README.md aesid.json asn1.js certificate.js fixProc.js index.js package.json parse-json index.js package.json readme.md parse-passwd README.md index.js package.json parse5 README.md lib common doctype.js error-codes.js foreign-content.js html.js unicode.js extensions error-reporting mixin-base.js parser-mixin.js preprocessor-mixin.js tokenizer-mixin.js location-info open-element-stack-mixin.js parser-mixin.js tokenizer-mixin.js position-tracking preprocessor-mixin.js index.js parser formatting-element-list.js index.js open-element-stack.js serializer index.js tokenizer index.js named-entity-data.js preprocessor.js tree-adapters default.js utils merge-options.js mixin.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 test test-path.js path-dirname 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 .travis.yml README.md index.js package.json test.js 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 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 physical-cpu-count .gitlab-ci.yml README.md index.js package.json 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 pinkie-promise index.js package.json readme.md pinkie index.js package.json readme.md pirates README.md index.d.ts lib index.js package.json pkg-dir index.d.ts index.js package.json readme.md pn .travis.yml README.md _promise.js _promisify.js assert.js async_hooks.js buffer.js child_process.js cluster.js console.js crypto.js dgram.js dns.js domain.js events.js fs.js http.js http2.js https.js inspector.js net.js os.js package.json path.js perf_hooks.js process.js punycode.js querystring.js readline.js repl.js scripts generate.js stream.js string_decoder.js test cp.js custom.js fs.js load.js timers.js timers.js tls.js tty.js url.js util.js v8.js vm.js zlib.js posix-character-classes README.md index.js package.json postcss-calc CHANGELOG.md README.md dist index.js lib convertUnit.js reducer.js stringifier.js transform.js parser.js node_modules postcss-value-parser README.md lib index.d.ts index.js parse.js stringify.js unit.js walk.js package.json package.json postcss-colormin README.md dist colours.js index.js keywords.json lib toShorthand.js package.json postcss-convert-values CHANGELOG.md README.md dist index.js lib convert.js package.json postcss-discard-comments README.md dist index.js lib commentParser.js commentRemover.js package.json postcss-discard-duplicates CHANGELOG.md README.md dist index.js package.json postcss-discard-empty CHANGELOG.md README.md dist index.js package.json postcss-discard-overridden CHANGELOG.md README.md dist index.js metadata.toml package.json src __tests__ fixtures counter-style.css counter-style.post.css keyframes.css keyframes.post.css index.js index.js postcss-merge-longhand README.md dist index.js lib canExplode.js canMerge.js colorMerge.js decl borders.js boxBase.js columns.js index.js margin.js padding.js getDecls.js getLastNode.js getRules.js getValue.js hasAllProps.js identical.js insertCloned.js isCustomProp.js mergeRules.js mergeValues.js minifyTrbl.js minifyWsc.js numValues.js parseTrbl.js parseWsc.js remove.js trbl.js validateWsc.js package.json postcss-merge-rules README.md dist index.js lib ensureCompatibility.js node_modules postcss-selector-parser API.md CHANGELOG.md README.md dist 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 package.json postcss-selector-parser.d.ts package.json postcss-minify-font-values CHANGELOG.md README.md dist index.js lib keywords.js minify-family.js minify-font.js minify-weight.js uniqs.js package.json postcss-minify-gradients README.md dist index.js package.json postcss-minify-params README.md dist index.js package.json postcss-minify-selectors README.md dist index.js lib canUnquote.js unquote.js node_modules postcss-selector-parser API.md CHANGELOG.md README.md dist 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 package.json postcss-selector-parser.d.ts package.json postcss-modules-extract-imports 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 postcss CHANGELOG.md CONTRIBUTING.md README-cn.md README.md docs architecture.md guidelines plugin.md runner.md source-maps.md syntax.md gulpfile.js 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 package.json supports-color browser.js index.js package.json readme.md package.json postcss-modules-local-by-default CHANGELOG.md README.md 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 postcss CHANGELOG.md CONTRIBUTING.md README-cn.md README.md docs architecture.md guidelines plugin.md runner.md source-maps.md syntax.md gulpfile.js 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 package.json supports-color browser.js index.js package.json readme.md package.json postcss-modules-scope 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 postcss CHANGELOG.md CONTRIBUTING.md README-cn.md README.md docs architecture.md guidelines plugin.md runner.md source-maps.md syntax.md gulpfile.js 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 package.json supports-color browser.js index.js package.json readme.md package.json postcss-modules-values .travis.yml 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 postcss CHANGELOG.md CONTRIBUTING.md README-cn.md README.md docs architecture.md guidelines plugin.md runner.md source-maps.md syntax.md gulpfile.js 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 package.json supports-color browser.js index.js package.json readme.md package.json src index.js test index.js postcss-normalize-charset CHANGELOG.md README.md dist index.js package.json postcss-normalize-display-values README.md dist index.js lib map.js package.json postcss-normalize-positions README.md dist index.js package.json postcss-normalize-repeat-style README.md dist index.js lib map.js package.json postcss-normalize-string README.md dist index.js package.json postcss-normalize-timing-functions README.md dist index.js lib map.js package.json postcss-normalize-unicode CHANGELOG.md README.md dist index.js package.json postcss-normalize-url CHANGELOG.md README.md dist index.js node_modules normalize-url index.js package.json readme.md package.json postcss-normalize-whitespace README.md dist index.js package.json postcss-ordered-values README.md dist index.js lib addSpace.js getParsed.js getValue.js rules animation.js border.js boxShadow.js flexFlow.js transition.js package.json postcss-reduce-initial README.md data fromInitial.json toInitial.json dist index.js package.json postcss-reduce-transforms README.md dist index.js package.json 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-svgo README.md dist index.js lib url.js package.json postcss-unique-selectors CHANGELOG.md README.md dist index.js package.json 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 ansi-styles index.js package.json readme.md chalk index.js node_modules supports-color browser.js index.js package.json readme.md 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 posthtml-parser .travis.yml .vscode launch.json README.md coverage base.css coverage.json index.html lcov-report base.css index.html posthtml-parser index.html index.js.html prettify.css prettify.js sorter.js posthtml-parser index.html index.js.html prettify.css prettify.js sorter.js index.d.ts index.js package.json posthtml-render CHANGELOG.md README.md lib index.d.ts index.js package.json posthtml CHANGELOG.md README.md lib api.js index.js package.json types posthtml.d.ts prebuild-install .travis.yml CONTRIBUTING.md README.md appveyor.yml asset.js bin.js download.js error.js help.txt index.js log.js package.json proxy.js rc.js util.js prelude-ls CHANGELOG.md README.md lib Func.js List.js Num.js Obj.js Str.js index.js package.json 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 package.json process-nextick-args index.js license.md package.json readme.md process README.md browser.js index.js package.json test.js prompts dist dateparts datepart.js day.js hours.js index.js meridiem.js milliseconds.js minutes.js month.js seconds.js year.js elements autocomplete.js autocompleteMultiselect.js confirm.js date.js index.js multiselect.js number.js prompt.js select.js text.js toggle.js index.js prompts.js util action.js clear.js entriesToDisplay.js figures.js index.js lines.js strip.js style.js wrap.js index.js lib dateparts datepart.js day.js hours.js index.js meridiem.js milliseconds.js minutes.js month.js seconds.js year.js elements autocomplete.js autocompleteMultiselect.js confirm.js date.js index.js multiselect.js number.js prompt.js select.js text.js toggle.js index.js prompts.js util action.js clear.js entriesToDisplay.js figures.js index.js lines.js strip.js style.js wrap.js package.json readme.md psl README.md browserstack-logo.svg data rules.json dist psl.js psl.min.js index.js package.json pstree.remy .travis.yml README.md lib index.js tree.js utils.js package.json tests fixtures index.js index.test.js public-encrypt .travis.yml browser.js index.js mgf.js node_modules bn.js README.md lib bn.js package.json util genCombMulTo.js genCombMulTo10.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 punycode LICENSE-MIT.txt README.md package.json punycode.es6.js punycode.js pupa index.d.ts index.js package.json readme.md purgecss README.md lib purgecss.d.ts purgecss.esm.d.ts purgecss.esm.js purgecss.js node_modules ansi-styles index.js package.json readme.md chalk index.js node_modules supports-color browser.js index.js package.json readme.md 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 commander CHANGELOG.md Readme.md index.js package.json typings index.d.ts has-flag index.js package.json readme.md postcss CHANGELOG.md README.md docs api assets scripts.min.js styles.min.css index.html 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 package.json supports-color browser.js index.js package.json readme.md package.json q CHANGES.md README.md package.json q.js queue.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 query-string index.js package.json readme.md 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 quote-stream .travis.yml bin cmd.js usage.txt example stream.js index.js package.json test simple.js unicode_separators.js whitespace.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 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 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 read-pkg-up index.d.ts index.js package.json readme.md read-pkg index.d.ts index.js node_modules type-fest index.d.ts package.json readme.md source basic.d.ts except.d.ts literal-union.d.ts merge-exclusive.d.ts merge.d.ts mutable.d.ts package-json.d.ts promisable.d.ts readonly-deep.d.ts require-at-least-one.d.ts 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 node_modules safe-buffer README.md index.d.ts index.js package.json package.json passthrough.js readable-browser.js readable.js transform.js writable-browser.js writable.js readdirp README.md index.d.ts index.js package.json 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 Chorasmian.js Common.js Coptic.js Cuneiform.js Cypriot.js Cyrillic.js Deseret.js Devanagari.js Dives_Akuru.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 Khitan_Small_Script.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 Yezidi.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 Chorasmian.js Common.js Coptic.js Cuneiform.js Cypriot.js Cyrillic.js Deseret.js Devanagari.js Dives_Akuru.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 Khitan_Small_Script.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 Yezidi.js Yi.js Zanabazar_Square.js index.js package.json unicode-version.js regenerate LICENSE-MIT.txt README.md package.json regenerate.js regenerator-runtime README.md package.json path.js runtime.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 regexpu-core LICENSE-MIT.txt README.md data character-class-escape-sets.js iu-mappings.js package.json rewrite-pattern.js registry-auth-token CHANGELOG.md README.md base64.js index.js package.json registry-url.js test auth-token.test.js registry-url.test.js registry-url index.d.ts index.js package.json readme.md regjsgen LICENSE-MIT.txt 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 request-promise-core README.md configure request-next.js request2.js errors.js lib errors.js plumbing.js package.json request-promise-native README.md errors.js lib rp.js node_modules tough-cookie README.md lib cookie.js memstore.js pathMatch.js permuteDomain.js pubsuffix-psl.js store.js version.js package.json package.json 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 node_modules tough-cookie README.md lib cookie.js memstore.js pathMatch.js permuteDomain.js pubsuffix-psl.js store.js version.js package.json uuid CHANGELOG.md LICENSE.md README.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 package.json request.js require-directory .travis.yml index.js package.json require-main-filename CHANGELOG.md LICENSE.txt 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 resolve-url bower.json changelog.md component.json package.json readme.md resolve-url.js test resolve-url.js resolve .travis.yml 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 responselike README.md package.json src index.js restore-cursor index.js node_modules mimic-fn index.js package.json readme.md onetime index.js package.json readme.md package.json readme.md ret README.md lib index.js positions.js sets.js types.js util.js package.json rgb-regex .travis.yml LICENSE.md README.md index.js package.json test test.js rgba-regex .travis.yml LICENSE.md README.md index.js package.json test test.js rimraf CHANGELOG.md README.md bin.js package.json rimraf.js ripemd160 CHANGELOG.md README.md index.js package.json rsvp CHANGELOG.md README.md dist es6 rsvp.es.js rsvp.es.js rsvp.js lib rsvp.js rsvp -internal.js all-settled.js all.js asap.js config.js defer.js enumerator.js events.js filter.js hash-settled.js hash.js instrument.js map.js node.js promise-hash.js promise.js promise all.js race.js reject.js resolve.js race.js reject.js resolve.js rethrow.js then.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 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 sane README.md index.js node_modules anymatch 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 fill-range README.md index.js node_modules extend-shallow README.md index.js package.json package.json is-number README.md index.js node_modules kind-of README.md index.js package.json package.json micromatch CHANGELOG.md README.md index.js lib cache.js compilers.js parsers.js utils.js package.json normalize-path README.md index.js package.json to-regex-range README.md index.js package.json package.json src cli.js common.js node_watcher.js poll_watcher.js utils recrawl-warning-dedupe.js watchexec_client.js watchexec_watcher.js watchman_client.js watchman_watcher.js sax README.md lib sax.js package.json saxes README.md package.json saxes.d.ts saxes.js semver-diff index.d.ts index.js package.json readme.md semver CHANGELOG.md README.md bin semver.js package.json semver.js send HISTORY.md README.md index.js node_modules debug .coveralls.yml .travis.yml CHANGELOG.md README.md component.json karma.conf.js node.js node_modules ms index.js license.md package.json readme.md package.json src browser.js debug.js index.js inspector-log.js node.js depd History.md Readme.md index.js lib browser index.js compat callsite-tostring.js event-listener-count.js index.js package.json http-errors HISTORY.md README.md index.js package.json ms index.js license.md package.json readme.md setprototypeof README.md index.d.ts index.js package.json test index.js package.json serialize-to-js README.md lib index.js internal reference.js utils.js package.json src index.js internal reference.js utils.js 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 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 shallow-copy .travis.yml example array.js object.js index.js package.json test array.js object.js shebang-command index.js package.json readme.md shebang-regex index.d.ts index.js package.json readme.md shellwords README.md lib shellwords.js package.json signal-exit CHANGELOG.md 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 README.md index.js package.json simple-swizzle README.md index.js node_modules is-arrayish README.md index.js package.json package.json sisteransi package.json readme.md src index.js sisteransi.d.ts slash index.d.ts index.js package.json readme.md 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 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 define-property README.md index.js package.json extend-shallow README.md index.js package.json ms index.js license.md package.json readme.md 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 package.json sort-keys index.js package.json readme.md source-map-resolve changelog.md lib decode-uri-component.js resolve-url.js source-map-resolve-node.js package.json readme.md source-map-resolve.js source-map-support LICENSE.md README.md browser-source-map-support.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.d.ts 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 split-string README.md index.js package.json 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 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 node_modules 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 package.json stable README.md index.d.ts package.json stable.js stable.min.js stack-utils index.js node_modules escape-string-regexp index.d.ts index.js package.json readme.md package.json readme.md static-eval .travis.yml CHANGELOG.md example eval.js vars.js index.js package.json security.md test eval.js prop.js template-strings.js static-extend index.js node_modules define-property README.md index.js package.json package.json static-module .travis.yml example brfs.js brfs source.js x.txt fs.js fs source.js x.txt index.js node_modules escodegen README.md bin escodegen.js esgenerate.js escodegen.js package.json esprima README.md bin esparse.js esvalidate.js dist esprima.js package.json object-inspect .ignored-tmp.js .travis.yml example all.js circular.js fn.js inspect.js index.js package.json test-core-js.js test browser dom.js circular.js deep.js element.js err.js fn.js has.js holes.js inspect.js lowbyte.js number.js undef.js values.js util.inspect.js package.json test assign.js assign comma.js source.js brfs.js brfs attribute.js attribute_brackets.js attribute_vars.js brackets.js empty.js multi_require.js multi_require_with_uninitialized.js source.js x.txt x5.js fn.js fn source.js fs.js fs html.js readfile.js robot.html x.txt fs_twice.js fs_twice 4x.js html.js readfile.js robot.html vars.js x.txt inline.js inline fn.js fn_call.js fn_expr.js obj.js obj_call.js obj_expr.js limit-parsing.js log.js log source.js many.js many a.txt all_inline.js b.txt c.txt inline.js source.js mixed.js mixed source.js unmixed.js xyz.txt nested.js nested source.js obj.js obj source.js prop.js prop source.js readfile_resolve.js readfile_resolve main.js node_modules aaa wow.txt shebang.js shebang source.js sourcemap.js sourcemap main.js unary.js unary supported.js unsupported.js varmod.js varmod source.js vars.html vars.js vars five.js multi-require.js one.js source.js vars.html statuses HISTORY.md README.md codes.json index.js package.json stealthy-require README.md lib index.js package.json stoppable lib stoppable.js package.json readme.md stream-browserify .travis.yml index.js package.json test buf.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 strict-uri-encode index.js package.json readme.md string-length index.d.ts index.js package.json readme.md string-width index.d.ts index.js package.json readme.md string.prototype.trimend .github workflows rebase.yml .travis.yml CHANGELOG.md README.md auto.js implementation.js index.js node_modules es-abstract .github FUNDING.yml workflows codeql-analysis.yml rebase.yml .travis.yml 2015 AbstractEqualityComparison.js AbstractRelationalComparison.js AdvanceStringIndex.js ArrayCreate.js ArraySetLength.js ArraySpeciesCreate.js Call.js CanonicalNumericIndexString.js CompletePropertyDescriptor.js CreateDataProperty.js CreateDataPropertyOrThrow.js CreateHTML.js CreateIterResultObject.js CreateListFromArrayLike.js CreateMethodProperty.js DateFromTime.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js DefinePropertyOrThrow.js DeletePropertyOrThrow.js EnumerableOwnNames.js FromPropertyDescriptor.js Get.js GetIterator.js GetMethod.js GetOwnPropertyKeys.js GetPrototypeFromConstructor.js GetSubstitution.js GetV.js HasOwnProperty.js HasProperty.js HourFromTime.js InLeapYear.js InstanceofOperator.js Invoke.js IsAccessorDescriptor.js IsArray.js IsCallable.js IsConcatSpreadable.js IsConstructor.js IsDataDescriptor.js IsExtensible.js IsGenericDescriptor.js IsInteger.js IsPromise.js IsPropertyDescriptor.js IsPropertyKey.js IsRegExp.js IteratorClose.js IteratorComplete.js IteratorNext.js IteratorStep.js IteratorValue.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js ObjectCreate.js OrdinaryDefineOwnProperty.js OrdinaryGetOwnProperty.js OrdinaryHasInstance.js OrdinaryHasProperty.js RegExpExec.js RequireObjectCoercible.js SameValue.js SameValueZero.js SecFromTime.js Set.js SetFunctionName.js SetIntegrityLevel.js SpeciesConstructor.js StrictEqualityComparison.js SymbolDescriptiveString.js TestIntegrityLevel.js TimeClip.js TimeFromYear.js TimeWithinDay.js ToBoolean.js ToDateString.js ToInt16.js ToInt32.js ToInt8.js ToInteger.js ToLength.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToPropertyKey.js ToString.js ToUint16.js ToUint32.js ToUint8.js ToUint8Clamp.js Type.js ValidateAndApplyPropertyDescriptor.js WeekDay.js YearFromTime.js modulo.js msFromTime.js thisBooleanValue.js thisNumberValue.js thisStringValue.js thisTimeValue.js 2016 AbstractEqualityComparison.js AbstractRelationalComparison.js AdvanceStringIndex.js ArrayCreate.js ArraySetLength.js ArraySpeciesCreate.js Call.js CanonicalNumericIndexString.js CompletePropertyDescriptor.js CreateDataProperty.js CreateDataPropertyOrThrow.js CreateHTML.js CreateIterResultObject.js CreateListFromArrayLike.js CreateMethodProperty.js DateFromTime.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js DefinePropertyOrThrow.js DeletePropertyOrThrow.js EnumerableOwnNames.js FromPropertyDescriptor.js Get.js GetIterator.js GetMethod.js GetOwnPropertyKeys.js GetPrototypeFromConstructor.js GetSubstitution.js GetV.js HasOwnProperty.js HasProperty.js HourFromTime.js InLeapYear.js InstanceofOperator.js Invoke.js IsAccessorDescriptor.js IsArray.js IsCallable.js IsConcatSpreadable.js IsConstructor.js IsDataDescriptor.js IsExtensible.js IsGenericDescriptor.js IsInteger.js IsPromise.js IsPropertyDescriptor.js IsPropertyKey.js IsRegExp.js IterableToArrayLike.js IteratorClose.js IteratorComplete.js IteratorNext.js IteratorStep.js IteratorValue.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js ObjectCreate.js OrdinaryDefineOwnProperty.js OrdinaryGetOwnProperty.js OrdinaryGetPrototypeOf.js OrdinaryHasInstance.js OrdinaryHasProperty.js OrdinarySetPrototypeOf.js RegExpExec.js RequireObjectCoercible.js SameValue.js SameValueNonNumber.js SameValueZero.js SecFromTime.js Set.js SetFunctionName.js SetIntegrityLevel.js SpeciesConstructor.js StrictEqualityComparison.js SymbolDescriptiveString.js TestIntegrityLevel.js TimeClip.js TimeFromYear.js TimeWithinDay.js ToBoolean.js ToDateString.js ToInt16.js ToInt32.js ToInt8.js ToInteger.js ToLength.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToPropertyKey.js ToString.js ToUint16.js ToUint32.js ToUint8.js ToUint8Clamp.js Type.js ValidateAndApplyPropertyDescriptor.js WeekDay.js YearFromTime.js modulo.js msFromTime.js thisBooleanValue.js thisNumberValue.js thisStringValue.js thisTimeValue.js 2017 AbstractEqualityComparison.js AbstractRelationalComparison.js AdvanceStringIndex.js ArrayCreate.js ArraySetLength.js ArraySpeciesCreate.js Call.js CanonicalNumericIndexString.js CompletePropertyDescriptor.js CreateDataProperty.js CreateDataPropertyOrThrow.js CreateHTML.js CreateIterResultObject.js CreateListFromArrayLike.js CreateMethodProperty.js DateFromTime.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js DefinePropertyOrThrow.js DeletePropertyOrThrow.js EnumerableOwnProperties.js FromPropertyDescriptor.js Get.js GetIterator.js GetMethod.js GetOwnPropertyKeys.js GetPrototypeFromConstructor.js GetSubstitution.js GetV.js HasOwnProperty.js HasProperty.js HourFromTime.js InLeapYear.js InstanceofOperator.js Invoke.js IsAccessorDescriptor.js IsArray.js IsCallable.js IsConcatSpreadable.js IsConstructor.js IsDataDescriptor.js IsExtensible.js IsGenericDescriptor.js IsInteger.js IsPromise.js IsPropertyDescriptor.js IsPropertyKey.js IsRegExp.js IterableToList.js IteratorClose.js IteratorComplete.js IteratorNext.js IteratorStep.js IteratorValue.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js ObjectCreate.js OrdinaryDefineOwnProperty.js OrdinaryGetOwnProperty.js OrdinaryGetPrototypeOf.js OrdinaryHasInstance.js OrdinaryHasProperty.js OrdinarySetPrototypeOf.js RegExpExec.js RequireObjectCoercible.js SameValue.js SameValueNonNumber.js SameValueZero.js SecFromTime.js Set.js SetFunctionName.js SetIntegrityLevel.js SpeciesConstructor.js StrictEqualityComparison.js SymbolDescriptiveString.js TestIntegrityLevel.js TimeClip.js TimeFromYear.js TimeWithinDay.js ToBoolean.js ToDateString.js ToIndex.js ToInt16.js ToInt32.js ToInt8.js ToInteger.js ToLength.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToPropertyKey.js ToString.js ToUint16.js ToUint32.js ToUint8.js ToUint8Clamp.js Type.js ValidateAndApplyPropertyDescriptor.js WeekDay.js YearFromTime.js modulo.js msFromTime.js thisBooleanValue.js thisNumberValue.js thisStringValue.js thisTimeValue.js 2018 AbstractEqualityComparison.js AbstractRelationalComparison.js AdvanceStringIndex.js ArrayCreate.js ArraySetLength.js ArraySpeciesCreate.js Call.js CanonicalNumericIndexString.js CompletePropertyDescriptor.js CopyDataProperties.js CreateDataProperty.js CreateDataPropertyOrThrow.js CreateHTML.js CreateIterResultObject.js CreateListFromArrayLike.js CreateMethodProperty.js DateFromTime.js DateString.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js DefinePropertyOrThrow.js DeletePropertyOrThrow.js EnumerableOwnPropertyNames.js FromPropertyDescriptor.js Get.js GetIterator.js GetMethod.js GetOwnPropertyKeys.js GetPrototypeFromConstructor.js GetSubstitution.js GetV.js HasOwnProperty.js HasProperty.js HourFromTime.js InLeapYear.js InstanceofOperator.js Invoke.js IsAccessorDescriptor.js IsArray.js IsCallable.js IsConcatSpreadable.js IsConstructor.js IsDataDescriptor.js IsExtensible.js IsGenericDescriptor.js IsInteger.js IsPromise.js IsPropertyKey.js IsRegExp.js IsStringPrefix.js IterableToList.js IteratorClose.js IteratorComplete.js IteratorNext.js IteratorStep.js IteratorValue.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js NumberToString.js ObjectCreate.js OrdinaryDefineOwnProperty.js OrdinaryGetOwnProperty.js OrdinaryGetPrototypeOf.js OrdinaryHasInstance.js OrdinaryHasProperty.js OrdinarySetPrototypeOf.js PromiseResolve.js RegExpExec.js RequireObjectCoercible.js SameValue.js SameValueNonNumber.js SameValueZero.js SecFromTime.js Set.js SetFunctionName.js SetIntegrityLevel.js SpeciesConstructor.js StrictEqualityComparison.js SymbolDescriptiveString.js TestIntegrityLevel.js TimeClip.js TimeFromYear.js TimeString.js TimeWithinDay.js ToBoolean.js ToDateString.js ToIndex.js ToInt16.js ToInt32.js ToInt8.js ToInteger.js ToLength.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToPropertyKey.js ToString.js ToUint16.js ToUint32.js ToUint8.js ToUint8Clamp.js Type.js ValidateAndApplyPropertyDescriptor.js WeekDay.js YearFromTime.js modulo.js msFromTime.js thisBooleanValue.js thisNumberValue.js thisStringValue.js thisSymbolValue.js thisTimeValue.js 2019 AbstractEqualityComparison.js AbstractRelationalComparison.js AddEntriesFromIterable.js AdvanceStringIndex.js ArrayCreate.js ArraySetLength.js ArraySpeciesCreate.js Call.js CanonicalNumericIndexString.js CompletePropertyDescriptor.js CopyDataProperties.js CreateDataProperty.js CreateDataPropertyOrThrow.js CreateHTML.js CreateIterResultObject.js CreateListFromArrayLike.js CreateMethodProperty.js DateFromTime.js DateString.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js DefinePropertyOrThrow.js DeletePropertyOrThrow.js EnumerableOwnPropertyNames.js FlattenIntoArray.js FromPropertyDescriptor.js Get.js GetIterator.js GetMethod.js GetOwnPropertyKeys.js GetPrototypeFromConstructor.js GetSubstitution.js GetV.js HasOwnProperty.js HasProperty.js HourFromTime.js InLeapYear.js InstanceofOperator.js Invoke.js IsAccessorDescriptor.js IsArray.js IsCallable.js IsConcatSpreadable.js IsConstructor.js IsDataDescriptor.js IsExtensible.js IsGenericDescriptor.js IsInteger.js IsPromise.js IsPropertyKey.js IsRegExp.js IsStringPrefix.js IterableToList.js IteratorClose.js IteratorComplete.js IteratorNext.js IteratorStep.js IteratorValue.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js NumberToString.js ObjectCreate.js OrdinaryDefineOwnProperty.js OrdinaryGetOwnProperty.js OrdinaryGetPrototypeOf.js OrdinaryHasInstance.js OrdinaryHasProperty.js OrdinarySetPrototypeOf.js PromiseResolve.js RegExpExec.js RequireObjectCoercible.js SameValue.js SameValueNonNumber.js SameValueZero.js SecFromTime.js Set.js SetFunctionName.js SetIntegrityLevel.js SpeciesConstructor.js StrictEqualityComparison.js SymbolDescriptiveString.js TestIntegrityLevel.js TimeClip.js TimeFromYear.js TimeString.js TimeWithinDay.js ToBoolean.js ToDateString.js ToIndex.js ToInt16.js ToInt32.js ToInt8.js ToInteger.js ToLength.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToPropertyKey.js ToString.js ToUint16.js ToUint32.js ToUint8.js ToUint8Clamp.js TrimString.js Type.js ValidateAndApplyPropertyDescriptor.js WeekDay.js YearFromTime.js modulo.js msFromTime.js thisBooleanValue.js thisNumberValue.js thisStringValue.js thisSymbolValue.js thisTimeValue.js 5 AbstractEqualityComparison.js AbstractRelationalComparison.js CheckObjectCoercible.js DateFromTime.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js FromPropertyDescriptor.js HourFromTime.js InLeapYear.js IsAccessorDescriptor.js IsCallable.js IsDataDescriptor.js IsGenericDescriptor.js IsPropertyDescriptor.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js SameValue.js SecFromTime.js StrictEqualityComparison.js TimeClip.js TimeFromYear.js TimeWithinDay.js ToBoolean.js ToInt32.js ToInteger.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToString.js ToUint16.js ToUint32.js Type.js WeekDay.js YearFromTime.js modulo.js msFromTime.js CHANGELOG.md GetIntrinsic.js README.md es2015.js es2016.js es2017.js es2018.js es2019.js es5.js es6.js es7.js helpers DefineOwnProperty.js OwnPropertyKeys.js assertRecord.js assign.js callBind.js callBound.js every.js forEach.js getInferredName.js getIteratorMethod.js getOwnPropertyDescriptor.js getProto.js getSymbolDescription.js isFinite.js isNaN.js isPrefixOf.js isPrimitive.js isPropertyDescriptor.js isSamePropertyDescriptor.js maxSafeInteger.js mod.js padTimeComponent.js regexTester.js setProto.js sign.js timeConstants.js index.js operations 2015.js 2016.js 2017.js 2018.js 2019.js package.json test GetIntrinsic.js diffOps.js es2015.js es2016.js es2017.js es2018.js es2019.js es5.js es6.js es7.js helpers OwnPropertyKeys.js assertRecord.js createBoundESNamespace.js defineProperty.js getSymbolDescription.js runManifestTest.js values.js index.js tests.js package.json polyfill.js shim.js test index.js shimmed.js tests.js string.prototype.trimstart .github workflows rebase.yml .travis.yml CHANGELOG.md README.md auto.js implementation.js index.js node_modules es-abstract .github FUNDING.yml workflows codeql-analysis.yml rebase.yml .travis.yml 2015 AbstractEqualityComparison.js AbstractRelationalComparison.js AdvanceStringIndex.js ArrayCreate.js ArraySetLength.js ArraySpeciesCreate.js Call.js CanonicalNumericIndexString.js CompletePropertyDescriptor.js CreateDataProperty.js CreateDataPropertyOrThrow.js CreateHTML.js CreateIterResultObject.js CreateListFromArrayLike.js CreateMethodProperty.js DateFromTime.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js DefinePropertyOrThrow.js DeletePropertyOrThrow.js EnumerableOwnNames.js FromPropertyDescriptor.js Get.js GetIterator.js GetMethod.js GetOwnPropertyKeys.js GetPrototypeFromConstructor.js GetSubstitution.js GetV.js HasOwnProperty.js HasProperty.js HourFromTime.js InLeapYear.js InstanceofOperator.js Invoke.js IsAccessorDescriptor.js IsArray.js IsCallable.js IsConcatSpreadable.js IsConstructor.js IsDataDescriptor.js IsExtensible.js IsGenericDescriptor.js IsInteger.js IsPromise.js IsPropertyDescriptor.js IsPropertyKey.js IsRegExp.js IteratorClose.js IteratorComplete.js IteratorNext.js IteratorStep.js IteratorValue.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js ObjectCreate.js OrdinaryDefineOwnProperty.js OrdinaryGetOwnProperty.js OrdinaryHasInstance.js OrdinaryHasProperty.js RegExpExec.js RequireObjectCoercible.js SameValue.js SameValueZero.js SecFromTime.js Set.js SetFunctionName.js SetIntegrityLevel.js SpeciesConstructor.js StrictEqualityComparison.js SymbolDescriptiveString.js TestIntegrityLevel.js TimeClip.js TimeFromYear.js TimeWithinDay.js ToBoolean.js ToDateString.js ToInt16.js ToInt32.js ToInt8.js ToInteger.js ToLength.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToPropertyKey.js ToString.js ToUint16.js ToUint32.js ToUint8.js ToUint8Clamp.js Type.js ValidateAndApplyPropertyDescriptor.js WeekDay.js YearFromTime.js modulo.js msFromTime.js thisBooleanValue.js thisNumberValue.js thisStringValue.js thisTimeValue.js 2016 AbstractEqualityComparison.js AbstractRelationalComparison.js AdvanceStringIndex.js ArrayCreate.js ArraySetLength.js ArraySpeciesCreate.js Call.js CanonicalNumericIndexString.js CompletePropertyDescriptor.js CreateDataProperty.js CreateDataPropertyOrThrow.js CreateHTML.js CreateIterResultObject.js CreateListFromArrayLike.js CreateMethodProperty.js DateFromTime.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js DefinePropertyOrThrow.js DeletePropertyOrThrow.js EnumerableOwnNames.js FromPropertyDescriptor.js Get.js GetIterator.js GetMethod.js GetOwnPropertyKeys.js GetPrototypeFromConstructor.js GetSubstitution.js GetV.js HasOwnProperty.js HasProperty.js HourFromTime.js InLeapYear.js InstanceofOperator.js Invoke.js IsAccessorDescriptor.js IsArray.js IsCallable.js IsConcatSpreadable.js IsConstructor.js IsDataDescriptor.js IsExtensible.js IsGenericDescriptor.js IsInteger.js IsPromise.js IsPropertyDescriptor.js IsPropertyKey.js IsRegExp.js IterableToArrayLike.js IteratorClose.js IteratorComplete.js IteratorNext.js IteratorStep.js IteratorValue.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js ObjectCreate.js OrdinaryDefineOwnProperty.js OrdinaryGetOwnProperty.js OrdinaryGetPrototypeOf.js OrdinaryHasInstance.js OrdinaryHasProperty.js OrdinarySetPrototypeOf.js RegExpExec.js RequireObjectCoercible.js SameValue.js SameValueNonNumber.js SameValueZero.js SecFromTime.js Set.js SetFunctionName.js SetIntegrityLevel.js SpeciesConstructor.js StrictEqualityComparison.js SymbolDescriptiveString.js TestIntegrityLevel.js TimeClip.js TimeFromYear.js TimeWithinDay.js ToBoolean.js ToDateString.js ToInt16.js ToInt32.js ToInt8.js ToInteger.js ToLength.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToPropertyKey.js ToString.js ToUint16.js ToUint32.js ToUint8.js ToUint8Clamp.js Type.js ValidateAndApplyPropertyDescriptor.js WeekDay.js YearFromTime.js modulo.js msFromTime.js thisBooleanValue.js thisNumberValue.js thisStringValue.js thisTimeValue.js 2017 AbstractEqualityComparison.js AbstractRelationalComparison.js AdvanceStringIndex.js ArrayCreate.js ArraySetLength.js ArraySpeciesCreate.js Call.js CanonicalNumericIndexString.js CompletePropertyDescriptor.js CreateDataProperty.js CreateDataPropertyOrThrow.js CreateHTML.js CreateIterResultObject.js CreateListFromArrayLike.js CreateMethodProperty.js DateFromTime.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js DefinePropertyOrThrow.js DeletePropertyOrThrow.js EnumerableOwnProperties.js FromPropertyDescriptor.js Get.js GetIterator.js GetMethod.js GetOwnPropertyKeys.js GetPrototypeFromConstructor.js GetSubstitution.js GetV.js HasOwnProperty.js HasProperty.js HourFromTime.js InLeapYear.js InstanceofOperator.js Invoke.js IsAccessorDescriptor.js IsArray.js IsCallable.js IsConcatSpreadable.js IsConstructor.js IsDataDescriptor.js IsExtensible.js IsGenericDescriptor.js IsInteger.js IsPromise.js IsPropertyDescriptor.js IsPropertyKey.js IsRegExp.js IterableToList.js IteratorClose.js IteratorComplete.js IteratorNext.js IteratorStep.js IteratorValue.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js ObjectCreate.js OrdinaryDefineOwnProperty.js OrdinaryGetOwnProperty.js OrdinaryGetPrototypeOf.js OrdinaryHasInstance.js OrdinaryHasProperty.js OrdinarySetPrototypeOf.js RegExpExec.js RequireObjectCoercible.js SameValue.js SameValueNonNumber.js SameValueZero.js SecFromTime.js Set.js SetFunctionName.js SetIntegrityLevel.js SpeciesConstructor.js StrictEqualityComparison.js SymbolDescriptiveString.js TestIntegrityLevel.js TimeClip.js TimeFromYear.js TimeWithinDay.js ToBoolean.js ToDateString.js ToIndex.js ToInt16.js ToInt32.js ToInt8.js ToInteger.js ToLength.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToPropertyKey.js ToString.js ToUint16.js ToUint32.js ToUint8.js ToUint8Clamp.js Type.js ValidateAndApplyPropertyDescriptor.js WeekDay.js YearFromTime.js modulo.js msFromTime.js thisBooleanValue.js thisNumberValue.js thisStringValue.js thisTimeValue.js 2018 AbstractEqualityComparison.js AbstractRelationalComparison.js AdvanceStringIndex.js ArrayCreate.js ArraySetLength.js ArraySpeciesCreate.js Call.js CanonicalNumericIndexString.js CompletePropertyDescriptor.js CopyDataProperties.js CreateDataProperty.js CreateDataPropertyOrThrow.js CreateHTML.js CreateIterResultObject.js CreateListFromArrayLike.js CreateMethodProperty.js DateFromTime.js DateString.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js DefinePropertyOrThrow.js DeletePropertyOrThrow.js EnumerableOwnPropertyNames.js FromPropertyDescriptor.js Get.js GetIterator.js GetMethod.js GetOwnPropertyKeys.js GetPrototypeFromConstructor.js GetSubstitution.js GetV.js HasOwnProperty.js HasProperty.js HourFromTime.js InLeapYear.js InstanceofOperator.js Invoke.js IsAccessorDescriptor.js IsArray.js IsCallable.js IsConcatSpreadable.js IsConstructor.js IsDataDescriptor.js IsExtensible.js IsGenericDescriptor.js IsInteger.js IsPromise.js IsPropertyKey.js IsRegExp.js IsStringPrefix.js IterableToList.js IteratorClose.js IteratorComplete.js IteratorNext.js IteratorStep.js IteratorValue.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js NumberToString.js ObjectCreate.js OrdinaryDefineOwnProperty.js OrdinaryGetOwnProperty.js OrdinaryGetPrototypeOf.js OrdinaryHasInstance.js OrdinaryHasProperty.js OrdinarySetPrototypeOf.js PromiseResolve.js RegExpExec.js RequireObjectCoercible.js SameValue.js SameValueNonNumber.js SameValueZero.js SecFromTime.js Set.js SetFunctionName.js SetIntegrityLevel.js SpeciesConstructor.js StrictEqualityComparison.js SymbolDescriptiveString.js TestIntegrityLevel.js TimeClip.js TimeFromYear.js TimeString.js TimeWithinDay.js ToBoolean.js ToDateString.js ToIndex.js ToInt16.js ToInt32.js ToInt8.js ToInteger.js ToLength.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToPropertyKey.js ToString.js ToUint16.js ToUint32.js ToUint8.js ToUint8Clamp.js Type.js ValidateAndApplyPropertyDescriptor.js WeekDay.js YearFromTime.js modulo.js msFromTime.js thisBooleanValue.js thisNumberValue.js thisStringValue.js thisSymbolValue.js thisTimeValue.js 2019 AbstractEqualityComparison.js AbstractRelationalComparison.js AddEntriesFromIterable.js AdvanceStringIndex.js ArrayCreate.js ArraySetLength.js ArraySpeciesCreate.js Call.js CanonicalNumericIndexString.js CompletePropertyDescriptor.js CopyDataProperties.js CreateDataProperty.js CreateDataPropertyOrThrow.js CreateHTML.js CreateIterResultObject.js CreateListFromArrayLike.js CreateMethodProperty.js DateFromTime.js DateString.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js DefinePropertyOrThrow.js DeletePropertyOrThrow.js EnumerableOwnPropertyNames.js FlattenIntoArray.js FromPropertyDescriptor.js Get.js GetIterator.js GetMethod.js GetOwnPropertyKeys.js GetPrototypeFromConstructor.js GetSubstitution.js GetV.js HasOwnProperty.js HasProperty.js HourFromTime.js InLeapYear.js InstanceofOperator.js Invoke.js IsAccessorDescriptor.js IsArray.js IsCallable.js IsConcatSpreadable.js IsConstructor.js IsDataDescriptor.js IsExtensible.js IsGenericDescriptor.js IsInteger.js IsPromise.js IsPropertyKey.js IsRegExp.js IsStringPrefix.js IterableToList.js IteratorClose.js IteratorComplete.js IteratorNext.js IteratorStep.js IteratorValue.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js NumberToString.js ObjectCreate.js OrdinaryDefineOwnProperty.js OrdinaryGetOwnProperty.js OrdinaryGetPrototypeOf.js OrdinaryHasInstance.js OrdinaryHasProperty.js OrdinarySetPrototypeOf.js PromiseResolve.js RegExpExec.js RequireObjectCoercible.js SameValue.js SameValueNonNumber.js SameValueZero.js SecFromTime.js Set.js SetFunctionName.js SetIntegrityLevel.js SpeciesConstructor.js StrictEqualityComparison.js SymbolDescriptiveString.js TestIntegrityLevel.js TimeClip.js TimeFromYear.js TimeString.js TimeWithinDay.js ToBoolean.js ToDateString.js ToIndex.js ToInt16.js ToInt32.js ToInt8.js ToInteger.js ToLength.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToPropertyKey.js ToString.js ToUint16.js ToUint32.js ToUint8.js ToUint8Clamp.js TrimString.js Type.js ValidateAndApplyPropertyDescriptor.js WeekDay.js YearFromTime.js modulo.js msFromTime.js thisBooleanValue.js thisNumberValue.js thisStringValue.js thisSymbolValue.js thisTimeValue.js 5 AbstractEqualityComparison.js AbstractRelationalComparison.js CheckObjectCoercible.js DateFromTime.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js FromPropertyDescriptor.js HourFromTime.js InLeapYear.js IsAccessorDescriptor.js IsCallable.js IsDataDescriptor.js IsGenericDescriptor.js IsPropertyDescriptor.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js SameValue.js SecFromTime.js StrictEqualityComparison.js TimeClip.js TimeFromYear.js TimeWithinDay.js ToBoolean.js ToInt32.js ToInteger.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToString.js ToUint16.js ToUint32.js Type.js WeekDay.js YearFromTime.js modulo.js msFromTime.js CHANGELOG.md GetIntrinsic.js README.md es2015.js es2016.js es2017.js es2018.js es2019.js es5.js es6.js es7.js helpers DefineOwnProperty.js OwnPropertyKeys.js assertRecord.js assign.js callBind.js callBound.js every.js forEach.js getInferredName.js getIteratorMethod.js getOwnPropertyDescriptor.js getProto.js getSymbolDescription.js isFinite.js isNaN.js isPrefixOf.js isPrimitive.js isPropertyDescriptor.js isSamePropertyDescriptor.js maxSafeInteger.js mod.js padTimeComponent.js regexTester.js setProto.js sign.js timeConstants.js index.js operations 2015.js 2016.js 2017.js 2018.js 2019.js package.json test GetIntrinsic.js diffOps.js es2015.js es2016.js es2017.js es2018.js es2019.js es5.js es6.js es7.js helpers OwnPropertyKeys.js assertRecord.js createBoundESNamespace.js defineProperty.js getSymbolDescription.js runManifestTest.js values.js index.js tests.js package.json polyfill.js shim.js test index.js shimmed.js tests.js string_decoder .travis.yml README.md lib string_decoder.js node_modules safe-buffer README.md index.d.ts index.js package.json package.json strip-ansi index.d.ts index.js package.json readme.md strip-bom index.d.ts index.js package.json readme.md strip-eof index.js package.json readme.md strip-final-newline index.js package.json readme.md strip-json-comments index.js package.json readme.md strip-outer index.js package.json readme.md strip-url-auth index.js package.json readme.md stylehacks README.md dist dictionary browsers.js identifiers.js postcss.js tags.js exists.js index.js isMixin.js plugin.js plugins bodyEmpty.js htmlCombinatorCommentBody.js htmlFirstChild.js important.js index.js leadingStar.js leadingUnderscore.js mediaSlash0.js mediaSlash0Slash9.js mediaSlash9.js slash9.js starHtml.js trailingSlashComma.js node_modules postcss-selector-parser API.md CHANGELOG.md README.md dist 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 package.json postcss-selector-parser.d.ts package.json supports-color browser.js index.js package.json readme.md supports-hyperlinks browser.js index.js package.json readme.md svgo .svgo.yml CHANGELOG.md README.md README.ru.md lib css-tools.js svgo.js svgo coa.js config.js css-class-list.js css-select-adapter.js css-style-declaration.js js2svg.js jsAPI.js plugins.js svg2js.js tools.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 plugins _collections.js _path.js _transforms.js addAttributesToSVGElement.js addClassesToSVGElement.js cleanupAttrs.js cleanupEnableBackground.js cleanupIDs.js cleanupListOfValues.js cleanupNumericValues.js collapseGroups.js convertColors.js convertEllipseToCircle.js convertPathData.js convertShapeToPath.js convertStyleToAttrs.js convertTransform.js inlineStyles.js mergePaths.js minifyStyles.js moveElemsAttrsToGroup.js moveGroupAttrsToElems.js prefixIds.js removeAttributesBySelector.js removeAttrs.js removeComments.js removeDesc.js removeDimensions.js removeDoctype.js removeEditorsNSData.js removeElementsByAttr.js removeEmptyAttrs.js removeEmptyContainers.js removeEmptyText.js removeHiddenElems.js removeMetadata.js removeNonInheritableGroupAttrs.js removeOffCanvasPaths.js removeRasterImages.js removeScriptElement.js removeStyleElement.js removeTitle.js removeUnknownsAndDefaults.js removeUnusedNS.js removeUselessDefs.js removeUselessStrokeAndFill.js removeViewBox.js removeXMLNS.js removeXMLProcInst.js reusePaths.js sortAttrs.js sortDefsChildren.js symbol-tree README.md lib SymbolTree.js SymbolTreeNode.js TreeIterator.js TreePosition.js package.json 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 node_modules 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 pack.js package.json sandbox.js 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 pack.js parse.js path-reservations.js pax.js read-entry.js replace.js types.js unpack.js update.js warn-mixin.js winchars.js write-entry.js package.json tcp-port-used README.md index.js node_modules debug CHANGELOG.md README.md dist debug.js package.json src browser.js common.js index.js node.js package.json test.js term-size index.d.ts index.js package.json readme.md terminal-link index.d.ts index.js package.json readme.md terser CHANGELOG.md PATRONS.md README.md dist bundle.js bundle.min.js node_modules commander CHANGELOG.md Readme.md index.js package.json typings index.d.ts package.json tools colorless-console.js domprops.js exit.js node.js props.html terser.d.ts test-exclude CHANGELOG.md LICENSE.txt README.md index.js is-outside-dir-posix.js is-outside-dir-win32.js is-outside-dir.js package.json text-encoding-utf-8 LICENSE.md README.md lib encoding.js encoding.lib.js package.json src encoding.js polyfill.js throat README.md index.d.ts index.js package.json through2 LICENSE.md README.md package.json through2.js timers-browserify CHANGELOG.md LICENSE.md README.md main.js package.json timsort LICENSE.md README.md build timsort.js timsort.min.js index.js package.json src timsort.js tiny-inflate index.js package.json readme.md test index.js lorem.txt tmpl .travis.yml lib tmpl.js package.json readme.md 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-readable-stream index.js package.json readme.md to-regex-range README.md index.js package.json to-regex README.md index.js package.json toidentifier README.md index.js package.json touch README.md bin nodetouch.js index.js package.json tough-cookie README.md lib cookie.js memstore.js pathMatch.js permuteDomain.js pubsuffix-psl.js store.js version.js package.json tr46 LICENSE.md README.md index.js lib mappingTable.json regexes.js statusMapping.js package.json trim-repeated index.js package.json readme.md ts-mixer CHANGELOG.md README.md dist decorator.d.ts decorator.js index.d.ts index.js mixin-tracking.d.ts mixin-tracking.js mixins.d.ts mixins.js proxy.d.ts proxy.js settings.d.ts settings.js types.d.ts types.js util.d.ts util.js package.json tslib CopyrightNotice.txt LICENSE.txt README.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-check README.md lib check.js index.js parse-type.js package.json type-detect README.md index.js package.json type-detect.js type-fest index.d.ts package.json readme.md source basic.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 readonly-deep.d.ts require-at-least-one.d.ts require-exactly-one.d.ts set-optional.d.ts set-required.d.ts typedarray-to-buffer .airtap.yml .travis.yml README.md index.js package.json test basic.js typedarray .travis.yml example tarray.js index.js package.json test server undef_globals.js tarray.js u3 README.md index.js lib cache.js eachCombination.js index.js package.json uncss LICENSE.md README.md node_modules acorn-globals README.md index.js package.json acorn-walk CHANGELOG.md README.md dist walk.js package.json acorn CHANGELOG.md README.md dist acorn.d.ts acorn.js bin.js package.json commander CHANGELOG.md Readme.md index.js package.json typings index.d.ts cssom LICENSE.txt lib CSSDocumentRule.js CSSFontFaceRule.js CSSHostRule.js CSSImportRule.js CSSKeyframeRule.js CSSKeyframesRule.js CSSMediaRule.js CSSOM.js CSSRule.js CSSStyleDeclaration.js CSSStyleRule.js CSSStyleSheet.js CSSSupportsRule.js CSSValue.js CSSValueExpression.js MatcherList.js MediaList.js StyleSheet.js clone.js index.js parse.js package.json cssstyle .eslintrc.js .travis.yml MIT-LICENSE.txt README.md lib CSSStyleDeclaration.js allExtraProperties.js allProperties.js constants.js implementedProperties.js named_colors.json parsers.js properties.js properties azimuth.js background.js backgroundAttachment.js backgroundColor.js backgroundImage.js backgroundPosition.js backgroundRepeat.js border.js borderBottom.js borderBottomColor.js borderBottomStyle.js borderBottomWidth.js borderCollapse.js borderColor.js borderLeft.js borderLeftColor.js borderLeftStyle.js borderLeftWidth.js borderRight.js borderRightColor.js borderRightStyle.js borderRightWidth.js borderSpacing.js borderStyle.js borderTop.js borderTopColor.js borderTopStyle.js borderTopWidth.js borderWidth.js bottom.js clear.js clip.js color.js cssFloat.js flex.js flexBasis.js flexGrow.js flexShrink.js float.js floodColor.js font.js fontFamily.js fontSize.js fontStyle.js fontVariant.js fontWeight.js height.js left.js lightingColor.js lineHeight.js margin.js marginBottom.js marginLeft.js marginRight.js marginTop.js opacity.js outlineColor.js padding.js paddingBottom.js paddingLeft.js paddingRight.js paddingTop.js right.js stopColor.js textLineThroughColor.js textOverlineColor.js textUnderlineColor.js top.js webkitBorderAfterColor.js webkitBorderBeforeColor.js webkitBorderEndColor.js webkitBorderStartColor.js webkitColumnRuleColor.js webkitMatchNearestMailBlockquoteColor.js webkitTapHighlightColor.js webkitTextEmphasisColor.js webkitTextFillColor.js webkitTextStrokeColor.js width.js utils getBasicPropertyDescriptor.js package.json scripts download_latest_properties.js generate_implemented_properties.js generate_properties.js tests tests.js data-urls LICENSE.txt README.md lib parser.js utils.js package.json domexception LICENSE.txt README.md lib DOMException-impl.js DOMException.js legacy-error-codes.json public-api.js utils.js package.json html-encoding-sniffer LICENSE.txt README.md lib html-encoding-sniffer.js package.json is-absolute-url index.d.ts index.js package.json readme.md jsdom Changelog.md LICENSE.txt README.md lib api.js jsdom browser Window.js default-stylesheet.js not-implemented.js parser html.js index.js xml.js resources async-resource-queue.js no-op-resource-loader.js per-document-resource-loader.js request-manager.js resource-loader.js resource-queue.js level2 style.js level3 xpath.js living aborting AbortController-impl.js AbortSignal-impl.js attributes.js attributes Attr-impl.js NamedNodeMap-impl.js constraint-validation DefaultConstraintValidation-impl.js ValidityState-impl.js domparsing DOMParser-impl.js parse5-adapter-serialization.js serialization.js events CloseEvent-impl.js CompositionEvent-impl.js CustomEvent-impl.js ErrorEvent-impl.js Event-impl.js EventModifierMixin-impl.js EventTarget-impl.js FocusEvent-impl.js HashChangeEvent-impl.js InputEvent-impl.js KeyboardEvent-impl.js MessageEvent-impl.js MouseEvent-impl.js PageTransitionEvent-impl.js PopStateEvent-impl.js ProgressEvent-impl.js StorageEvent-impl.js TouchEvent-impl.js UIEvent-impl.js WheelEvent-impl.js file-api Blob-impl.js File-impl.js FileList-impl.js FileReader-impl.js generated AbortController.js AbortSignal.js AddEventListenerOptions.js AssignedNodesOptions.js Attr.js BarProp.js BinaryType.js Blob.js BlobPropertyBag.js CDATASection.js CanPlayTypeResult.js CharacterData.js ChildNode.js CloseEvent.js CloseEventInit.js Comment.js CompositionEvent.js CompositionEventInit.js CustomEvent.js CustomEventInit.js DOMImplementation.js DOMParser.js DOMStringMap.js DOMTokenList.js Document.js DocumentFragment.js DocumentReadyState.js DocumentType.js Element.js ElementCSSInlineStyle.js ElementContentEditable.js ElementCreationOptions.js EndingType.js ErrorEvent.js ErrorEventInit.js Event.js EventInit.js EventListenerOptions.js EventModifierInit.js EventTarget.js External.js File.js FileList.js FilePropertyBag.js FileReader.js FocusEvent.js FocusEventInit.js FormData.js GetRootNodeOptions.js GlobalEventHandlers.js HTMLAnchorElement.js HTMLAreaElement.js HTMLAudioElement.js HTMLBRElement.js HTMLBaseElement.js HTMLBodyElement.js HTMLButtonElement.js HTMLCanvasElement.js HTMLCollection.js HTMLDListElement.js HTMLDataElement.js HTMLDataListElement.js HTMLDetailsElement.js HTMLDialogElement.js HTMLDirectoryElement.js HTMLDivElement.js HTMLElement.js HTMLEmbedElement.js HTMLFieldSetElement.js HTMLFontElement.js HTMLFormElement.js HTMLFrameElement.js HTMLFrameSetElement.js HTMLHRElement.js HTMLHeadElement.js HTMLHeadingElement.js HTMLHtmlElement.js HTMLHyperlinkElementUtils.js HTMLIFrameElement.js HTMLImageElement.js HTMLInputElement.js HTMLLIElement.js HTMLLabelElement.js HTMLLegendElement.js HTMLLinkElement.js HTMLMapElement.js HTMLMarqueeElement.js HTMLMediaElement.js HTMLMenuElement.js HTMLMetaElement.js HTMLMeterElement.js HTMLModElement.js HTMLOListElement.js HTMLObjectElement.js HTMLOptGroupElement.js HTMLOptionElement.js HTMLOptionsCollection.js HTMLOutputElement.js HTMLParagraphElement.js HTMLParamElement.js HTMLPictureElement.js HTMLPreElement.js HTMLProgressElement.js HTMLQuoteElement.js HTMLScriptElement.js HTMLSelectElement.js HTMLSlotElement.js HTMLSourceElement.js HTMLSpanElement.js HTMLStyleElement.js HTMLTableCaptionElement.js HTMLTableCellElement.js HTMLTableColElement.js HTMLTableElement.js HTMLTableRowElement.js HTMLTableSectionElement.js HTMLTemplateElement.js HTMLTextAreaElement.js HTMLTimeElement.js HTMLTitleElement.js HTMLTrackElement.js HTMLUListElement.js HTMLUnknownElement.js HTMLVideoElement.js HashChangeEvent.js HashChangeEventInit.js History.js InputEvent.js InputEventInit.js KeyboardEvent.js KeyboardEventInit.js LinkStyle.js Location.js MessageEvent.js MessageEventInit.js MimeType.js MimeTypeArray.js MouseEvent.js MouseEventInit.js MutationObserver.js MutationObserverInit.js MutationRecord.js NamedNodeMap.js Navigator.js NavigatorConcurrentHardware.js NavigatorCookies.js NavigatorID.js NavigatorLanguage.js NavigatorOnLine.js NavigatorPlugins.js Node.js NodeIterator.js NodeList.js NonDocumentTypeChildNode.js NonElementParentNode.js PageTransitionEvent.js PageTransitionEventInit.js ParentNode.js Performance.js Plugin.js PluginArray.js PopStateEvent.js PopStateEventInit.js ProcessingInstruction.js ProgressEvent.js ProgressEventInit.js SVGAnimatedString.js SVGBoundingBoxOptions.js SVGElement.js SVGGraphicsElement.js SVGNumber.js SVGSVGElement.js SVGStringList.js SVGTests.js SVGTitleElement.js Screen.js ScrollBehavior.js ScrollIntoViewOptions.js ScrollLogicalPosition.js ScrollOptions.js ScrollRestoration.js SelectionMode.js ShadowRoot.js ShadowRootInit.js ShadowRootMode.js Slotable.js Storage.js StorageEvent.js StorageEventInit.js SupportedType.js Text.js TextTrackKind.js TouchEvent.js TouchEventInit.js TreeWalker.js UIEvent.js UIEventInit.js ValidityState.js VisibilityState.js WebSocket.js WheelEvent.js WheelEventInit.js WindowEventHandlers.js XMLDocument.js XMLHttpRequestEventTarget.js XMLHttpRequestUpload.js utils.js helpers create-event-accessor.js custom-elements.js dates-and-times.js document-base-url.js events.js focusing.js form-controls.js internal-constants.js json.js mutation-observers.js namespaces.js ordered-set.js runtime-script-errors.js selectors.js shadow-dom.js strings.js stylesheets.js svg basic-types.js text.js traversal.js validate-names.js wrap-cookie-jar-for-request.js hr-time Performance-impl.js index.js mutation-observer MutationObserver-impl.js MutationRecord-impl.js named-properties-window.js navigator MimeType-impl.js MimeTypeArray-impl.js Navigator-impl.js NavigatorConcurrentHardware-impl.js NavigatorCookies-impl.js NavigatorID-impl.js NavigatorLanguage-impl.js NavigatorOnLine-impl.js NavigatorPlugins-impl.js Plugin-impl.js PluginArray-impl.js node-document-position.js node-filter.js node-type.js node.js nodes CDATASection-impl.js CharacterData-impl.js ChildNode-impl.js Comment-impl.js DOMImplementation-impl.js DOMStringMap-impl.js DOMTokenList-impl.js Document-impl.js DocumentFragment-impl.js DocumentType-impl.js Element-impl.js ElementCSSInlineStyle-impl.js ElementContentEditable-impl.js GlobalEventHandlers-impl.js HTMLAnchorElement-impl.js HTMLAndSVGElementShared-impl.js HTMLAreaElement-impl.js HTMLAudioElement-impl.js HTMLBRElement-impl.js HTMLBaseElement-impl.js HTMLBodyElement-impl.js HTMLButtonElement-impl.js HTMLCanvasElement-impl.js HTMLCollection-impl.js HTMLDListElement-impl.js HTMLDataElement-impl.js HTMLDataListElement-impl.js HTMLDetailsElement-impl.js HTMLDialogElement-impl.js HTMLDirectoryElement-impl.js HTMLDivElement-impl.js HTMLElement-impl.js HTMLEmbedElement-impl.js HTMLFieldSetElement-impl.js HTMLFontElement-impl.js HTMLFormElement-impl.js HTMLFrameElement-impl.js HTMLFrameSetElement-impl.js HTMLHRElement-impl.js HTMLHeadElement-impl.js HTMLHeadingElement-impl.js HTMLHtmlElement-impl.js HTMLHyperlinkElementUtils-impl.js HTMLIFrameElement-impl.js HTMLImageElement-impl.js HTMLInputElement-impl.js HTMLLIElement-impl.js HTMLLabelElement-impl.js HTMLLegendElement-impl.js HTMLLinkElement-impl.js HTMLMapElement-impl.js HTMLMarqueeElement-impl.js HTMLMediaElement-impl.js HTMLMenuElement-impl.js HTMLMetaElement-impl.js HTMLMeterElement-impl.js HTMLModElement-impl.js HTMLOListElement-impl.js HTMLObjectElement-impl.js HTMLOptGroupElement-impl.js HTMLOptionElement-impl.js HTMLOptionsCollection-impl.js HTMLOutputElement-impl.js HTMLParagraphElement-impl.js HTMLParamElement-impl.js HTMLPictureElement-impl.js HTMLPreElement-impl.js HTMLProgressElement-impl.js HTMLQuoteElement-impl.js HTMLScriptElement-impl.js HTMLSelectElement-impl.js HTMLSlotElement-impl.js HTMLSourceElement-impl.js HTMLSpanElement-impl.js HTMLStyleElement-impl.js HTMLTableCaptionElement-impl.js HTMLTableCellElement-impl.js HTMLTableColElement-impl.js HTMLTableElement-impl.js HTMLTableRowElement-impl.js HTMLTableSectionElement-impl.js HTMLTemplateElement-impl.js HTMLTextAreaElement-impl.js HTMLTimeElement-impl.js HTMLTitleElement-impl.js HTMLTrackElement-impl.js HTMLUListElement-impl.js HTMLUnknownElement-impl.js HTMLVideoElement-impl.js LinkStyle-impl.js Node-impl.js NodeList-impl.js NonDocumentTypeChildNode-impl.js NonElementParentNode-impl.js ParentNode-impl.js ProcessingInstruction-impl.js SVGElement-impl.js SVGGraphicsElement-impl.js SVGSVGElement-impl.js SVGTests-impl.js SVGTitleElement-impl.js ShadowRoot-impl.js Slotable-impl.js Text-impl.js WindowEventHandlers-impl.js XMLDocument-impl.js post-message.js register-elements.js svg SVGAnimatedString-impl.js SVGListBase.js SVGNumber-impl.js SVGStringList-impl.js traversal NodeIterator-impl.js TreeWalker-impl.js helpers.js websockets WebSocket-impl-browser.js WebSocket-impl.js webstorage Storage-impl.js window BarProp-impl.js External-impl.js History-impl.js Location-impl.js Screen-impl.js SessionHistory.js navigation.js xhr-sync-worker.js xhr-utils.js xhr FormData-impl.js XMLHttpRequestEventTarget-impl.js XMLHttpRequestUpload-impl.js xmlhttprequest-symbols.js xmlhttprequest.js named-properties-tracker.js utils.js virtual-console.js vm-shim.js package.json parse5 README.md lib common doctype.js error-codes.js foreign-content.js html.js unicode.js extensions error-reporting mixin-base.js parser-mixin.js preprocessor-mixin.js tokenizer-mixin.js location-info open-element-stack-mixin.js parser-mixin.js tokenizer-mixin.js position-tracking preprocessor-mixin.js index.js parser formatting-element-list.js index.js open-element-stack.js serializer index.js tokenizer index.js named-entity-data.js preprocessor.js tree-adapters default.js utils merge-options.js mixin.js package.json 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 saxes CHANGELOG.md README.md lib saxes.d.ts saxes.js package.json tough-cookie README.md lib cookie.js memstore.js pathMatch.js permuteDomain.js pubsuffix-psl.js store.js version.js package.json tr46 LICENSE.md README.md index.js lib mappingTable.json regexes.js package.json w3c-xmlserializer README.md lib XMLSerializer-impl.js XMLSerializer.js attributes.js constants.js index.js serialization.js utils.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 URLSearchParams-impl.js URLSearchParams.js infra.js public-api.js url-state-machine.js urlencoded.js utils.js package.json ws README.md browser.js index.js lib buffer-util.js constants.js event-target.js extension.js permessage-deflate.js receiver.js sender.js validation.js websocket-server.js websocket.js package.json package.json src jsdom.js lib.js uncss.js utility.js undefsafe .travis.yml README.md example.js lib undefsafe.js node_modules 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 ms index.js license.md package.json readme.md package.json 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 unicode-trie README.md builder.coffee builder.js coverage.js index.coffee index.js package.json test test.coffee union-value README.md index.js package.json uniq README.md package.json test test.js uniq.js uniqs .travis.yml README.md index.js package.json test.js unique-string index.d.ts index.js package.json readme.md universal-url README.md browser.js index.js node_modules tr46 LICENSE.md README.md index.js lib mappingTable.json regexes.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 URLSearchParams-impl.js URLSearchParams.js infra.js public-api.js url-state-machine.js urlencoded.js utils.js package.json package.json universalify README.md index.js package.json unorm LICENSE.md README.md lib unorm.js package.json unquote 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 update-notifier check.js index.js node_modules chalk index.d.ts package.json readme.md source index.js templates.js util.js package.json readme.md 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 urix index.js package.json readme.md test index.js url-parse-lax index.js node_modules prepend-http index.js package.json readme.md package.json readme.md 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 usb .travis.yml Readme.md libusb .private README.txt bd.cmd bm.sh bwince.cmd post-rewrite.sh pre-commit.sh wbs.txt wbs_wince.txt INSTALL_WIN.txt 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 xusb.c libusb core.c descriptor.c hotplug.c hotplug.h io.c libusb.h libusbi.h os darwin_usb.c darwin_usb.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 threads_posix.c threads_posix.h threads_windows.c threads_windows.h wince_usb.c wince_usb.h windows_common.h windows_usb.c windows_usb.h strerror.c sync.c version.h version_nano.h msvc 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_wince.sln missing.c missing.h stdint.h tests libusb_testlib.h stress.c testlib.c libusb_config config.h node_modules 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 package.json src helpers.h node_usb.h polyfill.h uv_async_queue.h test usb.coffee usb.js use README.md index.js package.json util-deprecate History.md README.md browser.js node.js package.json util.promisify .github FUNDING.yml workflows rebase.yml .travis.yml CHANGELOG.md README.md auto.js implementation.js index.js node_modules es-abstract .github FUNDING.yml workflows codeql-analysis.yml rebase.yml .travis.yml 2015 AbstractEqualityComparison.js AbstractRelationalComparison.js AdvanceStringIndex.js ArrayCreate.js ArraySetLength.js ArraySpeciesCreate.js Call.js CanonicalNumericIndexString.js CompletePropertyDescriptor.js CreateDataProperty.js CreateDataPropertyOrThrow.js CreateHTML.js CreateIterResultObject.js CreateListFromArrayLike.js CreateMethodProperty.js DateFromTime.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js DefinePropertyOrThrow.js DeletePropertyOrThrow.js EnumerableOwnNames.js FromPropertyDescriptor.js Get.js GetIterator.js GetMethod.js GetOwnPropertyKeys.js GetPrototypeFromConstructor.js GetSubstitution.js GetV.js HasOwnProperty.js HasProperty.js HourFromTime.js InLeapYear.js InstanceofOperator.js Invoke.js IsAccessorDescriptor.js IsArray.js IsCallable.js IsConcatSpreadable.js IsConstructor.js IsDataDescriptor.js IsExtensible.js IsGenericDescriptor.js IsInteger.js IsPromise.js IsPropertyDescriptor.js IsPropertyKey.js IsRegExp.js IteratorClose.js IteratorComplete.js IteratorNext.js IteratorStep.js IteratorValue.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js ObjectCreate.js OrdinaryDefineOwnProperty.js OrdinaryGetOwnProperty.js OrdinaryHasInstance.js OrdinaryHasProperty.js RegExpExec.js RequireObjectCoercible.js SameValue.js SameValueZero.js SecFromTime.js Set.js SetFunctionName.js SetIntegrityLevel.js SpeciesConstructor.js StrictEqualityComparison.js SymbolDescriptiveString.js TestIntegrityLevel.js TimeClip.js TimeFromYear.js TimeWithinDay.js ToBoolean.js ToDateString.js ToInt16.js ToInt32.js ToInt8.js ToInteger.js ToLength.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToPropertyKey.js ToString.js ToUint16.js ToUint32.js ToUint8.js ToUint8Clamp.js Type.js ValidateAndApplyPropertyDescriptor.js WeekDay.js YearFromTime.js modulo.js msFromTime.js thisBooleanValue.js thisNumberValue.js thisStringValue.js thisTimeValue.js 2016 AbstractEqualityComparison.js AbstractRelationalComparison.js AdvanceStringIndex.js ArrayCreate.js ArraySetLength.js ArraySpeciesCreate.js Call.js CanonicalNumericIndexString.js CompletePropertyDescriptor.js CreateDataProperty.js CreateDataPropertyOrThrow.js CreateHTML.js CreateIterResultObject.js CreateListFromArrayLike.js CreateMethodProperty.js DateFromTime.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js DefinePropertyOrThrow.js DeletePropertyOrThrow.js EnumerableOwnNames.js FromPropertyDescriptor.js Get.js GetIterator.js GetMethod.js GetOwnPropertyKeys.js GetPrototypeFromConstructor.js GetSubstitution.js GetV.js HasOwnProperty.js HasProperty.js HourFromTime.js InLeapYear.js InstanceofOperator.js Invoke.js IsAccessorDescriptor.js IsArray.js IsCallable.js IsConcatSpreadable.js IsConstructor.js IsDataDescriptor.js IsExtensible.js IsGenericDescriptor.js IsInteger.js IsPromise.js IsPropertyDescriptor.js IsPropertyKey.js IsRegExp.js IterableToArrayLike.js IteratorClose.js IteratorComplete.js IteratorNext.js IteratorStep.js IteratorValue.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js ObjectCreate.js OrdinaryDefineOwnProperty.js OrdinaryGetOwnProperty.js OrdinaryGetPrototypeOf.js OrdinaryHasInstance.js OrdinaryHasProperty.js OrdinarySetPrototypeOf.js RegExpExec.js RequireObjectCoercible.js SameValue.js SameValueNonNumber.js SameValueZero.js SecFromTime.js Set.js SetFunctionName.js SetIntegrityLevel.js SpeciesConstructor.js StrictEqualityComparison.js SymbolDescriptiveString.js TestIntegrityLevel.js TimeClip.js TimeFromYear.js TimeWithinDay.js ToBoolean.js ToDateString.js ToInt16.js ToInt32.js ToInt8.js ToInteger.js ToLength.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToPropertyKey.js ToString.js ToUint16.js ToUint32.js ToUint8.js ToUint8Clamp.js Type.js ValidateAndApplyPropertyDescriptor.js WeekDay.js YearFromTime.js modulo.js msFromTime.js thisBooleanValue.js thisNumberValue.js thisStringValue.js thisTimeValue.js 2017 AbstractEqualityComparison.js AbstractRelationalComparison.js AdvanceStringIndex.js ArrayCreate.js ArraySetLength.js ArraySpeciesCreate.js Call.js CanonicalNumericIndexString.js CompletePropertyDescriptor.js CreateDataProperty.js CreateDataPropertyOrThrow.js CreateHTML.js CreateIterResultObject.js CreateListFromArrayLike.js CreateMethodProperty.js DateFromTime.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js DefinePropertyOrThrow.js DeletePropertyOrThrow.js EnumerableOwnProperties.js FromPropertyDescriptor.js Get.js GetIterator.js GetMethod.js GetOwnPropertyKeys.js GetPrototypeFromConstructor.js GetSubstitution.js GetV.js HasOwnProperty.js HasProperty.js HourFromTime.js InLeapYear.js InstanceofOperator.js Invoke.js IsAccessorDescriptor.js IsArray.js IsCallable.js IsConcatSpreadable.js IsConstructor.js IsDataDescriptor.js IsExtensible.js IsGenericDescriptor.js IsInteger.js IsPromise.js IsPropertyDescriptor.js IsPropertyKey.js IsRegExp.js IterableToList.js IteratorClose.js IteratorComplete.js IteratorNext.js IteratorStep.js IteratorValue.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js ObjectCreate.js OrdinaryDefineOwnProperty.js OrdinaryGetOwnProperty.js OrdinaryGetPrototypeOf.js OrdinaryHasInstance.js OrdinaryHasProperty.js OrdinarySetPrototypeOf.js RegExpExec.js RequireObjectCoercible.js SameValue.js SameValueNonNumber.js SameValueZero.js SecFromTime.js Set.js SetFunctionName.js SetIntegrityLevel.js SpeciesConstructor.js StrictEqualityComparison.js SymbolDescriptiveString.js TestIntegrityLevel.js TimeClip.js TimeFromYear.js TimeWithinDay.js ToBoolean.js ToDateString.js ToIndex.js ToInt16.js ToInt32.js ToInt8.js ToInteger.js ToLength.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToPropertyKey.js ToString.js ToUint16.js ToUint32.js ToUint8.js ToUint8Clamp.js Type.js ValidateAndApplyPropertyDescriptor.js WeekDay.js YearFromTime.js modulo.js msFromTime.js thisBooleanValue.js thisNumberValue.js thisStringValue.js thisTimeValue.js 2018 AbstractEqualityComparison.js AbstractRelationalComparison.js AdvanceStringIndex.js ArrayCreate.js ArraySetLength.js ArraySpeciesCreate.js Call.js CanonicalNumericIndexString.js CompletePropertyDescriptor.js CopyDataProperties.js CreateDataProperty.js CreateDataPropertyOrThrow.js CreateHTML.js CreateIterResultObject.js CreateListFromArrayLike.js CreateMethodProperty.js DateFromTime.js DateString.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js DefinePropertyOrThrow.js DeletePropertyOrThrow.js EnumerableOwnPropertyNames.js FromPropertyDescriptor.js Get.js GetIterator.js GetMethod.js GetOwnPropertyKeys.js GetPrototypeFromConstructor.js GetSubstitution.js GetV.js HasOwnProperty.js HasProperty.js HourFromTime.js InLeapYear.js InstanceofOperator.js Invoke.js IsAccessorDescriptor.js IsArray.js IsCallable.js IsConcatSpreadable.js IsConstructor.js IsDataDescriptor.js IsExtensible.js IsGenericDescriptor.js IsInteger.js IsPromise.js IsPropertyKey.js IsRegExp.js IsStringPrefix.js IterableToList.js IteratorClose.js IteratorComplete.js IteratorNext.js IteratorStep.js IteratorValue.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js NumberToString.js ObjectCreate.js OrdinaryDefineOwnProperty.js OrdinaryGetOwnProperty.js OrdinaryGetPrototypeOf.js OrdinaryHasInstance.js OrdinaryHasProperty.js OrdinarySetPrototypeOf.js PromiseResolve.js RegExpExec.js RequireObjectCoercible.js SameValue.js SameValueNonNumber.js SameValueZero.js SecFromTime.js Set.js SetFunctionName.js SetIntegrityLevel.js SpeciesConstructor.js StrictEqualityComparison.js SymbolDescriptiveString.js TestIntegrityLevel.js TimeClip.js TimeFromYear.js TimeString.js TimeWithinDay.js ToBoolean.js ToDateString.js ToIndex.js ToInt16.js ToInt32.js ToInt8.js ToInteger.js ToLength.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToPropertyKey.js ToString.js ToUint16.js ToUint32.js ToUint8.js ToUint8Clamp.js Type.js ValidateAndApplyPropertyDescriptor.js WeekDay.js YearFromTime.js modulo.js msFromTime.js thisBooleanValue.js thisNumberValue.js thisStringValue.js thisSymbolValue.js thisTimeValue.js 2019 AbstractEqualityComparison.js AbstractRelationalComparison.js AddEntriesFromIterable.js AdvanceStringIndex.js ArrayCreate.js ArraySetLength.js ArraySpeciesCreate.js Call.js CanonicalNumericIndexString.js CompletePropertyDescriptor.js CopyDataProperties.js CreateDataProperty.js CreateDataPropertyOrThrow.js CreateHTML.js CreateIterResultObject.js CreateListFromArrayLike.js CreateMethodProperty.js DateFromTime.js DateString.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js DefinePropertyOrThrow.js DeletePropertyOrThrow.js EnumerableOwnPropertyNames.js FlattenIntoArray.js FromPropertyDescriptor.js Get.js GetIterator.js GetMethod.js GetOwnPropertyKeys.js GetPrototypeFromConstructor.js GetSubstitution.js GetV.js HasOwnProperty.js HasProperty.js HourFromTime.js InLeapYear.js InstanceofOperator.js Invoke.js IsAccessorDescriptor.js IsArray.js IsCallable.js IsConcatSpreadable.js IsConstructor.js IsDataDescriptor.js IsExtensible.js IsGenericDescriptor.js IsInteger.js IsPromise.js IsPropertyKey.js IsRegExp.js IsStringPrefix.js IterableToList.js IteratorClose.js IteratorComplete.js IteratorNext.js IteratorStep.js IteratorValue.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js NumberToString.js ObjectCreate.js OrdinaryDefineOwnProperty.js OrdinaryGetOwnProperty.js OrdinaryGetPrototypeOf.js OrdinaryHasInstance.js OrdinaryHasProperty.js OrdinarySetPrototypeOf.js PromiseResolve.js RegExpExec.js RequireObjectCoercible.js SameValue.js SameValueNonNumber.js SameValueZero.js SecFromTime.js Set.js SetFunctionName.js SetIntegrityLevel.js SpeciesConstructor.js StrictEqualityComparison.js SymbolDescriptiveString.js TestIntegrityLevel.js TimeClip.js TimeFromYear.js TimeString.js TimeWithinDay.js ToBoolean.js ToDateString.js ToIndex.js ToInt16.js ToInt32.js ToInt8.js ToInteger.js ToLength.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToPropertyKey.js ToString.js ToUint16.js ToUint32.js ToUint8.js ToUint8Clamp.js TrimString.js Type.js ValidateAndApplyPropertyDescriptor.js WeekDay.js YearFromTime.js modulo.js msFromTime.js thisBooleanValue.js thisNumberValue.js thisStringValue.js thisSymbolValue.js thisTimeValue.js 5 AbstractEqualityComparison.js AbstractRelationalComparison.js CheckObjectCoercible.js DateFromTime.js Day.js DayFromYear.js DayWithinYear.js DaysInYear.js FromPropertyDescriptor.js HourFromTime.js InLeapYear.js IsAccessorDescriptor.js IsCallable.js IsDataDescriptor.js IsGenericDescriptor.js IsPropertyDescriptor.js MakeDate.js MakeDay.js MakeTime.js MinFromTime.js MonthFromTime.js SameValue.js SecFromTime.js StrictEqualityComparison.js TimeClip.js TimeFromYear.js TimeWithinDay.js ToBoolean.js ToInt32.js ToInteger.js ToNumber.js ToObject.js ToPrimitive.js ToPropertyDescriptor.js ToString.js ToUint16.js ToUint32.js Type.js WeekDay.js YearFromTime.js modulo.js msFromTime.js CHANGELOG.md GetIntrinsic.js README.md es2015.js es2016.js es2017.js es2018.js es2019.js es5.js es6.js es7.js helpers DefineOwnProperty.js OwnPropertyKeys.js assertRecord.js assign.js callBind.js callBound.js every.js forEach.js getInferredName.js getIteratorMethod.js getOwnPropertyDescriptor.js getProto.js getSymbolDescription.js isFinite.js isNaN.js isPrefixOf.js isPrimitive.js isPropertyDescriptor.js isSamePropertyDescriptor.js maxSafeInteger.js mod.js padTimeComponent.js regexTester.js setProto.js sign.js timeConstants.js index.js operations 2015.js 2016.js 2017.js 2018.js 2019.js package.json test GetIntrinsic.js diffOps.js es2015.js es2016.js es2017.js es2018.js es2019.js es5.js es6.js es7.js helpers OwnPropertyKeys.js assertRecord.js createBoundESNamespace.js defineProperty.js getSymbolDescription.js runManifestTest.js values.js index.js tests.js package.json polyfill.js shim.js util CHANGELOG.md README.md node_modules inherits README.md inherits.js inherits_browser.js package.json package.json support isBuffer.js isBufferBrowser.js util.js 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 v8-compile-cache CHANGELOG.md README.md package.json v8-compile-cache.js v8-to-istanbul CHANGELOG.md LICENSE.txt README.md index.d.ts index.js lib branch.js function.js line.js source.js v8-to-istanbul.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 v8flags README.md config-path.js index.js package.json validate-npm-package-license README.md index.js package.json vendors index.json package.json readme.md verror CHANGES.md CONTRIBUTING.md README.md lib verror.js package.json visitor-as .travis.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 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 vlq CHANGELOG.md README.md dist vlq.js package.json src vlq.js vm-browserify .github FUNDING.yml .travis.yml CHANGELOG.md example run bundle.js entry.js index.html server.js index.js package.json security.md test vm.js w3c-hr-time CHANGELOG.md LICENSE.md README.md index.js lib calculate-clock-offset.js clock-is-accurate.js global-monotonic-clock.js performance.js utils.js package.json w3c-xmlserializer LICENSE.md README.md lib attributes.js constants.js serialize.js package.json walker .travis.yml lib walker.js package.json readme.md wcwidth Readme.md combining.js docs index.md index.js package.json test index.js webidl-conversions LICENSE.md README.md lib index.js package.json whatwg-encoding LICENSE.txt README.md lib labels-to-names.json supported-names.json whatwg-encoding.js package.json whatwg-mimetype LICENSE.txt README.md lib mime-type.js parser.js serializer.js utils.js package.json whatwg-url LICENSE.txt README.md dist Function.js URL-impl.js URL.js URLSearchParams-impl.js URLSearchParams.js VoidFunction.js encoding.js infra.js percent-encoding.js url-state-machine.js urlencoded.js utils.js index.js package.json webidl2js-wrapper.js which-module CHANGELOG.md README.md index.js package.json which-pm-runs README.md index.js package.json which CHANGELOG.md README.md package.json which.js wide-align README.md align.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 widest-line index.d.ts index.js package.json readme.md 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 write-file-atomic CHANGELOG.md README.md index.js package.json ws README.md browser.js index.js lib buffer-util.js constants.js event-target.js extension.js limiter.js permessage-deflate.js receiver.js sender.js stream.js validation.js websocket-server.js websocket.js package.json xdg-basedir index.d.ts index.js package.json readme.md xml-name-validator LICENSE.txt README.md lib generated-parser.js xml-name-validator.js package.json xmlchars README.md package.json xml 1.0 ed4.d.ts ed4.js ed5.d.ts ed5.js 1.1 ed2.d.ts ed2.js xmlchars.d.ts xmlchars.js xmlns 1.0 ed3.d.ts ed3.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 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 | ancestry inference replacement evaluation introspection context removal modification family comments isXXX assertXXX Inspector mode only ----------- | | 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) | :----------: | EDITABLE DEFAULTS END OF EDITABLE DEFAULTS | :--------- | | :-------- | | :--- | Options END OF REPORT | :--: | nested-env-vars (C) package-lock.json package.json resources.txt www assets css style.css js campaign.js index.js preview.js style.js templates campaign.html index.html preview.html vendor jquery.countdown.min.js progressbar.js header.html publish-project.js web-config.json
# 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 # serve-static [![NPM Version][npm-version-image]][npm-url] [![NPM Downloads][npm-downloads-image]][npm-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) [appveyor-image]: https://badgen.net/appveyor/ci/dougwilson/serve-static/master?label=windows [appveyor-url]: https://ci.appveyor.com/project/dougwilson/serve-static [coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/serve-static/master [coveralls-url]: https://coveralls.io/r/expressjs/serve-static?branch=master [node-image]: https://badgen.net/npm/node/serve-static [node-url]: https://nodejs.org/en/download/ [npm-downloads-image]: https://badgen.net/npm/dm/serve-static [npm-url]: https://npmjs.org/package/serve-static [npm-version-image]: https://badgen.net/npm/v/serve-static [travis-image]: https://badgen.net/travis/expressjs/serve-static/master?label=linux [travis-url]: https://travis-ci.org/expressjs/serve-static # <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 # 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 ``` # 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). # 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._ # 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;tj@vision-media.ca&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. ## 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._ # postcss-minify-params [![Build Status][ci-img]][ci] > Minify at-rule params with PostCSS. ```css @media only screen and ( min-width: 400px, min-height: 500px ) { h2{ color:blue } } ``` ```css @media only screen and (min-width:400px,min-height:500px) { h2{ color:blue } } ``` ## Usage ```js postcss([ require('postcss-minify-params') ]) ``` See [PostCSS] docs for examples for your environment. ## Contributors See [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md). ## License MIT © [Bogdan Chadkin](mailto:trysound@yandex.ru) [PostCSS]: https://github.com/postcss/postcss [ci-img]: https://travis-ci.org/cssnano/postcss-minify-params.svg [ci]: https://travis-ci.org/cssnano/postcss-minify-params # isarray `Array#isArray` for older browsers and deprecated Node.js versions. [![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) __Just use Array.isArray directly__, unless you need to support those older versions. ## Usage ```js var isArray = require('isarray'); console.log(isArray([])); // => true console.log(isArray({})); // => false ``` ## Installation With [npm](https://npmjs.org) do ```bash $ npm install isarray ``` Then bundle for the browser with [browserify](https://github.com/substack/node-browserify). ## 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)! # 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 # 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. # [postcss][postcss]-minify-selectors > Minify selectors with PostCSS. ## Install With [npm](https://www.npmjs.com/package/postcss-minify-selectors) do: ``` npm install postcss-minify-selectors --save ``` ## Example ### Input ```css h1 + p, h2, h3, h2{color:blue} ``` ### Output ```css h1+p,h2,h3{color:blue} ``` For more examples see the [tests](test.js). ## Usage See the [PostCSS documentation](https://github.com/postcss/postcss#usage) for examples for your environment. ## Contributors See [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md). ## License MIT © [Ben Briggs](http://beneb.info) [postcss]: https://github.com/postcss/postcss # cssnano For documentation, please see the following links: * Repository: https://github.com/cssnano/cssnano * Website: http://cssnano.co # 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`. # 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><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 ## 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. 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). # 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 prettyFormat = require('pretty-format'); // CommonJS ``` ```js import 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 | | `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 | | `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 prettyFormat = require('pretty-format'); const ReactElement = prettyFormat.plugins.ReactElement; const ReactTestComponent = prettyFormat.plugins.ReactTestComponent; const React = require('react'); const renderer = require('react-test-renderer'); ``` ```js // ES2015 modules and destructuring assignment import prettyFormat from 'pretty-format'; const {ReactElement, ReactTestComponent} = prettyFormat.plugins; import React from 'react'; import renderer from 'react-test-renderer'; ``` ```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 | | `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], } */ ``` # [postcss][postcss]-normalize-url > [Normalize URLs](https://github.com/sindresorhus/normalize-url) with PostCSS. ## Install With [npm](https://npmjs.org/package/postcss-normalize-url) do: ``` npm install postcss-normalize-url --save ``` ## Example ### Input ```css h1 { background: url("http://site.com:80/image.jpg") } ``` ### Output ```css h1 { background: url(http://site.com/image.jpg) } ``` Note that this module will also try to normalize relative URLs, and is capable of stripping unnecessary quotes. For more examples, see the [tests](test.js). ## Usage See the [PostCSS documentation](https://github.com/postcss/postcss#usage) for examples for your environment. ## API ### normalize([options]) Please see the [normalize-url documentation][docs]. By default, `normalizeProtocol`, `stripFragment` & `stripWWW` are set to `false`. ## Contributors See [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md). ## License MIT © [Ben Briggs](http://beneb.info) [docs]: https://github.com/sindresorhus/normalize-url#options [postcss]: https://github.com/postcss/postcss # 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. 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 `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value components are invalid (`9999999999999999.4.7.4` is likely invalid). # [postcss][postcss]-convert-values > Convert values with PostCSS (e.g. ms -> s) ## Install With [npm](https://npmjs.org/package/postcss-convert-values) do: ``` npm install postcss-convert-values --save ``` ## Example This plugin reduces CSS size by converting values to use different units where possible; for example, `500ms` can be represented as `.5s`. You can read more about these units in [this article][csstricks]. ### Input ```css h1 { font-size: 16px; width: 0em } ``` ### Output ```css h1 { font-size: 1pc; width: 0 } ``` Note that this plugin only covers conversions for duration and absolute length values. For color conversions, use [postcss-colormin][colormin]. ## API ### convertValues([options]) #### options ##### length Type: `boolean` Default: `true` Pass `false` to disable conversion from `px` to other absolute length units, such as `pc` & `pt` & vice versa. ##### time Type: `boolean` Default: `true` Pass `false` to disable conversion from `ms` to `s` & vice versa. ##### angle Type: `boolean` Default: `true` Pass `false` to disable conversion from `deg` to `turn` & vice versa. ##### precision Type: `boolean|number` Default: `false` Specify any numeric value here to round `px` values to that many decimal places; for example, using `{precision: 2}` will round `6.66667px` to `6.67px`, and `{precision: 0}` will round it to `7px`. Passing `false` (the default) will leave these values as is. It is recommended for most use cases to set this option to `2`. ## Usage See the [PostCSS documentation](https://github.com/postcss/postcss#usage) for examples for your environment. ## Contributors See [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md). ## License MIT © [Ben Briggs](http://beneb.info) [postcss]: https://github.com/postcss/postcss [csstricks]: https://css-tricks.com/the-lengths-of-css/ # Char Regex [![Travis CI Build Status](https://img.shields.io/travis/com/Richienb/char-regex/master.svg?style=for-the-badge)](https://travis-ci.com/Richienb/char-regex) A regex to match any full character, considering weird character ranges. Tested on every single emoji and unicode character. Based on the Lodash implementation. [![NPM Badge](https://nodei.co/npm/char-regex.png)](https://npmjs.com/package/char-regex) ## Install ```sh npm install char-regex ``` ## Usage ```js const charRegex = require("char-regex"); "❤️👊🏽".match(/./); //=> ["", "", "", "", "", "", ""] "❤️👊🏽".match(charRegex()); //=> ["❤️", "👊🏽"] ``` ## API ### charRegex() # 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). # 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). # 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._ # 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._ # 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 # 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 --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 `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value components are invalid (`9999999999999999.4.7.4` is likely invalid). # 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) # 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._ # [![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] > Regular expression for matching HTML comments ## Install ```sh $ npm install --save html-comment-regex ``` ## Usage ```js var htmlCommentRegex = require('html-comment-regex'); htmlCommentRegex.test('<!DOCTYPE html><!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--><html lang="en"><head><meta charset="UTF-8"><title>Document</title></head><body></body></html>'); //=> true htmlCommentRegex.test('<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title></head><body></body></html>'); //=> false ``` ## License MIT © [Steve Mao](https://github.com/stevemao) [npm-image]: https://badge.fury.io/js/html-comment-regex.svg [npm-url]: https://npmjs.org/package/html-comment-regex [travis-image]: https://travis-ci.org/stevemao/html-comment-regex.svg?branch=master [travis-url]: https://travis-ci.org/stevemao/html-comment-regex 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 }); ``` # jest-worker Module for executing heavy tasks under forked processes in parallel, by providing a `Promise` based interface, minimum overhead, and bound workers. The module works by providing an absolute path of the module to be loaded in all forked processes. Files relative to a node module are also accepted. All methods are exposed on the parent process as promises, so they can be `await`'ed. Child (worker) methods can either be synchronous or asynchronous. The module also implements support for bound workers. Binding a worker means that, based on certain parameters, the same task will always be executed by the same worker. The way bound workers work is by using the returned string of the `computeWorkerKey` method. If the string was used before for a task, the call will be queued to the related worker that processed the task earlier; if not, it will be executed by the first available worker, then sticked to the worker that executed it; so the next time it will be processed by the same worker. If you have no preference on the worker executing the task, but you have defined a `computeWorkerKey` method because you want _some_ of the tasks to be sticked, you can return `null` from it. The list of exposed methods can be explicitly provided via the `exposedMethods` option. If it is not provided, it will be obtained by requiring the child module into the main process, and analyzed via reflection. Check the "minimal example" section for a valid one. ## Install ```sh $ yarn add jest-worker ``` ## Example This example covers the minimal usage: ### File `parent.js` ```javascript import JestWorker from 'jest-worker'; async function main() { const worker = new JestWorker(require.resolve('./Worker')); const result = await worker.hello('Alice'); // "Hello, Alice" } main(); ``` ### File `worker.js` ```javascript export function hello(param) { return 'Hello, ' + param; } ``` ## Experimental worker Node 10 shipped with [worker-threads](https://nodejs.org/api/worker_threads.html), a "threading API" that uses SharedArrayBuffers to communicate between the main process and its child threads. This experimental Node feature can significantly improve the communication time between parent and child processes in `jest-worker`. Since `worker_threads` are considered experimental in Node, you have to opt-in to this behavior by passing `enableWorkerThreads: true` when instantiating the worker. While the feature was unflagged in Node 11.7.0, you'll need to run the Node process with the `--experimental-worker` flag for Node 10. ## API The only exposed method is a constructor (`JestWorker`) that is initialized by passing the worker path, plus an options object. ### `workerPath: string` (required) Node module name or absolute path of the file to be loaded in the child processes. Use `require.resolve` to transform a relative path into an absolute one. ### `options: Object` (optional) #### `exposedMethods: $ReadOnlyArray<string>` (optional) List of method names that can be called on the child processes from the parent process. You cannot expose any method named like a public `Worker` method, or starting with `_`. If you use method auto-discovery, then these methods will not be exposed, even if they exist. #### `numWorkers: number` (optional) Amount of workers to spawn. Defaults to the number of CPUs minus 1. #### `maxRetries: number` (optional) Maximum amount of times that a dead child can be re-spawned, per call. Defaults to `3`, pass `Infinity` to allow endless retries. #### `forkOptions: Object` (optional) Allow customizing all options passed to `childProcess.fork`. By default, some values are set (`cwd`, `env` and `execArgv`), but you can override them and customize the rest. For a list of valid values, check [the Node documentation](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options). #### `computeWorkerKey: (method: string, ...args: Array<any>) => ?string` (optional) Every time a method exposed via the API is called, `computeWorkerKey` is also called in order to bound the call to a worker. This is useful for workers that are able to cache the result or part of it. You bound calls to a worker by making `computeWorkerKey` return the same identifier for all different calls. If you do not want to bind the call to any worker, return `null`. The callback you provide is called with the method name, plus all the rest of the arguments of the call. Thus, you have full control to decide what to return. Check a practical example on bound workers under the "bound worker usage" section. By default, no process is bound to any worker. #### `setupArgs: Array<mixed>` (optional) The arguments that will be passed to the `setup` method during initialization. #### `WorkerPool: (workerPath: string, options?: WorkerPoolOptions) => WorkerPoolInterface` (optional) Provide a custom worker pool to be used for spawning child processes. By default, Jest will use a node thread pool if available and fall back to child process threads. The arguments that will be passed to the `setup` method during initialization. #### `enableWorkerThreads: boolean` (optional) `jest-worker` will automatically detect if `worker_threads` are available, but will not use them unless passed `enableWorkerThreads: true`. ## JestWorker ### Methods The returned `JestWorker` instance has all the exposed methods, plus some additional ones to interact with the workers itself: #### `getStdout(): Readable` Returns a `ReadableStream` where the standard output of all workers is piped. Note that the `silent` option of the child workers must be set to `true` to make it work. This is the default set by `jest-worker`, but keep it in mind when overriding options through `forkOptions`. #### `getStderr(): Readable` Returns a `ReadableStream` where the standard error of all workers is piped. Note that the `silent` option of the child workers must be set to `true` to make it work. This is the default set by `jest-worker`, but keep it in mind when overriding options through `forkOptions`. #### `end()` Finishes the workers by killing all workers. No further calls can be done to the `Worker` instance. Returns a Promise that resolves with `{ forceExited: boolean }` once all workers are dead. If `forceExited` is `true`, at least one of the workers did not exit gracefully, which likely happened because it executed a leaky task that left handles open. This should be avoided, force exiting workers is a last resort to prevent creating lots of orphans. **Note:** `await`ing the `end()` Promise immediately after the workers are no longer needed before proceeding to do other useful things in your program may not be a good idea. If workers have to be force exited, `jest-worker` may go through multiple stages of force exiting (e.g. SIGTERM, later SIGKILL) and give the worker overall around 1 second time to exit on its own. During this time, your program will wait, even though it may not be necessary that all workers are dead before continuing execution. Consider deliberately leaving this Promise floating (unhandled resolution). After your program has done the rest of its work and is about to exit, the Node process will wait for the Promise to resolve after all workers are dead as the last event loop task. That way you parallelized computation time of your program and waiting time and you didn't delay the outputs of your program unnecessarily. ### Worker IDs Each worker has a unique id (index that starts with `1`), which is available inside the worker as `process.env.JEST_WORKER_ID`. ## Setting up and tearing down the child process The child process can define two special methods (both of them can be asynchronous): - `setup()`: If defined, it's executed before the first call to any method in the child. - `teardown()`: If defined, it's executed when the farm ends. # More examples ## Standard usage This example covers the standard usage: ### File `parent.js` ```javascript import JestWorker from 'jest-worker'; async function main() { const myWorker = new JestWorker(require.resolve('./Worker'), { exposedMethods: ['foo', 'bar', 'getWorkerId'], numWorkers: 4, }); console.log(await myWorker.foo('Alice')); // "Hello from foo: Alice" console.log(await myWorker.bar('Bob')); // "Hello from bar: Bob" console.log(await myWorker.getWorkerId()); // "3" -> this message has sent from the 3rd worker const {forceExited} = await myWorker.end(); if (forceExited) { console.error('Workers failed to exit gracefully'); } } main(); ``` ### File `worker.js` ```javascript export function foo(param) { return 'Hello from foo: ' + param; } export function bar(param) { return 'Hello from bar: ' + param; } export function getWorkerId() { return process.env.JEST_WORKER_ID; } ``` ## Bound worker usage: This example covers the usage with a `computeWorkerKey` method: ### File `parent.js` ```javascript import JestWorker from 'jest-worker'; async function main() { const myWorker = new JestWorker(require.resolve('./Worker'), { computeWorkerKey: (method, filename) => filename, }); // Transform the given file, within the first available worker. console.log(await myWorker.transform('/tmp/foo.js')); // Wait a bit. await sleep(10000); // Transform the same file again. Will immediately return because the // transformed file is cached in the worker, and `computeWorkerKey` ensures // the same worker that processed the file the first time will process it now. console.log(await myWorker.transform('/tmp/foo.js')); const {forceExited} = await myWorker.end(); if (forceExited) { console.error('Workers failed to exit gracefully'); } } main(); ``` ### File `worker.js` ```javascript import babel from '@babel/core'; const cache = Object.create(null); export function transform(filename) { if (cache[filename]) { return cache[filename]; } // jest-worker can handle both immediate results and thenables. If a // thenable is returned, it will be await'ed until it resolves. return babel.transformFileAsync(filename).then(result => { cache[filename] = result; return result; }); } ``` ## Escodegen [![npm version](https://badge.fury.io/js/escodegen.svg)](http://badge.fury.io/js/escodegen) [![Build Status](https://secure.travis-ci.org/estools/escodegen.svg)](http://travis-ci.org/estools/escodegen) [![Dependency Status](https://david-dm.org/estools/escodegen.svg)](https://david-dm.org/estools/escodegen) [![devDependency Status](https://david-dm.org/estools/escodegen/dev-status.svg)](https://david-dm.org/estools/escodegen#info=devDependencies) Escodegen ([escodegen](http://github.com/estools/escodegen)) is an [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) (also popularly known as [JavaScript](http://en.wikipedia.org/wiki/JavaScript)) code generator from [Mozilla's Parser API](https://developer.mozilla.org/en/SpiderMonkey/Parser_API) AST. See the [online generator](https://estools.github.io/escodegen/demo/index.html) for a demo. ### Install Escodegen can be used in a web browser: <script src="escodegen.browser.js"></script> escodegen.browser.js can be found in tagged revisions on GitHub. Or in a Node.js application via npm: npm install escodegen ### Usage A simple example: the program escodegen.generate({ type: 'BinaryExpression', operator: '+', left: { type: 'Literal', value: 40 }, right: { type: 'Literal', value: 2 } }); produces the string `'40 + 2'`. See the [API page](https://github.com/estools/escodegen/wiki/API) for options. To run the tests, execute `npm test` in the root directory. ### Building browser bundle / minified browser bundle At first, execute `npm install` to install the all dev dependencies. After that, npm run-script build will generate `escodegen.browser.js`, which can be used in browser environments. And, npm run-script build-min will generate the minified file `escodegen.browser.min.js`. ### License #### Escodegen Copyright (C) 2012 [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. # 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 # 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;tj@vision-media.ca&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. 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. # lodash.uniq v4.5.0 The [lodash](https://lodash.com/) method `_.uniq` exported as a [Node.js](https://nodejs.org/) module. ## Installation Using npm: ```bash $ {sudo -H} npm i -g npm $ npm i --save lodash.uniq ``` In Node.js: ```js var uniq = require('lodash.uniq'); ``` See the [documentation](https://lodash.com/docs#uniq) or [package source](https://github.com/lodash/lodash/blob/4.5.0-npm-packages/lodash.uniq) for more details. # 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 # 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 <surrender@evilmartians.com>. [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> ## Sponsorship PostCSS needs your support. We are accepting donations [at Open Collective](https://opencollective.com/postcss/). <a href="https://tailwindcss.com/"> <img src="https://refactoringui.nyc3.cdn.digitaloceanspaces.com/tailwind-logo.svg" alt="Sponsored by Tailwind CSS" width="273" height="64"> </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 ### 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 ### Parcel [Parcel] has built-in PostCSS support. It already uses Autoprefixer and cssnano. If you want to change plugins, create `postcss.config.js` in project’s root: ```js module.exports = { plugins: [ require('autoprefixer'), require('postcss-nested') ] } ``` Parcel will even automatically install these plugins for you. > Please, be aware of [the several issues in Version 1](https://github.com/parcel-bundler/parcel/labels/CSS%20Preprocessing). Notice, [Version 2](https://github.com/parcel-bundler/parcel/projects/5) may resolve the issues via [issue #2157](https://github.com/parcel-bundler/parcel/issues/2157). [Parcel]: https://parceljs.org ### 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 ### 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') ] } ``` ## Contributing [Our contributing guidelines](./CONTRIBUTING.md) will help you with making pull request to this project. ## Editors & IDE Integration ### VS Code * [`csstools.postcss`] adds support for PostCSS, `postcss-preset-env` and CSS Modules. [`csstools.postcss`]: https://marketplace.visualstudio.com/items?itemName=csstools.postcss ### 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/ ## 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 ## For Enterprise Available as part of the Tidelift Subscription. The maintainers of `postcss` 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-postcss?utm_source=npm-postcss&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) # 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/source-map@0.7.3/dist/source-map.js"></script> <script> sourceMap.SourceMapConsumer.initialize({ "lib/mappings.wasm": "https://unpkg.com/source-map@0.7.3/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] } ``` # Command-Option-Argument Yet another parser for command line options. [![NPM Status][npm-img]][npm] [![Travis Status][test-img]][travis] [![AppVeyor Status][appveyor-img]][appveyor] [![Coverage Status][coverage-img]][coveralls] [![Dependency Status][dependency-img]][david] [npm]: https://www.npmjs.org/package/coa [npm-img]: https://img.shields.io/npm/v/coa.svg [travis]: https://travis-ci.org/veged/coa [test-img]: https://img.shields.io/travis/veged/coa.svg [appveyor]: https://ci.appveyor.com/project/zxqfox/coa [appveyor-img]: https://ci.appveyor.com/api/projects/status/github/veged/coa?svg=true [coveralls]: https://coveralls.io/r/veged/coa [coverage-img]: https://img.shields.io/coveralls/veged/coa.svg [david]: https://david-dm.org/veged/coa [dependency-img]: http://img.shields.io/david/veged/coa.svg ## What is it? COA is a parser for command line options that aim to get maximum profit from formalization your program API. Once you write definition in terms of commands, options and arguments you automaticaly get: * Command line help text * Program API for use COA-based programs as modules * Shell completion ### Other features * Rich types for options and arguments, such as arrays, boolean flags and required * Commands can be async throught using promising (powered by [Q](https://github.com/kriskowal/q)) * Easy submoduling some existing commands to new top-level one * Combined validation and complex parsing of values ### TODO * Localization * Shell-mode * Configs * Aliases * Defaults ## Examples ````javascript require('coa').Cmd() // main (top level) command declaration .name(process.argv[1]) // set top level command name from program name .title('My awesome command line util') // title for use in text messages .helpful() // make command "helpful", i.e. options -h --help with usage message .opt() // add some option .name('version') // name for use in API .title('Version') // title for use in text messages .short('v') // short key: -v .long('version') // long key: --version .flag() // for options without value .act(function(opts) { // add action for option // return message as result of action return JSON.parse(require('fs').readFileSync(__dirname + '/package.json')) .version; }) .end() // end option chain and return to main command .cmd().name('subcommand').apply(require('./subcommand').COA).end() // load subcommand from module .cmd() // inplace subcommand declaration .name('othercommand').title('Awesome other subcommand').helpful() .opt() .name('input').title('input file, required') .short('i').long('input') .val(function(v) { // validator function, also for translate simple values return require('fs').createReadStream(v) }) .req() // make option required .end() // end option chain and return to command .end() // end subcommand chain and return to parent command .run(process.argv.slice(2)); // parse and run on process.argv ```` ````javascript // subcommand.js exports.COA = function() { this .title('Awesome subcommand').helpful() .opt() .name('output').title('output file') .short('o').long('output') .output() // use default preset for "output" option declaration .end() }; ```` ## API reference ### Cmd Command is a top level entity. Commands may have options and arguments. #### Cmd.api Returns object containing all its subcommands as methods to use from other programs.<br> **@returns** *{Object}* #### Cmd.name Set a canonical command identifier to be used anywhere in the API.<br> **@param** *String* `_name` command name<br> **@returns** *COA.Cmd* `this` instance (for chainability) #### Cmd.title Set a long description for command to be used anywhere in text messages.<br> **@param** *String* `_title` command title<br> **@returns** *COA.Cmd* `this` instance (for chainability) #### Cmd.cmd Create new or add existing subcommand for current command.<br> **@param** *COA.Cmd* `[cmd]` existing command instance<br> **@returns** *COA.Cmd* new or added subcommand instance #### Cmd.opt Create option for current command.<br> **@returns** *COA.Opt* `new` option instance #### Cmd.arg Create argument for current command.<br> **@returns** *COA.Opt* `new` argument instance #### Cmd.act Add (or set) action for current command.<br> **@param** *Function* `act` action function, invoked in the context of command instance and has the parameters:<br> - *Object* `opts` parsed options<br> - *Array* `args` parsed arguments<br> - *Object* `res` actions result accumulator<br> It can return rejected promise by Cmd.reject (in case of error) or any other value treated as result.<br> **@param** *{Boolean}* [force=false] flag for set action instead add to existings<br> **@returns** *COA.Cmd* `this` instance (for chainability) #### Cmd.apply Apply function with arguments in context of command instance.<br> **@param** *Function* `fn`<br> **@param** *Array* `args`<br> **@returns** *COA.Cmd* `this` instance (for chainability) #### Cmd.comp Set custom additional completion for current command.<br> **@param** *Function* `fn` completion generation function, invoked in the context of command instance. Accepts parameters:<br> - *Object* `opts` completion options<br> It can return promise or any other value treated as result.<br> **@returns** *COA.Cmd* `this` instance (for chainability) #### Cmd.helpful Make command "helpful", i.e. add -h --help flags for print usage.<br> **@returns** *COA.Cmd* `this` instance (for chainability) #### Cmd.completable Adds shell completion to command, adds "completion" subcommand, that makes all the magic.<br> Must be called only on root command.<br> **@returns** *COA.Cmd* `this` instance (for chainability) #### Cmd.usage Build full usage text for current command instance.<br> **@returns** *String* `usage` text #### Cmd.run Parse arguments from simple format like NodeJS process.argv and run ahead current program, i.e. call process.exit when all actions done.<br> **@param** *Array* `argv`<br> **@returns** *COA.Cmd* `this` instance (for chainability) #### Cmd.invoke Invoke specified (or current) command using provided options and arguments.<br> **@param** *String|Array* `cmds` subcommand to invoke (optional)<br> **@param** *Object* `opts` command options (optional)<br> **@param** *Object* `args` command arguments (optional)<br> **@returns** *Q.Promise* #### Cmd.reject Return reject of actions results promise.<br> Use in .act() for return with error.<br> **@param** *Object* `reason` reject reason<br> You can customize toString() method and exitCode property of reason object.<br> **@returns** *Q.promise* rejected promise #### Cmd.end Finish chain for current subcommand and return parent command instance.<br> **@returns** *COA.Cmd* `parent` command ### Opt Option is a named entity. Options may have short and long keys for use from command line.<br> **@namespace**<br> **@class** Presents option #### Opt.name Set a canonical option identifier to be used anywhere in the API.<br> **@param** *String* `_name` option name<br> **@returns** *COA.Opt* `this` instance (for chainability) #### Opt.title Set a long description for option to be used anywhere in text messages.<br> **@param** *String* `_title` option title<br> **@returns** *COA.Opt* `this` instance (for chainability) #### Opt.short Set a short key for option to be used with one hyphen from command line.<br> **@param** *String* `_short`<br> **@returns** *COA.Opt* `this` instance (for chainability) #### Opt.long Set a short key for option to be used with double hyphens from command line.<br> **@param** *String* `_long`<br> **@returns** *COA.Opt* `this` instance (for chainability) #### Opt.flag Make an option boolean, i.e. option without value.<br> **@returns** *COA.Opt* `this` instance (for chainability) #### Opt.arr Makes an option accepts multiple values.<br> Otherwise, the value will be used by the latter passed.<br> **@returns** *COA.Opt* `this` instance (for chainability) #### Opt.req Makes an option req.<br> **@returns** *COA.Opt* `this` instance (for chainability) #### Opt.only Makes an option to act as a command, i.e. program will exit just after option action.<br> **@returns** *COA.Opt* `this` instance (for chainability) #### Opt.val Set a validation (or value) function for argument.<br> Value from command line passes through before becoming available from API.<br> Using for validation and convertion simple types to any values.<br> **@param** *Function* `_val` validating function, invoked in the context of option instance and has one parameter with value from command line<br> **@returns** *COA.Opt* `this` instance (for chainability) #### Opt.def Set a default value for option. Default value passed through validation function as ordinary value.<br> **@param** *Object* `_def`<br> **@returns** *COA.Opt* `this` instance (for chainability) #### Opt.input Make option value inputting stream. It's add useful validation and shortcut for STDIN. **@returns** *{COA.Opt}* `this` instance (for chainability) #### Opt.output Make option value outputing stream.<br> It's add useful validation and shortcut for STDOUT.<br> **@returns** *COA.Opt* `this` instance (for chainability) #### Opt.act Add action for current option command. This action is performed if the current option is present in parsed options (with any value).<br> **@param** *Function* `act` action function, invoked in the context of command instance and has the parameters:<br> - *Object* `opts` parsed options<br> - *Array* `args` parsed arguments<br> - *Object* `res` actions result accumulator<br> It can return rejected promise by Cmd.reject (in case of error) or any other value treated as result.<br> **@returns** *COA.Opt* `this` instance (for chainability) #### Opt.comp Set custom additional completion for current option.<br> **@param** *Function* `fn` completion generation function, invoked in the context of command instance. Accepts parameters:<br> - *Object* `opts` completion options<br> It can return promise or any other value treated as result.<br> **@returns** *COA.Opt* `this` instance (for chainability) #### Opt.end Finish chain for current option and return parent command instance.<br> **@returns** *COA.Cmd* `parent` command ### Arg Argument is a unnamed entity.<br> From command line arguments passed as list of unnamed values. #### Arg.name Set a canonical argument identifier to be used anywhere in text messages.<br> **@param** *String* `_name` argument name<br> **@returns** *COA.Arg* `this` instance (for chainability) #### Arg.title Set a long description for argument to be used anywhere in text messages.<br> **@param** *String* `_title` argument title<br> **@returns** *COA.Arg* `this` instance (for chainability) #### Arg.arr Makes an argument accepts multiple values.<br> Otherwise, the value will be used by the latter passed.<br> **@returns** *COA.Arg* `this` instance (for chainability) #### Arg.req Makes an argument req.<br> **@returns** *COA.Arg* `this` instance (for chainability) #### Arg.val Set a validation (or value) function for argument.<br> Value from command line passes through before becoming available from API.<br> Using for validation and convertion simple types to any values.<br> **@param** *Function* `_val` validating function, invoked in the context of argument instance and has one parameter with value from command line<br> **@returns** *COA.Arg* `this` instance (for chainability) #### Arg.def Set a default value for argument. Default value passed through validation function as ordinary value.<br> **@param** *Object* `_def`<br> **@returns** *COA.Arg* `this` instance (for chainability) #### Arg.output Make argument value outputing stream.<br> It's add useful validation and shortcut for STDOUT.<br> **@returns** *COA.Arg* `this` instance (for chainability) #### Arg.comp Set custom additional completion for current argument.<br> **@param** *Function* `fn` completion generation function, invoked in the context of command instance. Accepts parameters:<br> - *Object* `opts` completion options<br> It can return promise or any other value treated as result.<br> **@returns** *COA.Arg* `this` instance (for chainability) #### Arg.end Finish chain for current option and return parent command instance.<br> **@returns** *COA.Cmd* `parent` command # hsl-regex [![Build Status](https://secure.travis-ci.org/regexps/hsl-regex.png?branch=master)](https://travis-ci.org/regexps/hsl-regex) Regex for matching HSL colors. ## Installation ```bash npm install --save hsl-regex ``` ## Usage ```javascript var hslRegex = require('hsl-regex'); hslRegex({ exact: true }).test('hsl(123, 45%, 67%)'); // => true hslRegex({ exact: true }).test('foo bar'); // => false hslRegex({ exact: true }).exec('hsl(1, 1.111%, 1.1111%)'); // => [ // 'hsl(1, 1.111%, 1.1111%)', // '1', // '1.111%', // '1.1111%', // index: 0, // input: 'hsl(1, 1.111%, 1.1111%)' // ] 'hsl(123, 45%, 67%) cats and dogs'.match(hslRegex()); // = ['hsl(123, 45%, 67%)'] ``` ## License MIT ## 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. Create new Pull Request Crafted with <3 by John Otander ([@4lpine](https://twitter.com/4lpine)). *** > This package was initially generated with [yeoman](http://yeoman.io) and the [p generator](https://github.com/johnotander/generator-p.git). # 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). 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. # jest-diff Display differences clearly so people can review changes confidently. The default export serializes JavaScript **values**, compares them line-by-line, and returns a string which includes comparison lines. Two named exports compare **strings** character-by-character: - `diffStringsUnified` returns a string. - `diffStringsRaw` returns an array of `Diff` objects. Three named exports compare **arrays of strings** line-by-line: - `diffLinesUnified` and `diffLinesUnified2` return a string. - `diffLinesRaw` returns an array of `Diff` objects. ## Installation To add this package as a dependency of a project, run either of the following commands: - `npm install jest-diff` - `yarn add jest-diff` ## Usage of default export Given JavaScript **values**, `diffDefault(a, b, options?)` does the following: 1. **serialize** the values as strings using the `pretty-format` package 2. **compare** the strings line-by-line using the `diff-sequences` package 3. **format** the changed or common lines using the `chalk` package To use this function, write either of the following: - `const diffDefault = require('jest-diff').default;` in CommonJS modules - `import diffDefault from 'jest-diff';` in ECMAScript modules ### Example of default export ```js const a = ['delete', 'common', 'changed from']; const b = ['common', 'changed to', 'insert']; const difference = diffDefault(a, b); ``` The returned **string** consists of: - annotation lines: describe the two change indicators with labels, and a blank line - comparison lines: similar to “unified” view on GitHub, but `Expected` lines are green, `Received` lines are red, and common lines are dim (by default, see Options) ```diff - Expected + Received Array [ - "delete", "common", - "changed from", + "changed to", + "insert", ] ``` ### Edge cases of default export Here are edge cases for the return value: - `' Comparing two different types of values. …'` if the arguments have **different types** according to the `jest-get-type` package (instances of different classes have the same `'object'` type) - `'Compared values have no visual difference.'` if the arguments have either **referential identity** according to `Object.is` method or **same serialization** according to the `pretty-format` package - `null` if either argument is a so-called **asymmetric matcher** in Jasmine or Jest ## Usage of diffStringsUnified Given **strings**, `diffStringsUnified(a, b, options?)` does the following: 1. **compare** the strings character-by-character using the `diff-sequences` package 2. **clean up** small (often coincidental) common substrings, also known as chaff 3. **format** the changed or common lines using the `chalk` package Although the function is mainly for **multiline** strings, it compares any strings. Write either of the following: - `const {diffStringsUnified} = require('jest-diff');` in CommonJS modules - `import {diffStringsUnified} from 'jest-diff';` in ECMAScript modules ### Example of diffStringsUnified ```js const a = 'common\nchanged from'; const b = 'common\nchanged to'; const difference = diffStringsUnified(a, b); ``` The returned **string** consists of: - annotation lines: describe the two change indicators with labels, and a blank line - comparison lines: similar to “unified” view on GitHub, and **changed substrings** have **inverse** foreground and background colors (that is, `from` has white-on-green and `to` has white-on-red, which the following example does not show) ```diff - Expected + Received common - changed from + changed to ``` ### Performance of diffStringsUnified To get the benefit of **changed substrings** within the comparison lines, a character-by-character comparison has a higher computational cost (in time and space) than a line-by-line comparison. If the input strings can have **arbitrary length**, we recommend that the calling code set a limit, beyond which splits the strings, and then calls `diffLinesUnified` instead. For example, Jest falls back to line-by-line comparison if either string has length greater than 20K characters. ## Usage of diffLinesUnified Given **arrays of strings**, `diffLinesUnified(aLines, bLines, options?)` does the following: 1. **compare** the arrays line-by-line using the `diff-sequences` package 2. **format** the changed or common lines using the `chalk` package You might call this function when strings have been split into lines and you do not need to see changed substrings within lines. ### Example of diffLinesUnified ```js const aLines = ['delete', 'common', 'changed from']; const bLines = ['common', 'changed to', 'insert']; const difference = diffLinesUnified(aLines, bLines); ``` ```diff - Expected + Received - delete common - changed from + changed to + insert ``` ### Edge cases of diffLinesUnified or diffStringsUnified Here are edge cases for arguments and return values: - both `a` and `b` are empty strings: no comparison lines - only `a` is empty string: all comparison lines have `bColor` and `bIndicator` (see Options) - only `b` is empty string: all comparison lines have `aColor` and `aIndicator` (see Options) - `a` and `b` are equal non-empty strings: all comparison lines have `commonColor` and `commonIndicator` (see Options) ## Usage of diffLinesUnified2 Given two **pairs** of arrays of strings, `diffLinesUnified2(aLinesDisplay, bLinesDisplay, aLinesCompare, bLinesCompare, options?)` does the following: 1. **compare** the pair of `Compare` arrays line-by-line using the `diff-sequences` package 2. **format** the corresponding lines in the pair of `Display` arrays using the `chalk` package Jest calls this function to consider lines as common instead of changed if the only difference is indentation. You might call this function for case insensitive or Unicode equivalence comparison of lines. ### Example of diffLinesUnified2 ```js import format from 'pretty-format'; const a = { text: 'Ignore indentation in serialized object', time: '2019-09-19T12:34:56.000Z', type: 'CREATE_ITEM', }; const b = { payload: { text: 'Ignore indentation in serialized object', time: '2019-09-19T12:34:56.000Z', }, type: 'CREATE_ITEM', }; const difference = diffLinesUnified2( // serialize with indentation to display lines format(a).split('\n'), format(b).split('\n'), // serialize without indentation to compare lines format(a, {indent: 0}).split('\n'), format(b, {indent: 0}).split('\n'), ); ``` The `text` and `time` properties are common, because their only difference is indentation: ```diff - Expected + Received Object { + payload: Object { text: 'Ignore indentation in serialized object', time: '2019-09-19T12:34:56.000Z', + }, type: 'CREATE_ITEM', } ``` The preceding example illustrates why (at least for indentation) it seems more intuitive that the function returns the common line from the `bLinesDisplay` array instead of from the `aLinesDisplay` array. ## Usage of diffStringsRaw Given **strings** and a boolean option, `diffStringsRaw(a, b, cleanup)` does the following: 1. **compare** the strings character-by-character using the `diff-sequences` package 2. optionally **clean up** small (often coincidental) common substrings, also known as chaff Because `diffStringsRaw` returns the difference as **data** instead of a string, you can format it as your application requires (for example, enclosed in HTML markup for browser instead of escape sequences for console). The returned **array** describes substrings as instances of the `Diff` class, which calling code can access like array tuples: The value at index `0` is one of the following: | value | named export | description | | ----: | :------------ | :-------------------- | | `0` | `DIFF_EQUAL` | in `a` and in `b` | | `-1` | `DIFF_DELETE` | in `a` but not in `b` | | `1` | `DIFF_INSERT` | in `b` but not in `a` | The value at index `1` is a substring of `a` or `b` or both. ### Example of diffStringsRaw with cleanup ```js const diffs = diffStringsRaw('changed from', 'changed to', true); ``` | `i` | `diffs[i][0]` | `diffs[i][1]` | | --: | ------------: | :------------ | | `0` | `0` | `'changed '` | | `1` | `-1` | `'from'` | | `2` | `1` | `'to'` | ### Example of diffStringsRaw without cleanup ```js const diffs = diffStringsRaw('changed from', 'changed to', false); ``` | `i` | `diffs[i][0]` | `diffs[i][1]` | | --: | ------------: | :------------ | | `0` | `0` | `'changed '` | | `1` | `-1` | `'fr'` | | `2` | `1` | `'t'` | | `3` | `0` | `'o'` | | `4` | `-1` | `'m'` | ### Advanced import for diffStringsRaw Here are all the named imports that you might need for the `diffStringsRaw` function: - `const {DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, Diff, diffStringsRaw} = require('jest-diff');` in CommonJS modules - `import {DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, Diff, diffStringsRaw} from 'jest-diff';` in ECMAScript modules To write a **formatting** function, you might need the named constants (and `Diff` in TypeScript annotations). If you write an application-specific **cleanup** algorithm, then you might need to call the `Diff` constructor: ```js const diffCommon = new Diff(DIFF_EQUAL, 'changed '); const diffDelete = new Diff(DIFF_DELETE, 'from'); const diffInsert = new Diff(DIFF_INSERT, 'to'); ``` ## Usage of diffLinesRaw Given **arrays of strings**, `diffLinesRaw(aLines, bLines)` does the following: - **compare** the arrays line-by-line using the `diff-sequences` package Because `diffLinesRaw` returns the difference as **data** instead of a string, you can format it as your application requires. ### Example of diffLinesRaw ```js const aLines = ['delete', 'common', 'changed from']; const bLines = ['common', 'changed to', 'insert']; const diffs = diffLinesRaw(aLines, bLines); ``` | `i` | `diffs[i][0]` | `diffs[i][1]` | | --: | ------------: | :--------------- | | `0` | `-1` | `'delete'` | | `1` | `0` | `'common'` | | `2` | `-1` | `'changed from'` | | `3` | `1` | `'changed to'` | | `4` | `1` | `'insert'` | ### Edge case of diffLinesRaw If you call `string.split('\n')` for an empty string: - the result is `['']` an array which contains an empty string - instead of `[]` an empty array Depending of your application, you might call `diffLinesRaw` with either array. ### Example of split method ```js import {diffLinesRaw} from 'jest-diff'; const a = 'non-empty string'; const b = ''; const diffs = diffLinesRaw(a.split('\n'), b.split('\n')); ``` | `i` | `diffs[i][0]` | `diffs[i][1]` | | --: | ------------: | :------------------- | | `0` | `-1` | `'non-empty string'` | | `1` | `1` | `''` | Which you might format as follows: ```diff - Expected - 1 + Received + 1 - non-empty string + ``` ### Example of splitLines0 function For edge case behavior like the `diffLinesUnified` function, you might define a `splitLines0` function, which given an empty string, returns `[]` an empty array: ```js export const splitLines0 = string => string.length === 0 ? [] : string.split('\n'); ``` ```js import {diffLinesRaw} from 'jest-diff'; const a = ''; const b = 'line 1\nline 2\nline 3'; const diffs = diffLinesRaw(a.split('\n'), b.split('\n')); ``` | `i` | `diffs[i][0]` | `diffs[i][1]` | | --: | ------------: | :------------ | | `0` | `1` | `'line 1'` | | `1` | `1` | `'line 2'` | | `2` | `1` | `'line 3'` | Which you might format as follows: ```diff - Expected - 0 + Received + 3 + line 1 + line 2 + line 3 ``` In contrast to the `diffLinesRaw` function, the `diffLinesUnified` and `diffLinesUnified2` functions **automatically** convert array arguments computed by string `split` method, so callers do **not** need a `splitLine0` function. ## Options The default options are for the report when an assertion fails from the `expect` package used by Jest. For other applications, you can provide an options object as a third argument: - `diffDefault(a, b, options)` - `diffStringsUnified(a, b, options)` - `diffLinesUnified(aLines, bLines, options)` - `diffLinesUnified2(aLinesDisplay, bLinesDisplay, aLinesCompare, bLinesCompare, options)` ### Properties of options object | name | default | | :-------------------------------- | :----------------- | | `aAnnotation` | `'Expected'` | | `aColor` | `chalk.green` | | `aIndicator` | `'-'` | | `bAnnotation` | `'Received'` | | `bColor` | `chalk.red` | | `bIndicator` | `'+'` | | `changeColor` | `chalk.inverse` | | `changeLineTrailingSpaceColor` | `string => string` | | `commonColor` | `chalk.dim` | | `commonIndicator` | `' '` | | `commonLineTrailingSpaceColor` | `string => string` | | `contextLines` | `5` | | `emptyFirstOrLastLinePlaceholder` | `''` | | `expand` | `true` | | `includeChangeCounts` | `false` | | `omitAnnotationLines` | `false` | | `patchColor` | `chalk.yellow` | For more information about the options, see the following examples. ### Example of options for labels If the application is code modification, you might replace the labels: ```js const options = { aAnnotation: 'Original', bAnnotation: 'Modified', }; ``` ```diff - Original + Modified common - changed from + changed to ``` The `jest-diff` package does not assume that the 2 labels have equal length. ### Example of options for colors of changed lines For consistency with most diff tools, you might exchange the colors: ```ts import chalk = require('chalk'); const options = { aColor: chalk.red, bColor: chalk.green, }; ``` ### Example of option for color of changed substrings Although the default inverse of foreground and background colors is hard to beat for changed substrings **within lines**, especially because it highlights spaces, if you want bold font weight on yellow background color: ```ts import chalk = require('chalk'); const options = { changeColor: chalk.bold.bgYellowBright, }; ``` ### Example of option to format trailing spaces Because the default export does not display substring differences within lines, formatting can help you see when lines differ by the presence or absence of trailing spaces found by `/\s+$/` regular expression. - If change lines have a background color, then you can see trailing spaces. - If common lines have default dim color, then you cannot see trailing spaces. You might want yellowish background color to see them. ```js const options = { aColor: chalk.rgb(128, 0, 128).bgRgb(255, 215, 255), // magenta bColor: chalk.rgb(0, 95, 0).bgRgb(215, 255, 215), // green commonLineTrailingSpaceColor: chalk.bgYellow, }; ``` The value of a Color option is a function, which given a string, returns a string. If you want to replace trailing spaces with middle dot characters: ```js const replaceSpacesWithMiddleDot = string => '·'.repeat(string.length); const options = { changeLineTrailingSpaceColor: replaceSpacesWithMiddleDot, commonLineTrailingSpaceColor: replaceSpacesWithMiddleDot, }; ``` If you need the TypeScript type of a Color option: ```ts import {DiffOptionsColor} from 'jest-diff'; ``` ### Example of options for no colors To store the difference in a file without escape codes for colors, provide an identity function: ```js const noColor = string => string; const options = { aColor: noColor, bColor: noColor, changeColor: noColor, commonColor: noColor, patchColor: noColor, }; ``` ### Example of options for indicators For consistency with the `diff` command, you might replace the indicators: ```js const options = { aIndicator: '<', bIndicator: '>', }; ``` The `jest-diff` package assumes (but does not enforce) that the 3 indicators have equal length. ### Example of options to limit common lines By default, the output includes all common lines. To emphasize the changes, you might limit the number of common “context” lines: ```js const options = { contextLines: 1, expand: false, }; ``` A patch mark like `@@ -12,7 +12,9 @@` accounts for omitted common lines. ### Example of option for color of patch marks If you want patch marks to have the same dim color as common lines: ```ts import chalk = require('chalk'); const options = { expand: false, patchColor: chalk.dim, }; ``` ### Example of option to include change counts To display the number of changed lines at the right of annotation lines: ```js const a = ['common', 'changed from']; const b = ['common', 'changed to', 'insert']; const options = { includeChangeCounts: true, }; const difference = diffDefault(a, b, options); ``` ```diff - Expected - 1 + Received + 2 Array [ "common", - "changed from", + "changed to", + "insert", ] ``` ### Example of option to omit annotation lines To display only the comparison lines: ```js const a = 'common\nchanged from'; const b = 'common\nchanged to'; const options = { omitAnnotationLines: true, }; const difference = diffStringsUnified(a, b, options); ``` ```diff common - changed from + changed to ``` ### Example of option for empty first or last lines If the **first** or **last** comparison line is **empty**, because the content is empty and the indicator is a space, you might not notice it. The replacement option is a string whose default value is `''` empty string. Because Jest trims the report when a matcher fails, it deletes an empty last line. Therefore, Jest uses as placeholder the downwards arrow with corner leftwards: ```js const options = { emptyFirstOrLastLinePlaceholder: '↵', // U+21B5 }; ``` If a content line is empty, then the corresponding comparison line is automatically trimmed to remove the margin space (represented as a middle dot below) for the default indicators: | Indicator | untrimmed | trimmed | | ----------------: | :-------- | :------ | | `aIndicator` | `'-·'` | `'-'` | | `bIndicator` | `'+·'` | `'+'` | | `commonIndicator` | `' ·'` | `''` | # 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 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> # Node-TimSort: Fast Sorting for Node.js [![Build Status](https://travis-ci.org/mziccard/node-timsort.svg?branch=master)](https://travis-ci.org/mziccard/node-timsort) [![npm version](https://badge.fury.io/js/timsort.svg)](https://www.npmjs.com/package/timsort) An adaptive and **stable** sort algorithm based on merging that requires fewer than nlog(n) comparisons when run on partially sorted arrays. The algorithm uses O(n) memory and still runs in O(nlogn) (worst case) on random arrays. This implementation is based on the original [TimSort](http://svn.python.org/projects/python/trunk/Objects/listsort.txt) developed by Tim Peters for Python's lists (code [here](http://svn.python.org/projects/python/trunk/Objects/listobject.c)). TimSort has been also adopted in Java starting from version 7. ## Acknowledgments - @novacrazy: ported the module to ES6/ES7 and made it available via bower - @kasperisager: implemented faster lexicographic comparison of small integers ## Usage Install the package with npm: ``` npm install --save timsort ``` And use it: ```javascript var TimSort = require('timsort'); var arr = [...]; TimSort.sort(arr); ``` You can also install it with bower: ``` bower install timsort ``` As `array.sort()` by default the `timsort` module sorts according to lexicographical order. You can also provide your own compare function (to sort any object) as: ```javascript function numberCompare(a,b) { return a-b; } var arr = [...]; var TimSort = require('timsort'); TimSort.sort(arr, numberCompare); ``` You can also sort only a specific subrange of the array: ```javascript TimSort.sort(arr, 5, 10); TimSort.sort(arr, numberCompare, 5, 10); ``` ## Performance A benchmark is provided in `benchmark/index.js`. It compares the `timsort` module against the default `array.sort` method in the numerical sorting of different types of integer array (as described [here](http://svn.python.org/projects/python/trunk/Objects/listsort.txt)): - *Random array* - *Descending array* - *Ascending array* - *Ascending array with 3 random exchanges* - *Ascending array with 10 random numbers in the end* - *Array of equal elements* - *Random Array with many duplicates* - *Random Array with some duplicates* For any of the array types the sorting is repeated several times and for different array sizes, average execution time is then printed. I run the benchmark on Node v6.3.1 (both pre-compiled and compiled from source, results are very similar), obtaining the following values: <table> <tr> <th></th><th></th> <th colspan="2">Execution Time (ns)</th> <th rowspan="2">Speedup</th> </tr> <tr> <th>Array Type</th> <th>Length</th> <th>TimSort.sort</th> <th>array.sort</th> </tr> <tbody> <tr> <td rowspan="4">Random</td><td>10</td><td>404</td><td>1583</td><td>3.91</td> </tr> <tr> <td>100</td><td>7147</td><td>4442</td><td>0.62</td> </tr> <tr> <td>1000</td><td>96395</td><td>59979</td><td>0.62</td> </tr> <tr> <td>10000</td><td>1341044</td><td>6098065</td><td>4.55</td> </tr> <tr> <td rowspan="4">Descending</td><td>10</td><td>180</td><td>1881</td><td>10.41</td> </tr> <tr> <td>100</td><td>682</td><td>19210</td><td>28.14</td> </tr> <tr> <td>1000</td><td>3809</td><td>185185</td><td>48.61</td> </tr> <tr> <td>10000</td><td>35878</td><td>5392428</td><td>150.30</td> </tr> <tr> <td rowspan="4">Ascending</td><td>10</td><td>173</td><td>816</td><td>4.69</td> </tr> <tr> <td>100</td><td>578</td><td>18147</td><td>31.34</td> </tr> <tr> <td>1000</td><td>2551</td><td>331993</td><td>130.12</td> </tr> <tr> <td>10000</td><td>22098</td><td>5382446</td><td>243.57</td> </tr> <tr> <td rowspan="4">Ascending + 3 Rand Exc</td><td>10</td><td>232</td><td>927</td><td>3.99</td> </tr> <tr> <td>100</td><td>1059</td><td>15792</td><td>14.90</td> </tr> <tr> <td>1000</td><td>3525</td><td>300708</td><td>85.29</td> </tr> <tr> <td>10000</td><td>27455</td><td>4781370</td><td>174.15</td> </tr> <tr> <td rowspan="4">Ascending + 10 Rand End</td><td>10</td><td>378</td><td>1425</td><td>3.77</td> </tr> <tr> <td>100</td><td>1707</td><td>23346</td><td>13.67</td> </tr> <tr> <td>1000</td><td>5818</td><td>334744</td><td>57.53</td> </tr> <tr> <td>10000</td><td>38034</td><td>4985473</td><td>131.08</td> </tr> <tr> <td rowspan="4">Equal Elements</td><td>10</td><td>164</td><td>766</td><td>4.68</td> </tr> <tr> <td>100</td><td>520</td><td>3188</td><td>6.12</td> </tr> <tr> <td>1000</td><td>2340</td><td>27971</td><td>11.95</td> </tr> <tr> <td>10000</td><td>17011</td><td>281672</td><td>16.56</td> </tr> <tr> <td rowspan="4">Many Repetitions</td><td>10</td><td>396</td><td>1482</td><td>3.74</td> </tr> <tr> <td>100</td><td>7282</td><td>25267</td><td>3.47</td> </tr> <tr> <td>1000</td><td>105528</td><td>420120</td><td>3.98</td> </tr> <tr> <td>10000</td><td>1396120</td><td>5787399</td><td>4.15</td> </tr> <tr> <td rowspan="4">Some Repetitions</td><td>10</td><td>390</td><td>1463</td><td>3.75</td> </tr> <tr> <td>100</td><td>6678</td><td>20082</td><td>3.01</td> </tr> <tr> <td>1000</td><td>104344</td><td>374103</td><td>3.59</td> </tr> <tr> <td>10000</td><td>1333816</td><td>5474000</td><td>4.10</td> </tr> </tbody> </table> `TimSort.sort` **is faster** than `array.sort` on almost of the tested array types. In general, the more ordered the array is the better `TimSort.sort` performs with respect to `array.sort` (up to 243 times faster on already sorted arrays). And also, in general, the bigger the array the more we benefit from using the `timsort` module. These data strongly depend on Node.js version and the machine on which the benchmark is run. I strongly encourage you to run the benchmark on your own setup with: ``` npm run benchmark ``` Please also notice that: - This benchmark is far from exhaustive. Several cases are not considered and the results must be taken as partial - *inlining* is surely playing an active role in `timsort` module's good performance - A more accurate comparison of the algorithms would require implementing `array.sort` in pure javascript and counting element comparisons ## Stability TimSort is *stable* which means that equal items maintain their relative order after sorting. Stability is a desirable property for a sorting algorithm. Consider the following array of items with an height and a weight. ```javascript [ { height: 100, weight: 80 }, { height: 90, weight: 90 }, { height: 70, weight: 95 }, { height: 100, weight: 100 }, { height: 80, weight: 110 }, { height: 110, weight: 115 }, { height: 100, weight: 120 }, { height: 70, weight: 125 }, { height: 70, weight: 130 }, { height: 100, weight: 135 }, { height: 75, weight: 140 }, { height: 70, weight: 140 } ] ``` Items are already sorted by `weight`. Sorting the array according to the item's `height` with the `timsort` module results in the following array: ```javascript [ { height: 70, weight: 95 }, { height: 70, weight: 125 }, { height: 70, weight: 130 }, { height: 70, weight: 140 }, { height: 75, weight: 140 }, { height: 80, weight: 110 }, { height: 90, weight: 90 }, { height: 100, weight: 80 }, { height: 100, weight: 100 }, { height: 100, weight: 120 }, { height: 100, weight: 135 }, { height: 110, weight: 115 } ] ``` Items with the same `height` are still sorted by `weight` which means they preserved their relative order. `array.sort`, instead, is not guarranteed to be *stable*. In Node v0.12.7 sorting the previous array by `height` with `array.sort` results in: ```javascript [ { height: 70, weight: 140 }, { height: 70, weight: 95 }, { height: 70, weight: 125 }, { height: 70, weight: 130 }, { height: 75, weight: 140 }, { height: 80, weight: 110 }, { height: 90, weight: 90 }, { height: 100, weight: 100 }, { height: 100, weight: 80 }, { height: 100, weight: 135 }, { height: 100, weight: 120 }, { height: 110, weight: 115 } ] ``` As you can see the sorting did not preserve `weight` ordering for items with the same `height`. 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. # jest-leak-detector Module for verifying whether an object has been garbage collected or not. Internally creates a weak reference to the object, and forces garbage collection to happen. If the reference is gone, it meant no one else was pointing to the object. ## Example ```javascript (async function () { let reference = {}; let isLeaking; const detector = new LeakDetector(reference); // Reference is held in memory. isLeaking = await detector.isLeaking(); console.log(isLeaking); // true // We destroy the only reference to the object. reference = null; // Reference is gone. isLeaking = await detector.isLeaking(); console.log(isLeaking); // false })(); ``` # cssnano-util-same-parent > Check that two PostCSS nodes share the same parent. ## Contributors See [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md). ## License MIT © [Ben Briggs](http://beneb.info) # RTrace A tiny utility that records allocations, retains, releases 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` and include an instance of this module as the import named `rtrace`. ```js var rtr = rtrace(e => { // handle error }); WebAssembly.instantiate(..., { rtrace: rtr, ... }); ... if (rtr.active) { let leakCount = rtr.check(); if (leakCount) { // handle error } } ``` Note that references retained in globals which are not cleared before execution concludes 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. # node-notifier [![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] Send cross platform native notifications using Node.js. Notification Center for macOS, `notify-osd`/`libnotify-bin` for Linux, Toasters for Windows 8/10, or taskbar balloons for earlier Windows versions. Growl is used if none of these requirements are met. [Works well with Electron](#within-electron-packaging). ![macOS Screenshot](https://raw.githubusercontent.com/mikaelbr/node-notifier/master/example/mac.png) ![Native Windows Screenshot](https://raw.githubusercontent.com/mikaelbr/node-notifier/master/example/windows.png) ## Input Example macOS Notification Center ![Input Example](https://raw.githubusercontent.com/mikaelbr/node-notifier/master/example/input-example.gif) ## Actions Example Windows SnoreToast ![Actions Example](https://raw.githubusercontent.com/mikaelbr/node-notifier/master/example/windows-actions-example.gif) ## Quick Usage Show a native notification on macOS, Windows, Linux: ```javascript const notifier = require('node-notifier'); // String notifier.notify('Message'); // Object notifier.notify({ title: 'My notification', message: 'Hello, there!' }); ``` ## Requirements - **macOS**: >= 10.8 for native notifications, or Growl if earlier. - **Linux**: `notify-osd` or `libnotify-bin` installed (Ubuntu should have this by default) - **Windows**: >= 8, or task bar balloons for Windows < 8. Growl as fallback. Growl takes precedence over Windows balloons. - **General Fallback**: Growl See [documentation and flow chart for reporter choice](./DECISION_FLOW.md). ## Install ```shell npm install --save node-notifier ``` ## <abbr title="Command Line Interface">CLI</abbr> <abbr title="Command Line Interface">CLI</abbr> has moved to separate project: <https://github.com/mikaelbr/node-notifier-cli> ## Cross-Platform Advanced Usage Standard usage, with cross-platform fallbacks as defined in the [reporter flow chart](./DECISION_FLOW.md). All of the options below will work in some way or another on most platforms. ```javascript const notifier = require('node-notifier'); const path = require('path'); notifier.notify( { title: 'My awesome title', message: 'Hello from node, Mr. User!', icon: path.join(__dirname, 'coulson.jpg'), // Absolute path (doesn't work on balloons) sound: true, // Only Notification Center or Windows Toasters wait: true // Wait with callback, until user action is taken against notification, does not apply to Windows Toasters as they always wait or notify-send as it does not support the wait option }, function (err, response) { // Response is response from notification } ); notifier.on('click', function (notifierObject, options, event) { // Triggers if `wait: true` and user clicks notification }); notifier.on('timeout', function (notifierObject, options) { // Triggers if `wait: true` and notification closes }); ``` If you want super fine-grained control, you can customize each reporter individually, allowing you to tune specific options for different systems. See below for documentation on each reporter. **Example:** ```javascript const NotificationCenter = require('node-notifier/notifiers/notificationcenter'); new NotificationCenter(options).notify(); const NotifySend = require('node-notifier/notifiers/notifysend'); new NotifySend(options).notify(); const WindowsToaster = require('node-notifier/notifiers/toaster'); new WindowsToaster(options).notify(); const Growl = require('node-notifier/notifiers/growl'); new Growl(options).notify(); const WindowsBalloon = require('node-notifier/notifiers/balloon'); new WindowsBalloon(options).notify(); ``` Or, if you are using several reporters (or you're lazy): ```javascript // NOTE: Technically, this takes longer to require const nn = require('node-notifier'); new nn.NotificationCenter(options).notify(); new nn.NotifySend(options).notify(); new nn.WindowsToaster(options).notify(options); new nn.WindowsBalloon(options).notify(options); new nn.Growl(options).notify(options); ``` ## Contents - [Notification Center documentation](#usage-notificationcenter) - [Windows Toaster documentation](#usage-windowstoaster) - [Windows Balloon documentation](#usage-windowsballoon) - [Growl documentation](#usage-growl) - [Notify-send documentation](#usage-notifysend) ### Usage: `NotificationCenter` Same usage and parameter setup as [**`terminal-notifier`**](https://github.com/julienXX/terminal-notifier). Native Notification Center requires macOS version 10.8 or higher. If you have an earlier version, Growl will be the fallback. If Growl isn't installed, an error will be returned in the callback. #### Example Because `node-notifier` wraps around [**`terminal-notifier`**](https://github.com/julienXX/terminal-notifier), you can do anything `terminal-notifier` can, just by passing properties to the `notify` method. For example: - if `terminal-notifier` says `-message`, you can do `{message: 'Foo'}` - if `terminal-notifier` says `-list ALL`, you can do `{list: 'ALL'}`. Notification is the primary focus of this module, so listing and activating do work, but they aren't documented. ### All notification options with their defaults: ```javascript const NotificationCenter = require('node-notifier').NotificationCenter; var notifier = new NotificationCenter({ withFallback: false, // Use Growl Fallback if <= 10.8 customPath: undefined // Relative/Absolute path to binary if you want to use your own fork of terminal-notifier }); notifier.notify( { title: undefined, subtitle: undefined, message: undefined, sound: false, // Case Sensitive string for location of sound file, or use one of macOS' native sounds (see below) icon: 'Terminal Icon', // Absolute Path to Triggering Icon contentImage: undefined, // Absolute Path to Attached Image (Content Image) open: undefined, // URL to open on Click wait: false, // Wait for User Action against Notification or times out. Same as timeout = 5 seconds // New in latest version. See `example/macInput.js` for usage timeout: 5, // Takes precedence over wait if both are defined. closeLabel: undefined, // String. Label for cancel button actions: undefined, // String | Array<String>. Action label or list of labels in case of dropdown dropdownLabel: undefined, // String. Label to be used if multiple actions reply: false // Boolean. If notification should take input. Value passed as third argument in callback and event emitter. }, function (error, response, metadata) { console.log(response, metadata); } ); ``` --- **Note:** The `wait` option is shorthand for `timeout: 5`. This just sets a timeout for 5 seconds. It does _not_ make the notification sticky! As of Version 6.0 there is a default `timeout` set of `10` to ensure that the application closes properly. In order to remove the `timeout` and have an instantly closing notification (does not support actions), set `timeout` to `false`. If you are using `action` it is recommended to set `timeout` to a high value to ensure the user has time to respond. _Exception:_ If `reply` is defined, it's recommended to set `timeout` to a either high value, or to nothing at all. --- **For macOS notifications: `icon`, `contentImage`, and all forms of `reply`/`actions` require macOS 10.9.** Sound can be one of these: `Basso`, `Blow`, `Bottle`, `Frog`, `Funk`, `Glass`, `Hero`, `Morse`, `Ping`, `Pop`, `Purr`, `Sosumi`, `Submarine`, `Tink`. If `sound` is simply `true`, `Bottle` is used. --- **See Also:** - [Example: specific Notification Centers](./example/advanced.js) - [Example: input](./example/macInput.js). --- **Custom Path clarification** `customPath` takes a value of a relative or absolute path to the binary of your fork/custom version of **`terminal-notifier`**. **Example:** `./vendor/mac.noindex/terminal-notifier.app/Contents/MacOS/terminal-notifier` **Spotlight clarification** `terminal-notifier.app` resides in a `mac.noindex` folder to prevent Spotlight from indexing the app. ### Usage: `WindowsToaster` **Note:** There are some limitations for images in native Windows 8 notifications: - The image must be a PNG image - The image must be smaller than 1024×1024 px - The image must be less than 200kb - The image must be specified using an absolute path These limitations are due to the Toast notification system. A good tip is to use something like `path.join` or `path.delimiter` to keep your paths cross-platform. From [mikaelbr/gulp-notify#90 (comment)](https://github.com/mikaelbr/gulp-notify/issues/90#issuecomment-129333034) > You can make it work by going to System > Notifications & Actions. The 'toast' > app needs to have Banners enabled. (You can activate banners by clicking on the > 'toast' app and setting the 'Show notification banners' to On) --- **Windows 10 Fall Creators Update (Version 1709) Note:** [**Snoretoast**](https://github.com/KDE/snoretoast) is used to get native Windows Toasts! The default behaviour is to have the underlying toaster applicaton as `appID`. This works as expected, but shows `SnoreToast` as text in the notification. With the Fall Creators Update, Notifications on Windows 10 will only work as expected if a valid `appID` is specified. Your `appID` must be exactly the same value that was registered during the installation of your app. You can find the ID of your App by searching the registry for the `appID` you specified at installation of your app. For example: If you use the squirrel framework, your `appID` will be something like `com.squirrel.your.app`. ```javascript const WindowsToaster = require('node-notifier').WindowsToaster; var notifier = new WindowsToaster({ withFallback: false, // Fallback to Growl or Balloons? customPath: undefined // Relative/Absolute path if you want to use your fork of SnoreToast.exe }); notifier.notify( { title: undefined, // String. Required message: undefined, // String. Required if remove is not defined icon: undefined, // String. Absolute path to Icon sound: false, // Bool | String (as defined by http://msdn.microsoft.com/en-us/library/windows/apps/hh761492.aspx) id: undefined, // Number. ID to use for closing notification. appID: undefined, // String. App.ID and app Name. Defaults to no value, causing SnoreToast text to be visible. remove: undefined, // Number. Refer to previously created notification to close. install: undefined // String (path, application, app id). Creates a shortcut <path> in the start menu which point to the executable <application>, appID used for the notifications. }, function (error, response) { console.log(response); } ); ``` ### Usage: `Growl` ```javascript const Growl = require('node-notifier').Growl; var notifier = new Growl({ name: 'Growl Name Used', // Defaults as 'Node' host: 'localhost', port: 23053 }); notifier.notify({ title: 'Foo', message: 'Hello World', icon: fs.readFileSync(__dirname + '/coulson.jpg'), wait: false, // Wait for User Action against Notification // and other growl options like sticky etc. sticky: false, label: undefined, priority: undefined }); ``` See more information about using [growly](https://github.com/theabraham/growly/). ### Usage: `WindowsBalloon` For earlier versions of Windows, taskbar balloons are used (unless fallback is activated and Growl is running). The balloons notifier uses a great project called [**`notifu`**](http://www.paralint.com/projects/notifu/). ```javascript const WindowsBalloon = require('node-notifier').WindowsBalloon; var notifier = new WindowsBalloon({ withFallback: false, // Try Windows Toast and Growl first? customPath: undefined // Relative/Absolute path if you want to use your fork of notifu }); notifier.notify( { title: undefined, message: undefined, sound: false, // true | false. time: 5000, // How long to show balloon in ms wait: false, // Wait for User Action against Notification type: 'info' // The notification type : info | warn | error }, function (error, response) { console.log(response); } ); ``` See full usage on the [project homepage: **`notifu`**](http://www.paralint.com/projects/notifu/). ### Usage: `NotifySend` **Note:** `notify-send` doesn't support the `wait` flag. ```javascript const NotifySend = require('node-notifier').NotifySend; var notifier = new NotifySend(); notifier.notify({ title: 'Foo', message: 'Hello World', icon: __dirname + '/coulson.jpg', wait: false, // Defaults no exipre time set. If true expire time of 5 seconds is used timeout: 10, // Alias for expire-time, time etc. Time before notify-send expires. Defaults to 10 seconds. // .. and other notify-send flags: 'app-name': 'node-notifier', urgency: undefined, category: undefined, hint: undefined }); ``` See flags and options on the man page [`notify-send(1)`](http://manpages.ubuntu.com/manpages/gutsy/man1/notify-send.1.html) ## Thanks to OSS `node-notifier` is made possible through Open Source Software. A very special thanks to all the modules `node-notifier` uses. - [`terminal-notifier`](https://github.com/julienXX/terminal-notifier) - [`Snoretoast`](https://github.com/KDE/snoretoast) - [`notifu`](http://www.paralint.com/projects/notifu/) - [`growly`](https://github.com/theabraham/growly/) [![NPM downloads][npm-downloads]][npm-url] ## Common Issues ### Windows: `SnoreToast` text See note on "Windows 10 Fall Creators Update" in Windows section. _**Short answer:** update your `appID`._ ### Use inside tmux session When using `node-notifier` within a tmux session, it can cause a hang in the system. This can be solved by following the steps described in [this comment](https://github.com/julienXX/terminal-notifier/issues/115#issuecomment-104214742) There’s even more info [here](https://github.com/mikaelbr/node-notifier/issues/61#issuecomment-163560801) <https://github.com/mikaelbr/node-notifier/issues/61#issuecomment-163560801>. ### macOS: Custom icon without Terminal icon Even if you define an icon in the configuration object for `node-notifier`, you will see a small Terminal icon in the notification (see the example at the top of this document). This is the way notifications on macOS work. They always show the icon of the parent application initiating the notification. For `node-notifier`, `terminal-notifier` is the initiator, and it has the Terminal icon defined as its icon. To define your custom icon, you need to fork `terminal-notifier` and build your custom version with your icon. See [Issue #71 for more info](https://github.com/mikaelbr/node-notifier/issues/71) <https://github.com/mikaelbr/node-notifier/issues/71>. ### Within Electron Packaging If packaging your Electron app as an `asar`, you will find `node-notifier` will fail to load. Due to the way asar works, you cannot execute a binary from within an `asar`. As a simple solution, when packaging the app into an asar please make sure you `--unpack` the `vendor/` folder of `node-notifier`, so the module still has access to the notification binaries. You can do so with the following command: ```bash asar pack . app.asar --unpack "./node_modules/node-notifier/vendor/**" ``` ### Using with pkg For issues using with the pkg module. Check this issue out: https://github.com/mikaelbr/node-notifier/issues/220#issuecomment-425963752 ### Using Webpack When using `node-notifier` inside of `webpack`, you must add the snippet below to your `webpack.config.js`. This is necessary because `node-notifier` loads the notifiers from a binary, so it needs a relative file path. When webpack compiles the modules, it supresses file directories, causing `node-notifier` to error on certain platforms. To fix this, you can configure webpack to keep the relative file directories. Do so by append the following code to your `webpack.config.js`: ```javascript node: { __filename: true, __dirname: true } ``` ## License This package is licensed using the [MIT License](http://en.wikipedia.org/wiki/MIT_License). [SnoreToast](https://raw.githubusercontent.com/mikaelbr/node-notifier/master/vendor/snoreToast/LICENSE) and [Notifu](https://raw.githubusercontent.com/mikaelbr/node-notifier/master/vendor/notifu/LICENSE) have licenses in their vendored versions which do not match the MIT license, LGPL-3 and BSD 3-Clause to be specific. We are not lawyers, but have made our best efforts to conform to the terms in those licenses while releasing this package using the license we chose. [npm-url]: https://npmjs.org/package/node-notifier [npm-image]: http://img.shields.io/npm/v/node-notifier.svg?style=flat [npm-downloads]: http://img.shields.io/npm/dm/node-notifier.svg?style=flat [travis-url]: http://travis-ci.org/mikaelbr/node-notifier [travis-image]: http://img.shields.io/travis/mikaelbr/node-notifier.svg?style=flat 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. # w3c-xmlserializer An XML serializer that follows the [W3C specification](https://w3c.github.io/DOM-Parsing/). This module is mostly used as an internal part of [jsdom](https://github.com/jsdom/jsdom). However, you can use it independently with some care. That isn't very well-documented yet, but hopefully the below sample can give you an idea. ## Basic usage ```js const { XMLSerializer } = require("w3c-xmlserializer"); const { JSDOM } = require("jsdom"); const { document } = new JSDOM().window; const XMLSerializer = XMLSerializer.interface; const serializer = new XMLSerializer(); const doc = document.createElement("akomaNtoso"); console.log(serializer.serializeToString(doc)); // => '<akomantoso xmlns="http://www.w3.org/1999/xhtml"></akomantoso>' ``` 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 <nathan@tootallnate.net> 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 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-license-ids) and [spdx-exceptions](https://www.npmjs.com/package/spdx-exceptions) 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. # 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._ # 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.3.0. __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. # 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 <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/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> # 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. ### 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). ## 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) ### 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. [![Build Status](https://travis-ci.org/fgnass/uniqs.svg?branch=master)](https://travis-ci.org/fgnass/uniqs) ### Tiny utility to create unions and de-duplicated lists. Example: ```js var uniqs = require('uniqs'); var foo = { foo: 23 }; var list = [3, 2, 2, 1, foo, foo]; uniqs(list); // => [3, 2, 1, { foo: 23 }] ``` You can pass multiple lists to create a union: ```js uniqs([2, 1, 1], [2, 3, 3, 4], [4, 3, 2]); // => [2, 1, 3, 4] ``` Passing individual items works too: ```js uniqs(3, 2, 2, [1, 1, 2]); // => [3, 2, 1] ``` ### Summary * Uniqueness is defined based on strict object equality. * The lists do not need to be sorted. * The resulting array contains the items in the order of their first appearance. ### About This package has been written to accompany utilities like [flatten](https://npmjs.org/package/flatten) as alternative to full-blown libraries like underscore or lodash. The implementation is optimized for simplicity rather than performance and looks like this: ```js module.exports = function uniqs() { var list = Array.prototype.concat.apply([], arguments); return list.filter(function(item, i) { return i == list.indexOf(item); }); }; ``` ### License MIT # 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 [![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 2016 ([ECMA-262 7th 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) (~1300 [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.parse(program); { type: 'Program', body: [ { type: 'VariableDeclaration', declarations: [Object], kind: 'const' } ], sourceType: 'script' } ``` # CSS Module Loader Core > A loader-agnostic CSS Modules implementation, based on PostCSS [![Build Status](https://travis-ci.org/css-modules/css-modules-loader-core.svg?branch=master)](https://travis-ci.org/css-modules/css-modules-loader-core) ## API ```js import Core from 'css-modules-loader-core' let core = new Core() ``` ### core.load( sourceString , sourcePath , pathFetcher ) =><br>&nbsp;&nbsp;Promise({ injectableSource, exportTokens }) Processes the input CSS `sourceString`, looking for dependencies such as `@import` or `:import`. Any localisation will happen by prefixing a sanitised version of `sourcePath` When dependencies are found, it will ask the `pathFetcher` for each dependency, resolve & inline any imports, and return the following object: - `injectableSource`: the final, merged CSS file without `@import` or `:import` statements - `exportTokens`: the mapping from local name to scoped name, as described in the file's `:export` block These should map nicely to what your build-tool-specific loader needs to do its job. ### new Core([plugins]) The default set of plugins is [[postcss-modules-local-by-default](https://github.com/css-modules/postcss-modules-local-by-default), [postcss-modules-extract-imports](https://github.com/css-modules/postcss-modules-extract-imports), [postcss-modules-scope](https://github.com/css-modules/postcss-modules-scope)] (i.e. the CSS Modules specification). This can override which PostCSS plugins you wish to execute, e.g. ```js import Core from 'css-loader-core' import autoprefixer from 'autoprefixer' import colorFunctions from 'postcss-color-function' // Don't run local-by-default, but use colorFunctions // beforehand and autoprefixer afterwards: let core = new Core([ colorFunctions, core.plugins.extractImports, core.plugins.scope, autoprefixer("Last 2 Versions") ]) ``` 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 ``` # istanbul-lib-source-maps [![Build Status](https://travis-ci.org/istanbuljs/istanbuljs.svg?branch=master)](https://travis-ci.org/istanbuljs/istanbuljs) Source map support for istanbuljs. ## Debugging _istanbul-lib-source-maps_ uses the [debug](https://www.npmjs.com/package/debug) module. Run your application with the environment variable `DEBUG=istanbuljs`, to receive debug output. # 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. ![decimal.js](https://raw.githubusercontent.com/MikeMcl/decimal.js/gh-pages/decimaljs.png) An arbitrary-precision Decimal type for JavaScript. [![Build Status](https://travis-ci.org/MikeMcl/decimal.js.svg)](https://travis-ci.org/MikeMcl/decimal.js) [![CDNJS](https://img.shields.io/cdnjs/v/decimal.js.svg)](https://cdnjs.com/libraries/decimal.js) <br> ## Features - Integers and floats - Simple but full-featured API - Replicates many of the methods of JavaScript's `Number.prototype` and `Math` objects - Also handles hexadecimal, binary and octal values - Faster, smaller, and perhaps easier to use than JavaScript versions of Java's BigDecimal - No dependencies - Wide platform compatibility: uses JavaScript 1.5 (ECMAScript 3) features only - Comprehensive [documentation](http://mikemcl.github.io/decimal.js/) and test set - Includes a TypeScript declaration file: *decimal.d.ts* ![API](https://raw.githubusercontent.com/MikeMcl/decimal.js/gh-pages/API.png) The library is similar to [bignumber.js](https://github.com/MikeMcl/bignumber.js/), but here precision is specified in terms of significant digits rather than decimal places, and all calculations are rounded to the precision (similar to Python's decimal module) rather than just those involving division. This library also adds the trigonometric functions, among others, and supports non-integer powers, which makes it a significantly larger library than *bignumber.js* and the even smaller [big.js](https://github.com/MikeMcl/big.js/). For a lighter version of this library without the trigonometric functions see [decimal.js-light](https://github.com/MikeMcl/decimal.js-light/). ## Load The library is the single JavaScript file *decimal.js* (or minified, *decimal.min.js*). Browser: ```html <script src='path/to/decimal.js'></script> ``` [Node.js](http://nodejs.org): ```bash $ npm install --save decimal.js ``` ```js var Decimal = require('decimal.js'); ``` ES6 module (*decimal.mjs*): ```js //import Decimal from 'decimal.js'; import {Decimal} from 'decimal.js'; ``` AMD loader libraries such as [requireJS](http://requirejs.org/): ```js require(['decimal'], function(Decimal) { // Use Decimal here in local scope. No global Decimal. }); ``` ## 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 object, `Decimal`, the constructor of Decimal instances. It accepts a value of type number, string or Decimal. ```js x = new Decimal(123.4567) y = new Decimal('123456.7e-3') z = new Decimal(x) x.equals(y) && y.equals(z) && x.equals(z) // true ``` A value can also be in binary, hexadecimal or octal if the appropriate prefix is included. ```js x = new Decimal('0xff.f') // '255.9375' y = new Decimal('0b10101100') // '172' z = x.plus(y) // '427.9375' z.toBinary() // '0b110101011.1111' z.toBinary(13) // '0b1.101010111111p+8' ``` Using binary exponential notation to create a Decimal with the value of `Number.MAX_VALUE`: ```js x = new Decimal('0b1.1111111111111111111111111111111111111111111111111111p+1023') ``` A Decimal is immutable in the sense that it is not changed by its methods. ```js 0.3 - 0.1 // 0.19999999999999998 x = new Decimal(0.3) x.minus(0.1) // '0.2' x // '0.3' ``` The methods that return a Decimal can be chained. ```js x.dividedBy(y).plus(z).times(9).floor() x.times('1.23456780123456789e+9').plus(9876.5432321).dividedBy('4444562598.111772').ceil() ``` Many method names have a shorter alias. ```js x.squareRoot().dividedBy(y).toPower(3).equals(x.sqrt().div(y).pow(3)) // true x.cmp(y.mod(z).neg()) == 1 && x.comparedTo(y.modulo(z).negated()) == 1 // true ``` Like JavaScript's Number type, there are `toExponential`, `toFixed` and `toPrecision` methods, ```js x = new Decimal(255.5) x.toExponential(5) // '2.55500e+2' x.toFixed(5) // '255.50000' x.toPrecision(5) // '255.50' ``` and almost all of the methods of JavaScript's Math object are also replicated. ```js Decimal.sqrt('6.98372465832e+9823') // '8.3568682281821340204e+4911' Decimal.pow(2, 0.0979843) // '1.0702770511687781839' ``` There are `isNaN` and `isFinite` methods, as `NaN` and `Infinity` are valid `Decimal` values, ```js x = new Decimal(NaN) // 'NaN' y = new Decimal(Infinity) // 'Infinity' x.isNaN() && !y.isNaN() && !x.isFinite() && !y.isFinite() // true ``` and a `toFraction` method with an optional *maximum denominator* argument ```js z = new Decimal(355) pi = z.dividedBy(113) // '3.1415929204' pi.toFraction() // [ '7853982301', '2500000000' ] pi.toFraction(1000) // [ '355', '113' ] ``` All calculations are rounded according to the number of significant digits and rounding mode specified by the `precision` and `rounding` properties of the Decimal constructor. For advanced usage, multiple Decimal constructors can be created, each with their own independent configuration which applies to all Decimal numbers created from it. ```js // Set the precision and rounding of the default Decimal constructor Decimal.set({ precision: 5, rounding: 4 }) // Create another Decimal constructor, optionally passing in a configuration object Decimal9 = Decimal.clone({ precision: 9, rounding: 1 }) x = new Decimal(5) y = new Decimal9(5) x.div(3) // '1.6667' y.div(3) // '1.66666666' ``` The value of a Decimal is stored in a floating point format in terms of its digits, exponent and sign. ```js x = new Decimal(-12345.67); x.d // [ 12345, 6700000 ] digits (base 10000000) x.e // 4 exponent (base 10) x.s // -1 sign ``` For further information see the [API](http://mikemcl.github.io/decimal.js/) reference in the *doc* directory. ## Test The library can be tested using Node.js or a browser. The *test* directory contains the file *test.js* which runs all the tests when executed by Node, and the file *test.html* which runs all the tests when opened in a browser. To run all the tests, from a command-line at the root directory using npm ```bash $ npm test ``` or at the *test* directory using Node ```bash $ node test ``` Each separate test module can also be executed individually, for example, at the *test/modules* directory ```bash $ node toFraction ``` ## Build For Node, if [uglify-js](https://github.com/mishoo/UglifyJS2) is installed ```bash npm install uglify-js -g ``` then ```bash npm run build ``` will create *decimal.min.js*, and a source map will also be added to the *doc* directory. ## Licence MIT. See *LICENCE.md* # 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;tj@vision-media.ca&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. # range-parser [![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] Range header field parser. ## 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 range-parser ``` ## API <!-- eslint-disable no-unused-vars --> ```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 <!-- eslint-disable no-undef --> ```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. <!-- eslint-disable no-undef --> ```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) [coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/range-parser/master [coveralls-url]: https://coveralls.io/r/jshttp/range-parser?branch=master [node-image]: https://badgen.net/npm/node/range-parser [node-url]: https://nodejs.org/en/download [npm-downloads-image]: https://badgen.net/npm/dm/range-parser [npm-url]: https://npmjs.org/package/range-parser [npm-version-image]: https://badgen.net/npm/v/range-parser [travis-image]: https://badgen.net/travis/jshttp/range-parser/master [travis-url]: https://travis-ci.org/jshttp/range-parser # filesize.js [![build status](https://secure.travis-ci.org/avoidwork/filesize.js.svg)](http://travis-ci.org/avoidwork/filesize.js) [![downloads](https://img.shields.io/npm/dt/filesize.svg)](https://www.npmjs.com/package/filesize) [![CDNJS version](https://img.shields.io/cdnjs/v/filesize.svg)](https://cdnjs.com/libraries/filesize) filesize.js provides a simple way to get a human readable file size string from a number (float or integer) or string. ## Optional settings `filesize()` accepts an optional descriptor Object as a second argument, so you can customize the output. ### base _*(number)*_ Number base, default is `2` ### bits _*(boolean)*_ Enables `bit` sizes, default is `false` ### exponent _*(number)*_ Specifies the symbol via exponent, e.g. `2` is `MB` for base 2, default is `-1` ### fullform _*(boolean)*_ Enables full form of unit of measure, default is `false` ### fullforms _*(array)*_ Array of full form overrides, default is `[]` ### output _*(string)*_ Output of function (`array`, `exponent`, `object`, or `string`), default is `string` ### round _*(number)*_ Decimal place, default is `2` ### separator _*(string)*_ Decimal separator character, default is `.` ### spacer _*(string)*_ Character between the `result` and `suffix`, default is `" "` ### standard _*(string)*_ Standard unit of measure, can be `iec` or `jedec`, default is `jedec`; can be overruled by `base` ### symbols _*(object)*_ Dictionary of SI/JEDEC symbols to replace for localization, defaults to english if no match is found ### suffixes (deprecated: use 'symbols') _*(object)*_ Dictionary of SI/JEDEC symbols to replace for localization, defaults to english if no match is found ### unix _*(boolean)*_ Enables unix style human readable output, e.g `ls -lh`, default is `false` ## Examples ```javascript filesize(500); // "500 B" filesize(500, {bits: true}); // "4 Kb" filesize(265318, {base: 10}); // "265.32 kB" filesize(265318); // "259.1 KB" filesize(265318, {round: 0}); // "259 KB" filesize(265318, {output: "array"}); // [259.1, "KB"] filesize(265318, {output: "object"}); // {value: 259.1, suffix: "KB", symbol: "KB"} filesize(1, {symbols: {B: "Б"}}); // "1 Б" filesize(1024); // "1 KB" filesize(1024, {exponent: 0}); // "1024 B" filesize(1024, {output: "exponent"}); // 1 filesize(265318, {standard: "iec"}); // "259.1 KiB" filesize(265318, {standard: "iec", fullform: true}); // "259.1 kibibytes" filesize(12, {fullform: true, fullforms: ["байтов"]}); // "12 байтов" filesize(265318, {separator: ","}); // "259,1 KB" ``` ## Partial Application `filesize.partial()` takes the second parameter of `filesize()` and returns a new function with the configuration applied upon execution. This can be used to reduce `Object` creation if you call `filesize()` without caching the `descriptor` in lexical scope. ```javascript const size = filesize.partial({standard: "iec"}); size(265318); // "259.1 KiB" ``` ## How can I load filesize.js? filesize.js supports AMD loaders (require.js, curl.js, etc.), node.js & npm (```npm install filesize```), or using a script tag. An ES6 version is bundled with an npm install, but requires you load it with the full path, e.g. `require(path.join(__dirname, 'node_modules', 'filesize', 'lib', 'filesize.es6.js'))`. ## License Copyright (c) 2018 Jason Mulligan Licensed under the BSD-3 license. [![build status](https://secure.travis-ci.org/dankogai/js-base64.png)](http://travis-ci.org/dankogai/js-base64) # base64.js Yet another Base64 transcoder ## Usage ### 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`. ### In Browser * Locally ```html <script src="base64.js"></script> ``` * Directly from CDN. In which case you don't even need to install. ```html <!-- the latest --> <script src="https://cdn.jsdelivr.net/npm/js-base64/base64.min.js"> ``` ```html <!-- with version fixed --> <script src="https://cdn.jsdelivr.net/npm/js-base64@2.6.4/base64.min.js"> ``` ### node.js ```javascript var Base64 = require('js-base64').Base64; ``` ## es6+ ```javascript import { Base64 } from 'js-base64'; ``` ## SYNOPSIS ```javascript Base64.encode('dankogai'); // ZGFua29nYWk= Base64.btoa( 'dankogai'); // ZGFua29nYWk= Base64.fromUint8Array( // ZGFua29nYWk= new Uint8Array([100,97,110,107,111,103,97,105]) ); Base64.fromUint8Array( // ZGFua29nYW which is URI safe new Uint8Array([100,97,110,107,111,103,97,105]), true ); Base64.encode( '小飼弾'); // 5bCP6aO85by+ Base64.encodeURI('小飼弾'); // 5bCP6aO85by- which equals to Base64.encode('小飼弾', true) Base64.btoa( '小飼弾'); // raises exception ``` ```javascript Base64.decode('ZGFua29nYWk='); // dankogai Base64.atob( 'ZGFua29nYWk='); // dankogai Base64.toUint8Array( // new Uint8Array([100,97,110,107,111,103,97,105]) 'ZGFua29nYWk=' ); Base64.decode('5bCP6aO85by+'); // 小飼弾 // note .decodeURI() is unnecessary since it accepts both flavors Base64.decode('5bCP6aO85by-'); // 小飼弾 Base64.atob( '5bCP6aO85by+'); // '小飼弾' which is nonsense ``` ### 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 <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 # cssnano-util-get-arguments > Get a list of arguments, separated by a comma. ## Contributors See [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md). ## License MIT © [Ben Briggs](http://beneb.info) # 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 # [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} } ``` 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> # 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. # [postcss][postcss]-minify-gradients > Minify gradient parameters with PostCSS. ## Install With [npm](https://npmjs.org/package/postcss-minify-gradients) do: ``` npm install postcss-minify-gradients ``` ## Example Where possible, this module will minify gradient parameters. It can convert linear gradient directional syntax to angles, remove the unnecessary `0%` and `100%` start and end values, and minimise color stops that use the same length values (the browser will adjust the value automatically). ### Input ```css h1 { background: linear-gradient(to bottom, #ffe500 0%, #ffe500 50%, #121 50%, #121 100%) } ``` ### Output ```css h1 { background: linear-gradient(180deg, #ffe500, #ffe500 50%, #121 0, #121) } ``` ## Usage See the [PostCSS documentation](https://github.com/postcss/postcss#usage) for examples for your environment. ## Contributors See [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md). ## License MIT © [Ben Briggs](http://beneb.info) [postcss]: https://github.com/postcss/postcss # 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). # 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. # 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:trysound@yandex.ru) # 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._ # 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._ 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**(value: `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. # babel-preset-jest > Babel preset for all Jest plugins. This preset is automatically included when using [babel-jest](https://github.com/facebook/jest/tree/master/packages/babel-jest). ## Install ```sh $ npm install --save-dev babel-preset-jest ``` ## Usage ### Via `babel.config.js` (Recommended) ```js module.exports = { presets: ['jest'], }; ``` ### Via CLI ```sh $ babel script.js --presets jest ``` ### Via Node API ```javascript require('@babel/core').transform('code', { presets: ['jest'], }); ``` # 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](https://evilmartians.com/?utm_source=postcss) at <surrender@evilmartians.com>. [Abstract Syntax Tree]: https://en.wikipedia.org/wiki/Abstract_syntax_tree [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 ### Gulp Use [`gulp-postcss`] and [`gulp-sourcemaps`]. ```js gulp.task('css', function () { var postcss = require('gulp-postcss'); var 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 fs = require('fs'); const postcss = require('postcss'); const precss = require('precss'); const autoprefixer = require('autoprefixer'); 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 ## 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/ # cssnano-util-raw-cache > Manages the raw value formatting for generated AST nodes. ## Contributors See [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md). ## License MIT © [Ben Briggs](http://beneb.info) # 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._ 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> # 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._ # 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`/`es2019` 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` ## Security Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. [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 # 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._ # 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`/`es2019` 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` ## Security Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. [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 # 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. # 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. # [postcss][postcss]-reduce-initial > Reduce `initial` definitions to the *actual* initial value, where possible. ## Install With [npm](https://npmjs.org/package/postcss-reduce-initial) do: ``` npm install postcss-reduce-initial --save ``` ## Examples See the [data](data) for more conversions. This data is courtesy of Mozilla. ### Convert `initial` values When the `initial` keyword is longer than the property value, it will be converted: #### Input ```css h1 { min-width: initial; } ``` #### Output ```css h1 { min-width: 0; } ``` ### Convert values back to `initial` When the `initial` value is smaller than the property value, it will be converted: #### Input ```css h1 { transform-box: border-box; } ``` #### Output ```css h1 { transform-box: initial; } ``` This conversion is only applied when you supply a browsers list that all support the `initial` keyword; it's worth noting that Internet Explorer has no support. ## Usage See the [PostCSS documentation](https://github.com/postcss/postcss#usage) for examples for your environment. ## Contributors See [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md). ## License [Template:CSSData] by Mozilla Contributors is licensed under [CC-BY-SA 2.5]. [Template:CSSData]: https://developer.mozilla.org/en-US/docs/Template:CSSData [CC-BY-SA 2.5]: http://creativecommons.org/licenses/by-sa/2.5/ MIT © [Ben Briggs](http://beneb.info) [postcss]: https://github.com/postcss/postcss # throat Throttle the parallelism of an asynchronous, promise returning, function / functions. This has special utility when you set the concurrency to `1`. That way you get a mutually exclusive lock. [Professionally supported throat is now available](https://tidelift.com/subscription/pkg/npm-throat?utm_source=npm-throat&utm_medium=referral&utm_campaign=readme) [![Build Status](https://img.shields.io/travis/ForbesLindesay/throat/master.svg)](https://travis-ci.org/ForbesLindesay/throat) [![Coverage Status](https://img.shields.io/coveralls/ForbesLindesay/throat/master.svg?style=flat)](https://coveralls.io/r/ForbesLindesay/throat?branch=master) [![Dependency Status](https://img.shields.io/david/ForbesLindesay/throat.svg)](https://david-dm.org/ForbesLindesay/throat) [![NPM version](https://img.shields.io/npm/v/throat.svg)](https://www.npmjs.com/package/throat) [![Greenkeeper badge](https://badges.greenkeeper.io/ForbesLindesay/throat.svg)](https://greenkeeper.io/) ## Installation npm install throat ## API ### throat(concurrency) This returns a function that acts a bit like a lock (exactly as a lock if concurrency is 1). Example, only 2 of the following functions will execute at any one time: ```js const throat = require('throat')(2); // alternatively provide your own promise implementation const throat = require('throat')(require('promise'))(2); const promise = Promise.resolve(); const resA = throat(() => /* async stuff... */ promise); const resB = throat(() => /* async stuff... */ promise); const resC = throat(() => /* async stuff... */ promise); const resD = throat(() => /* async stuff... */ promise); const resE = throat(() => /* async stuff... */ promise); ``` ### throat(concurrency, worker) This returns a function that is an exact copy of `worker` except that it will only execute up to `concurrency` times in parallel before further requests are queued: ```js const throat = require('throat'); // alternatively provide your own promise implementation const throat = require('throat')(require('promise')); const input = ['fileA.txt', 'fileB.txt', 'fileC.txt', 'fileD.txt']; const data = Promise.all(input.map(throat(2, fileName => readFile(fileName)))); ``` Only 2 files will be read at a time, sometimes limiting parallelism in this way can improve scalability. ## 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 # 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/ # 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._ # 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;tj@vision-media.ca&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-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 Status](https://travis-ci.org/node-hid/node-hid.svg?branch=master)](https://travis-ci.org/node-hid/node-hid) [![Build status](https://ci.appveyor.com/api/projects/status/sqgrud8yufx12dbt?svg=true)](https://ci.appveyor.com/project/todbot/node-hid/branch/master) * [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) * [Keyboards and Mice](#keyboards-and-mice) * [Mac notes](#mac-notes) * [Windows notes](#windows-notes) * [Xbox 360 Controller on Windows 10](#xbox-360-controller-on-windows-10) * [Linux notes](#linux-notes) * [Selecting driver type](#selecting-driver-type) * [udev device permissions](#udev-device-permissions) * [Compiling from source](#compiling-from-source) * [Linux (kernel 2.6 ) : (install examples shown for Debian/Ubuntu)](#linux-kernel-26--install-examples-shown-for-debianubuntu) * [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) * [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 16.04 x64 ### Supported Node versions ### * Node v6 to * Node v13 ### Supported Electron versions ### * Electron v1 to * Electron v9 ## Installation For most "standard" use cases (node v4.x on mac, linux, windows on a x86 or x64 processor), `node-hid` will install nice and easy with a standard: ``` 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, mac, windows on standard processor platforms). If you are on a special case, `node-hid` will work, but it will compile the binary when you install. If `node-hid` doesn't have a pre-built binary for your system (e.g. Linux on Raspberry Pi), `node-gyp` is used to compile `node-hid` locally. It will need the pre-requisites listed in [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 like `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. ### Keyboards and Mice 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. There are non-standard work-arounds for this, but in general you cannot use `node-hid` to access keyboard-like devices. ## 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 ### Selecting driver type By default as of `node-hid@0.7.0`, the [hidraw](https://www.kernel.org/doc/Documentation/hid/hidraw.txt) driver is used to talk to HID devices. Before `node-hid@0.7.0`, 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 node-hid@0.5.7 ``` or: ``` npm install node-hid --build-from-source --driver=libusb ``` ### 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). ## Compiling from source To compile & develop locally or if `prebuild` cannot download a pre-built binary for you, you will need the following tools: ### Linux (kernel 2.6+) : (install examples shown for Debian/Ubuntu) * Compilation tools: `apt install build-essential git` * gcc-4.8+: `apt install gcc-4.8 g++-4.8 && export CXX=g++-4.8` * libusb-1.0-0 w/headers:`apt install libusb-1.0-0 libusb-1.0-0-dev` * libudev-dev: `apt install libudev-dev` (Debian/Ubuntu) / `yum install libusbx-devel` (Fedora) ### Mac OS X 10.8+ * [Xcode](https://itunes.apple.com/us/app/xcode/id497799835?mt=12) ### Windows 7, 8, 10 * 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 node ./src/show-devices.js ``` 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 ``` ## 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-toy](https://github.com/todbot/electron-hid-toy) - a simple example of using `node-hid`, that will hopefully always track the latest Electron release * [electron-hid-test](https://github.com/todbot/electron-hid-test) - even simpler example of using `node-hid` * [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-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)); ``` ## Install Install with ``` npm install is-callable ``` ## 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 # 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) # 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;julian@juliangruber.com&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. # 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. 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) # which-pm-runs > Detects what package manager executes the process [![npm version](https://img.shields.io/npm/v/which-pm-runs.svg)](https://www.npmjs.com/package/which-pm-runs) [![Build Status](https://img.shields.io/travis/zkochan/which-pm-runs/master.svg)](https://travis-ci.org/zkochan/which-pm-runs) ## Installation ``` npm i which-pm-runs ``` ## Usage ```js 'use strict' const whichPMRuns = require('which-pm-runs') whichPMRuns() //> {name: "pnpm", version: "0.64.2"} ``` ## Related * [which-pm](https://github.com/zkochan/which-pm) - Detects what package manager was used for installation ## License [MIT](LICENSE) © [Zoltan Kochan](http://kochan.io) # 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. # 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. ## 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. # 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) # 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](https://evilmartians.com/?utm_source=postcss) at <surrender@evilmartians.com>. [Abstract Syntax Tree]: https://en.wikipedia.org/wiki/Abstract_syntax_tree [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 ### Gulp Use [`gulp-postcss`] and [`gulp-sourcemaps`]. ```js gulp.task('css', function () { var postcss = require('gulp-postcss'); var 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 fs = require('fs'); const postcss = require('postcss'); const precss = require('precss'); const autoprefixer = require('autoprefixer'); 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 ## 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/ ## 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'} ``` # babel-jest [Babel](https://github.com/babel/babel) [jest](https://github.com/facebook/jest) plugin ## Usage If you are already using `jest-cli`, add `babel-jest` and it will automatically compile JavaScript code using Babel. ```bash yarn add --dev babel-jest @babel/core ``` If you would like to write your own preprocessor, uninstall and delete babel-jest and set the [config.transform](https://jestjs.io/docs/configuration#transform-object-string-string) option to your preprocessor. ## Setup _Note: this step is only required if you are using `babel-jest` with additional code preprocessors._ To explicitly define `babel-jest` as a transformer for your JavaScript code, map _.js_ files to the `babel-jest` module. Typescript files are also supported. ```json "transform": { "^.+\\.[t|j]sx?$": "babel-jest" }, ``` 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. pako for enterprise ------------------- Available as part of the Tidelift Subscription The maintainers of pako 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-pako?utm_source=npm-pako&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) 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 # 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. # duplexer2 [![Build Status](https://travis-ci.org/deoxxa/duplexer2.svg?branch=master)](https://travis-ci.org/deoxxa/duplexer2) [![Coverage Status](https://coveralls.io/repos/deoxxa/duplexer2/badge.svg?branch=master&service=github)](https://coveralls.io/github/deoxxa/duplexer2?branch=master) Like [duplexer](https://github.com/Raynos/duplexer) but using Streams3 ```javascript var stream = require("stream"); var duplexer2 = require("duplexer2"); var writable = new stream.Writable({objectMode: true}), readable = new stream.Readable({objectMode: true}); writable._write = function _write(input, encoding, done) { if (readable.push(input)) { return done(); } else { readable.once("drain", done); } }; readable._read = function _read(n) { // no-op }; // simulate the readable thing closing after a bit writable.once("finish", function() { setTimeout(function() { readable.push(null); }, 500); }); var duplex = duplexer2(writable, readable); duplex.on("data", function(e) { console.log("got data", JSON.stringify(e)); }); duplex.on("finish", function() { console.log("got finish event"); }); duplex.on("end", function() { console.log("got end event"); }); duplex.write("oh, hi there", function() { console.log("finished writing"); }); duplex.end(function() { console.log("finished ending"); }); ``` ``` got data "oh, hi there" finished writing got finish event finished ending got end event ``` ## Overview This is a reimplementation of [duplexer](https://www.npmjs.com/package/duplexer) using the Streams3 API which is standard in Node as of v4. Everything largely works the same. ## Installation [Available via `npm`](https://docs.npmjs.com/cli/install): ``` $ npm i duplexer2 ``` ## API ### duplexer2 Creates a new `DuplexWrapper` object, which is the actual class that implements most of the fun stuff. All that fun stuff is hidden. DON'T LOOK. ```javascript duplexer2([options], writable, readable) ``` ```javascript const duplex = duplexer2(new stream.Writable(), new stream.Readable()); ``` Arguments * __options__ - an object specifying the regular `stream.Duplex` options, as well as the properties described below. * __writable__ - a writable stream * __readable__ - a readable stream Options * __bubbleErrors__ - a boolean value that specifies whether to bubble errors from the underlying readable/writable streams. Default is `true`. ## License 3-clause BSD. [A copy](./LICENSE) is included with the source. ## Contact * GitHub ([deoxxa](http://github.com/deoxxa)) * Twitter ([@deoxxa](http://twitter.com/deoxxa)) * Email ([deoxxa@fknsrs.biz](mailto:deoxxa@fknsrs.biz)) # 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._ https-proxy-agent ================ ### An HTTP(s) proxy `http.Agent` implementation for HTTPS [![Build Status](https://travis-ci.org/TooTallNate/node-https-proxy-agent.svg?branch=master)](https://travis-ci.org/TooTallNate/node-https-proxy-agent) This module provides an `http.Agent` implementation that connects to a specified HTTP or HTTPS proxy server, and can be used with the built-in `https` module. Specifically, this `Agent` implementation connects to an intermediary "proxy" server and issues the [CONNECT HTTP method][CONNECT], which tells the proxy to open a direct TCP connection to the destination server. Since this agent implements the CONNECT HTTP method, it also works with other protocols that use this method when connecting over proxies (i.e. WebSockets). See the "Examples" section below for more. Installation ------------ Install with `npm`: ``` bash $ npm install https-proxy-agent ``` Examples -------- #### `https` module example ``` js var url = require('url'); var https = require('https'); var HttpsProxyAgent = require('https-proxy-agent'); // HTTP/HTTPS proxy to connect to var proxy = process.env.http_proxy || 'http://168.63.76.32:3128'; console.log('using proxy server %j', proxy); // HTTPS endpoint for the proxy to connect to var endpoint = process.argv[2] || 'https://graph.facebook.com/tootallnate'; console.log('attempting to GET %j', endpoint); var options = url.parse(endpoint); // create an instance of the `HttpsProxyAgent` class with the proxy server information var agent = new HttpsProxyAgent(proxy); options.agent = agent; https.get(options, function (res) { console.log('"response" event!', res.headers); res.pipe(process.stdout); }); ``` #### `ws` WebSocket connection example ``` js var url = require('url'); var WebSocket = require('ws'); var HttpsProxyAgent = require('https-proxy-agent'); // HTTP/HTTPS proxy to connect to var proxy = process.env.http_proxy || 'http://168.63.76.32:3128'; console.log('using proxy server %j', proxy); // WebSocket endpoint for the proxy to connect to var endpoint = process.argv[2] || 'ws://echo.websocket.org'; var parsed = url.parse(endpoint); console.log('attempting to connect to WebSocket %j', endpoint); // create an instance of the `HttpsProxyAgent` class with the proxy server information var options = url.parse(proxy); var agent = new HttpsProxyAgent(options); // finally, initiate the WebSocket connection var socket = new WebSocket(endpoint, { agent: agent }); socket.on('open', function () { console.log('"open" event!'); socket.send('hello world'); }); socket.on('message', function (data, flags) { console.log('"message" event! %j %j', data, flags); socket.close(); }); ``` API --- ### new HttpsProxyAgent(Object options) The `HttpsProxyAgent` class implements an `http.Agent` subclass that connects to the specified "HTTP(s) proxy server" in order to proxy HTTPS and/or WebSocket requests. This is achieved by using the [HTTP `CONNECT` method][CONNECT]. The `options` argument may either be a string URI of the proxy server to use, or an "options" object with more specific properties: * `host` - String - Proxy host to connect to (may use `hostname` as well). Required. * `port` - Number - Proxy port to connect to. Required. * `protocol` - String - If `https:`, then use TLS to connect to the proxy. * `headers` - Object - Additional HTTP headers to be sent on the HTTP CONNECT method. * Any other options given are passed to the `net.connect()`/`tls.connect()` functions. License ------- (The MIT License) Copyright (c) 2013 Nathan Rajlich &lt;nathan@tootallnate.net&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. [CONNECT]: http://en.wikipedia.org/wiki/HTTP_tunnel#HTTP_CONNECT_Tunneling # 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 # 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._ # 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._ # [postcss][postcss]-normalize-positions > Normalize positions with PostCSS. ## Install With [npm](https://npmjs.org/package/postcss-normalize-positions) do: ``` npm install postcss-normalize-positions --save ``` ## Example ### Input ```css div { background-position: bottom left; } ``` ### Output ```css div { background-position:0 100%; } ``` ## Usage See the [PostCSS documentation](https://github.com/postcss/postcss#usage) for examples for your environment. ## Contributors See [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md). ## License MIT © [Ben Briggs](http://beneb.info) [postcss]: https://github.com/postcss/postcss 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. ### 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. 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 ``` # 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. # 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. 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) # Jest 🃏 Delightful JavaScript Testing - **👩🏻‍💻 Developer Ready**: Complete and ready to set-up JavaScript testing solution. Works out of the box for any React project. - **🏃🏽 Instant Feedback**: Failed tests run first. Fast interactive mode can switch between running all tests or only test files related to changed files. - **📸 Snapshot Testing**: Jest can [capture snapshots](https://jestjs.io/docs/snapshot-testing.html) of React trees or other serializable values to simplify UI testing. Read More: https://jestjs.io/ # 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._ # 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 Licensed [3]: http://ci.testling.com/Raynos/xtend.png [4]: http://ci.testling.com/Raynos/xtend # 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._ # normalize-html-whitespace [![NPM Version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] > Safely remove repeating whitespace from HTML text. Using `\s` to normalize HTML whitespace will strip out characters that are actually rendered by a web browser. Such would be classified as a lossy change and would produce a different visual result. This package will collapse multiple whitespace characters down to a single space, while ignoring the following characters: * `\u00a0` or `&nbsp;` (non-breaking space) * `\ufeff` or `&#65279;` (zero-width non-breaking space) …as well as these lesser-known ones: * `\u1680`​ or `&#5760;` (Ogham space mark) * `\u180e` or `&#6158;` (Mongolian vowel separator) * `\u2000​` or `&#8192;` (en quad) * `\u2001` or `&#8193;` (em quad) * `\u2002` or `&#8194;` (en space) * `\u2003` or `&#8195;` (em space) * `\u2004` or `&#8196;` (three-per-em space) * `\u2005` or `&#8197;` (four-per-em space) * `\u2006` or `&#8198;` (six-per-em space) * `\u2007` or `&#8199;` (figure space) * `\u2008` or `&#8200;` (punctuation space) * `\u2009` or `&#8201;` (thin space) * `\u200a` or `&#8202;` (hair space) * `\u2028` or `&#8232;` (line separator) * `\u2029` or `&#8233;` (paragraph separator) * `\u202f` or `&#8239;` (narrow non-breaking space) * `\u205f` or `&#8287;` (medium mathematical space) * `\u3000` or `&#12288;` (ideographic space) For the sake of completeness, the following characters which are not part of `\s` will also not be affected: * `\u200b` or `&#8203;` (zero-width breaking space) Note: this package does not contain an HTML parser. It is meant to be used on text nodes only. ## Installation [Node.js](http://nodejs.org/) `>= 8` is required. Type this at the command line: ```shell npm install normalize-html-whitespace ``` ## Usage ```js const normalizeWhitespace = require('normalize-html-whitespace'); normalizeWhitespace(' foo bar baz '); //-> ' foo bar baz ' ``` [npm-image]: https://img.shields.io/npm/v/normalize-html-whitespace.svg [npm-url]: https://npmjs.com/package/normalize-html-whitespace [travis-image]: https://img.shields.io/travis/stevenvachon/normalize-html-whitespace.svg [travis-url]: https://travis-ci.org/stevenvachon/normalize-html-whitespace # 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 # 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._ # 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). # tr46 An JavaScript implementation of [Unicode Technical Standard #46: Unicode IDNA Compatibility Processing](https://unicode.org/reports/tr46/). ## Installation [Node.js](http://nodejs.org) ≥ 8 is required. To install, type this at the command line: ```shell npm install tr46 # or yarn add 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) * [`processingOption`](#processingOption) * [`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. 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) # [postcss][postcss]-discard-empty > Discard empty rules and values with PostCSS. ## Install With [npm](https://npmjs.org/package/postcss-discard-empty) do: ``` npm install postcss-discard-empty --save ``` ## Example For more examples see the [tests](src/__tests__/index.js). ### Input ```css @font-face; h1 {} {color:blue} h2 {color:} h3 {color:red} ``` ### Output ```css h3 {color:red} ``` ## Usage See the [PostCSS documentation](https://github.com/postcss/postcss#usage) for examples for your environment. ## Contributors See [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md). ## License MIT © [Ben Briggs](http://beneb.info) [postcss]: https://github.com/postcss/postcss # 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/lupomontero/psl.svg)](https://greenkeeper.io/) [![Build Status](https://travis-ci.org/lupomontero/psl.svg?branch=master)](https://travis-ci.org/lupomontero/psl) [![devDependency Status](https://david-dm.org/lupomontero/psl/dev-status.png)](https://david-dm.org/lupomontero/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/). Cross browser testing provided by [<img alt="BrowserStack" width="160" src="./browserstack-logo.svg" />](https://www.browserstack.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/lupomontero/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 <lupomontero@gmail.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. # 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. # 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/jsdom/jsdom). ## Specification conformance whatwg-url is currently up to date with the URL spec up to commit [83adf0c](https://github.com/whatwg/url/commit/83adf0c9ca9a88948e1e5d93374ffded04eec727). 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`. ### `whatwg-url/webidl2js-wrapper` module This module exports the `URL` and `URLSearchParams` [interface wrappers API](https://github.com/jsdom/webidl2js#for-interfaces) generated by [webidl2js](https://github.com/jsdom/webidl2js). ## 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 prepare 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. 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 #is-negative-zero <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 negative zero? === will lie to you. ## Example ```js var isNegativeZero = require('is-negative-zero'); var assert = require('assert'); assert.notOk(isNegativeZero(undefined)); assert.notOk(isNegativeZero(null)); assert.notOk(isNegativeZero(false)); assert.notOk(isNegativeZero(true)); assert.notOk(isNegativeZero(0)); assert.notOk(isNegativeZero(42)); assert.notOk(isNegativeZero(Infinity)); assert.notOk(isNegativeZero(-Infinity)); assert.notOk(isNegativeZero(NaN)); assert.notOk(isNegativeZero('foo')); assert.notOk(isNegativeZero(function () {})); assert.notOk(isNegativeZero([])); assert.notOk(isNegativeZero({})); assert.ok(isNegativeZero(-0)); ``` ## Tests Simply clone the repo, `npm install`, and run `npm test` [1]: https://npmjs.org/package/is-negative-zero [2]: http://vb.teelaun.ch/ljharb/is-negative-zero.svg [3]: https://travis-ci.org/ljharb/is-negative-zero.svg [4]: https://travis-ci.org/ljharb/is-negative-zero [5]: https://david-dm.org/ljharb/is-negative-zero.svg [6]: https://david-dm.org/ljharb/is-negative-zero [7]: https://david-dm.org/ljharb/is-negative-zero/dev-status.svg [8]: https://david-dm.org/ljharb/is-negative-zero#info=devDependencies [9]: https://ci.testling.com/ljharb/is-negative-zero.png [10]: https://ci.testling.com/ljharb/is-negative-zero [11]: https://nodei.co/npm/is-negative-zero.png?downloads=true&stars=true [license-image]: http://img.shields.io/npm/l/is-negative-zero.svg [license-url]: LICENSE [downloads-image]: http://img.shields.io/npm/dm/is-negative-zero.svg [downloads-url]: http://npm-stat.com/charts.html?package=is-negative-zero [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. ### `.canonicalizedDomain()` ### `.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. ### `.removeAllCookies(cb(err))` Removes all cookies from the jar. This is a new backwards-compatible feature of `tough-cookie` version 2.5, so not all Stores will implement it efficiently. For Stores that do not implement `removeAllCookies`, the fallback is to call `removeCookie` after `getAllCookies`. If `getAllCookies` fails or isn't implemented in the Store, that error is returned. If one or more of the `removeCookie` calls fail, only the first error is returned. ### `.removeAllCookiesSync()` Sync version of `.removeAllCookies()` ## 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.removeAllCookies(cb(err))` _Optional_. Removes all cookies from the store. Pass an error if one or more cookies can't be removed. **Note**: New method as of `tough-cookie` version 2.5, so not all Stores will implement this, plus some stores may choose not to implement this. ### `store.getAllCookies(cb(err, cookies))` _Optional_. 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. **Note**: not all Stores can implement this due to technical limitations, so it is optional. ## 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. Supports serialization, `getAllCookies`, and `removeAllCookies`. ## 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: 'tough-cookie@1.x.y', // 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 BSD-3-Clause: ```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. ``` # [hex-color-regex][author-www-url] [![npmjs.com][npmjs-img]][npmjs-url] [![The MIT License][license-img]][license-url] > The best regular expression (regex) for matching hex color values from string. [![code climate][codeclimate-img]][codeclimate-url] [![standard code style][standard-img]][standard-url] [![travis build status][travis-img]][travis-url] [![coverage status][coverage-img]][coverage-url] [![dependency status][david-img]][david-url] ## Install ``` npm i hex-color-regex --save npm test ``` ## Usage > For more use-cases see the [tests](./test.js) - `[opts]` **{Object}** pass `strict: true` for strict mode - `return` **{RegExp}** **Example** ```js var hexColorRegex = require('hex-color-regex') hexColorRegex().test('#f3f}') //=> true hexColorRegex({strict: true}).test('#f3f}') //=> false hexColorRegex().test('foo #f3f bar') //=> true hexColorRegex({strict: true}).test('foo #f3f bar') //=> false hexColorRegex().test('#a54f2c}') //=> true hexColorRegex({strict: true}).test('#a54f2c}') //=> false hexColorRegex().test('foo #a54f2c bar') //=> true hexColorRegex({strict: true}).test('foo #a54f2c bar') //=> false hexColorRegex().test('#ffff') //=> false hexColorRegex().test('ffff') //=> false hexColorRegex().test('#fff') //=> true hexColorRegex().test('fff') //=> false hexColorRegex().test('#4g1') //=> false hexColorRegex().test('4g1') //=> false hexColorRegex().test('#zY1') //=> false hexColorRegex().test('zY1') //=> false hexColorRegex().test('#7f68ZY') //=> false hexColorRegex().test('7f68ZY') //=> false hexColorRegex().test('ffffff') //=> false hexColorRegex().test('#afebe3') //=> true hexColorRegex().test('#AFEBE3') //=> true hexColorRegex().test('#3cb371') //=> true hexColorRegex().test('#3CB371') //=> true hexColorRegex().test('#556b2f') //=> true hexColorRegex().test('#556B2F') //=> true hexColorRegex().test('#708090') //=> true hexColorRegex().test('#7b68ee') //=> true hexColorRegex().test('#7B68EE') //=> true hexColorRegex().test('#eeeeee') //=> true hexColorRegex().test('#ffffff') //=> true hexColorRegex().test('#111111') //=> true hexColorRegex().test('#afe') //=> true hexColorRegex().test('#AF3') //=> true hexColorRegex().test('#3cb') //=> true hexColorRegex().test('#3CB') //=> true hexColorRegex().test('#b2f') //=> true hexColorRegex().test('#5B2') //=> true hexColorRegex().test('#708') //=> true hexColorRegex().test('#68e') //=> true hexColorRegex().test('#7AF') //=> true hexColorRegex().test('#777') //=> true hexColorRegex().test('#FFF') //=> true hexColorRegex().test('#fff') //=> true ``` ## Matching groups - `match[0]` hex value with hash - `#f3f3f3` - `match[1]` hex value without the hash - `f3f3f3` **Example** ```js hexColorRegex().exec('foo #fff bar') //=> [ '#fff', 'fff', index: 4, input: 'foo #fff bar' ] hexColorRegex({strict: true}).exec('foo #fff bar') //=> null hexColorRegex().exec('foo #f3f3f3 bar') //=> [ '#f3f3f3', 'f3f3f3', index: 4, input: 'foo #f3f3f3 bar' ] hexColorRegex({strict: true}).exec('foo #f3f3f3 bar') //=> null ``` ## Related - [benz](https://github.com/tunnckocore/benz): Compose your control flow with absolute elegance. Support async/await, callbacks, thunks, generators, promises, observables, child… [more](https://github.com/tunnckocore/benz) - [is-hexcolor](https://github.com/tunnckocore/is-hexcolor): Check that given value is valid hex color, using `hex-color-regex` - the best regex for… [more](https://github.com/tunnckocore/is-hexcolor) - [is-ansi](https://github.com/tunnckocore/is-ansi): Check that given string contain ANSI color codes, without CLI - [is-missing](https://github.com/tunnckocore/is-missing): Check that given `name` or `user/repo` exists in npm registry or in github as user… [more](https://github.com/tunnckocore/is-missing) - [is-kindof](https://github.com/tunnckocore/is-kindof): Check type of given javascript value. Support promises, generators, streams, and native types. Thin wrapper… [more](https://github.com/tunnckocore/is-kindof) - [is-typeof-error](https://github.com/tunnckocore/is-typeof-error): Check that given value is any type of error and instanceof Error - [is-async-function](https://github.com/tunnckocore/is-async-function): Check that given function is async (callback) function or not. Trying to guess that based… [more](https://github.com/tunnckocore/is-async-function) - [kind-error](https://github.com/tunnckocore/kind-error): Correct inheriting from `Error`. Supports constructing from an object of properties - focused on assertion. - [kind-of-extra](https://github.com/tunnckocore/kind-of-extra): Extends `kind-of` type check utility with support for promises, generators, streams and errors. Like `kindof(Promise.resolve(1))… [more](https://github.com/tunnckocore/kind-of-extra) - [vez](https://github.com/tunnckocore/vez): Middleware composition at new level. Ultimate alternative to `ware`, `plugins`, `koa-compose` and `composition` packages. Allows… [more](https://github.com/tunnckocore/vez) ## Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/regexhq/hex-color-regex/issues/new). But before doing anything, please read the [CONTRIBUTING.md](./CONTRIBUTING.md) guidelines. ## [Charlike Make Reagent](http://j.mp/1stW47C) [![new message to charlike][new-message-img]][new-message-url] [![freenode #charlike][freenode-img]][freenode-url] [![tunnckocore.tk][author-www-img]][author-www-url] [![keybase tunnckocore][keybase-img]][keybase-url] [![tunnckoCore npm][author-npm-img]][author-npm-url] [![tunnckoCore twitter][author-twitter-img]][author-twitter-url] [![tunnckoCore github][author-github-img]][author-github-url] [npmjs-url]: https://www.npmjs.com/package/hex-color-regex [npmjs-img]: https://img.shields.io/npm/v/hex-color-regex.svg?label=hex-color-regex [license-url]: https://github.com/regexhq/hex-color-regex/blob/master/LICENSE.md [license-img]: https://img.shields.io/badge/license-MIT-blue.svg [codeclimate-url]: https://codeclimate.com/github/regexps/hex-color-regex [codeclimate-img]: https://img.shields.io/codeclimate/github/regexps/hex-color-regex.svg [coverage-url]: https://codeclimate.com/github/regexps/hex-color-regex [coverage-img]: https://img.shields.io/codeclimate/coverage/github/regexps/hex-color-regex.svg [travis-url]: https://travis-ci.org/regexhq/hex-color-regex [travis-img]: https://img.shields.io/travis/regexhq/hex-color-regex.svg [coveralls-url]: https://coveralls.io/r/regexhq/hex-color-regex [coveralls-img]: https://img.shields.io/coveralls/regexhq/hex-color-regex.svg [david-url]: https://david-dm.org/regexhq/hex-color-regex [david-img]: https://img.shields.io/david/dev/regexhq/hex-color-regex.svg [standard-url]: https://github.com/feross/standard [standard-img]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [author-www-url]: http://www.tunnckocore.tk [author-www-img]: https://img.shields.io/badge/www-tunnckocore.tk-fe7d37.svg [keybase-url]: https://keybase.io/tunnckocore [keybase-img]: https://img.shields.io/badge/keybase-tunnckocore-8a7967.svg [author-npm-url]: https://www.npmjs.com/~tunnckocore [author-npm-img]: https://img.shields.io/badge/npm-~tunnckocore-cb3837.svg [author-twitter-url]: https://twitter.com/tunnckoCore [author-twitter-img]: https://img.shields.io/badge/twitter-@tunnckoCore-55acee.svg [author-github-url]: https://github.com/tunnckoCore [author-github-img]: https://img.shields.io/badge/github-@tunnckoCore-4183c4.svg [freenode-url]: http://webchat.freenode.net/?channels=charlike [freenode-img]: https://img.shields.io/badge/freenode-%23charlike-5654a4.svg [new-message-url]: https://github.com/tunnckoCore/messages [new-message-img]: https://img.shields.io/badge/send%20me-message-green.svg # 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] } ``` # 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] 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/es-shims/object.getownpropertydescriptors.svg [travis-svg]: https://travis-ci.org/es-shims/Object.getOwnPropertyDescriptors.svg [travis-url]: https://travis-ci.org/es-shims/Object.getOwnPropertyDescriptors [deps-svg]: https://david-dm.org/es-shims/object.getownpropertydescriptors.svg [deps-url]: https://david-dm.org/es-shims/object.getownpropertydescriptors [dev-deps-svg]: https://david-dm.org/es-shims/object.getownpropertydescriptors/dev-status.svg [dev-deps-url]: https://david-dm.org/es-shims/object.getownpropertydescriptors#info=devDependencies [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 ![Async Logo](https://raw.githubusercontent.com/caolan/async/master/logo/async-logo_readme.jpg) [![Build Status via Travis CI](https://travis-ci.org/caolan/async.svg?branch=master)](https://travis-ci.org/caolan/async) [![NPM version](https://img.shields.io/npm/v/async.svg)](https://www.npmjs.com/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) [![libhive - Open source examples](https://www.libhive.com/providers/npm/packages/async/examples/badge.svg)](https://www.libhive.com/providers/npm/packages/async) [![jsDelivr Hits](https://data.jsdelivr.com/v1/package/npm/async/badge?style=rounded)](https://www.jsdelivr.com/package/npm/async) Async is a utility module which provides straight-forward, powerful functions for working with [asynchronous JavaScript](http://caolan.github.io/async/global.html). Although originally designed for use with [Node.js](https://nodejs.org/) and installable via `npm install --save async`, it can also be used directly in the browser. This version of the package is optimized for the Node.js environment. If you use Async with webpack, install [`async-es`](https://www.npmjs.com/package/async-es) instead. For Documentation, visit <https://caolan.github.io/async/> *For Async v1.5.x documentation, go [HERE](https://github.com/caolan/async/blob/v1.5.2/README.md)* ```javascript // for use with Node-style callbacks... var async = require("async"); var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; var configs = {}; async.forEachOf(obj, (value, key, callback) => { fs.readFile(__dirname + value, "utf8", (err, data) => { if (err) return callback(err); try { configs[key] = JSON.parse(data); } catch (e) { return callback(e); } callback(); }); }, err => { if (err) console.error(err.message); // configs is now a map of JSON data doSomethingWith(configs); }); ``` ```javascript var async = require("async"); // ...or ES2017 async functions async.mapLimit(urls, 5, async function(url) { const response = await fetch(url) return response.body }, (err, results) => { if (err) throw err // results is now an array of the response bodies console.log(results) }) ``` # ws: a Node.js WebSocket library [![Version npm](https://img.shields.io/npm/v/ws.svg?logo=npm)](https://www.npmjs.com/package/ws) [![Linux Build](https://img.shields.io/travis/websockets/ws/master.svg?logo=travis)](https://travis-ci.org/websockets/ws) [![Windows Build](https://img.shields.io/appveyor/ci/lpinca/ws/master.svg?logo=appveyor)](https://ci.appveyor.com/project/lpinca/ws) [![Coverage Status](https://img.shields.io/coveralls/websockets/ws/master.svg)](https://coveralls.io/github/websockets/ws) ws is a simple to use, blazing fast, and thoroughly tested WebSocket client and server implementation. Passes the quite extensive Autobahn test suite: [server][server-report], [client][client-report]. **Note**: This module does not work in the browser. The client in the docs is a reference to a back end with the role of a client in the WebSocket communication. Browser clients must use the native [`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) object. To make the same code work seamlessly on Node.js and the browser, you can use one of the many wrappers available on npm, like [isomorphic-ws](https://github.com/heineiuo/isomorphic-ws). ## Table of Contents - [Protocol support](#protocol-support) - [Installing](#installing) - [Opt-in for performance and spec compliance](#opt-in-for-performance-and-spec-compliance) - [API docs](#api-docs) - [WebSocket compression](#websocket-compression) - [Usage examples](#usage-examples) - [Sending and receiving text data](#sending-and-receiving-text-data) - [Sending binary data](#sending-binary-data) - [Simple server](#simple-server) - [External HTTP/S server](#external-https-server) - [Multiple servers sharing a single HTTP/S server](#multiple-servers-sharing-a-single-https-server) - [Server broadcast](#server-broadcast) - [echo.websocket.org demo](#echowebsocketorg-demo) - [Other examples](#other-examples) - [Error handling best practices](#error-handling-best-practices) - [FAQ](#faq) - [How to get the IP address of the client?](#how-to-get-the-ip-address-of-the-client) - [How to detect and close broken connections?](#how-to-detect-and-close-broken-connections) - [How to connect via a proxy?](#how-to-connect-via-a-proxy) - [Changelog](#changelog) - [License](#license) ## Protocol support - **HyBi drafts 07-12** (Use the option `protocolVersion: 8`) - **HyBi drafts 13-17** (Current default, alternatively option `protocolVersion: 13`) ## Installing ``` npm install ws ``` ### Opt-in for performance and spec compliance There are 2 optional modules that can be installed along side with the ws module. These modules are binary addons which improve certain operations. Prebuilt binaries are available for the most popular platforms so you don't necessarily need to have a C++ compiler installed on your machine. - `npm install --save-optional bufferutil`: Allows to efficiently perform operations such as masking and unmasking the data payload of the WebSocket frames. - `npm install --save-optional utf-8-validate`: Allows to efficiently check if a message contains valid UTF-8 as required by the spec. ## API docs See [`/doc/ws.md`](./doc/ws.md) for Node.js-like docs for the ws classes. ## WebSocket compression ws supports the [permessage-deflate extension][permessage-deflate] which enables the client and server to negotiate a compression algorithm and its parameters, and then selectively apply it to the data payloads of each WebSocket message. The extension is disabled by default on the server and enabled by default on the client. It adds a significant overhead in terms of performance and memory consumption so we suggest to enable it only if it is really needed. Note that Node.js has a variety of issues with high-performance compression, where increased concurrency, especially on Linux, can lead to [catastrophic memory fragmentation][node-zlib-bug] and slow performance. If you intend to use permessage-deflate in production, it is worthwhile to set up a test representative of your workload and ensure Node.js/zlib will handle it with acceptable performance and memory usage. Tuning of permessage-deflate can be done via the options defined below. You can also use `zlibDeflateOptions` and `zlibInflateOptions`, which is passed directly into the creation of [raw deflate/inflate streams][node-zlib-deflaterawdocs]. See [the docs][ws-server-options] for more options. ```js const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080, perMessageDeflate: { zlibDeflateOptions: { // See zlib defaults. chunkSize: 1024, memLevel: 7, level: 3 }, zlibInflateOptions: { chunkSize: 10 * 1024 }, // Other options settable: clientNoContextTakeover: true, // Defaults to negotiated value. serverNoContextTakeover: true, // Defaults to negotiated value. serverMaxWindowBits: 10, // Defaults to negotiated value. // Below options specified as default values. concurrencyLimit: 10, // Limits zlib concurrency for perf. threshold: 1024 // Size (in bytes) below which messages // should not be compressed. } }); ``` The client will only use the extension if it is supported and enabled on the server. To always disable the extension on the client set the `perMessageDeflate` option to `false`. ```js const WebSocket = require('ws'); const ws = new WebSocket('ws://www.host.com/path', { perMessageDeflate: false }); ``` ## Usage examples ### Sending and receiving text data ```js const WebSocket = require('ws'); const ws = new WebSocket('ws://www.host.com/path'); ws.on('open', function open() { ws.send('something'); }); ws.on('message', function incoming(data) { console.log(data); }); ``` ### Sending binary data ```js const WebSocket = require('ws'); const ws = new WebSocket('ws://www.host.com/path'); ws.on('open', function open() { const array = new Float32Array(5); for (var i = 0; i < array.length; ++i) { array[i] = i / 2; } ws.send(array); }); ``` ### Simple server ```js const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', function connection(ws) { ws.on('message', function incoming(message) { console.log('received: %s', message); }); ws.send('something'); }); ``` ### External HTTP/S server ```js const fs = require('fs'); const https = require('https'); const WebSocket = require('ws'); const server = new https.createServer({ cert: fs.readFileSync('/path/to/cert.pem'), key: fs.readFileSync('/path/to/key.pem') }); const wss = new WebSocket.Server({ server }); wss.on('connection', function connection(ws) { ws.on('message', function incoming(message) { console.log('received: %s', message); }); ws.send('something'); }); server.listen(8080); ``` ### Multiple servers sharing a single HTTP/S server ```js const http = require('http'); const WebSocket = require('ws'); const server = http.createServer(); const wss1 = new WebSocket.Server({ noServer: true }); const wss2 = new WebSocket.Server({ noServer: true }); wss1.on('connection', function connection(ws) { // ... }); wss2.on('connection', function connection(ws) { // ... }); server.on('upgrade', function upgrade(request, socket, head) { const pathname = url.parse(request.url).pathname; if (pathname === '/foo') { wss1.handleUpgrade(request, socket, head, function done(ws) { wss1.emit('connection', ws, request); }); } else if (pathname === '/bar') { wss2.handleUpgrade(request, socket, head, function done(ws) { wss2.emit('connection', ws, request); }); } else { socket.destroy(); } }); server.listen(8080); ``` ### Server broadcast ```js const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); // Broadcast to all. wss.broadcast = function broadcast(data) { wss.clients.forEach(function each(client) { if (client.readyState === WebSocket.OPEN) { client.send(data); } }); }; wss.on('connection', function connection(ws) { ws.on('message', function incoming(data) { // Broadcast to everyone else. wss.clients.forEach(function each(client) { if (client !== ws && client.readyState === WebSocket.OPEN) { client.send(data); } }); }); }); ``` ### echo.websocket.org demo ```js const WebSocket = require('ws'); const ws = new WebSocket('wss://echo.websocket.org/', { origin: 'https://websocket.org' }); ws.on('open', function open() { console.log('connected'); ws.send(Date.now()); }); ws.on('close', function close() { console.log('disconnected'); }); ws.on('message', function incoming(data) { console.log(`Roundtrip time: ${Date.now() - data} ms`); setTimeout(function timeout() { ws.send(Date.now()); }, 500); }); ``` ### Other examples For a full example with a browser client communicating with a ws server, see the examples folder. Otherwise, see the test cases. ## Error handling best practices ```js // If the WebSocket is closed before the following send is attempted ws.send('something'); // Errors (both immediate and async write errors) can be detected in an optional // callback. The callback is also the only way of being notified that data has // actually been sent. ws.send('something', function ack(error) { // If error is not defined, the send has been completed, otherwise the error // object will indicate what failed. }); // Immediate errors can also be handled with `try...catch`, but **note** that // since sends are inherently asynchronous, socket write failures will *not* be // captured when this technique is used. try { ws.send('something'); } catch (e) { /* handle error */ } ``` ## FAQ ### How to get the IP address of the client? The remote IP address can be obtained from the raw socket. ```js const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', function connection(ws, req) { const ip = req.connection.remoteAddress; }); ``` When the server runs behind a proxy like NGINX, the de-facto standard is to use the `X-Forwarded-For` header. ```js wss.on('connection', function connection(ws, req) { const ip = req.headers['x-forwarded-for'].split(/\s*,\s*/)[0]; }); ``` ### How to detect and close broken connections? Sometimes the link between the server and the client can be interrupted in a way that keeps both the server and the client unaware of the broken state of the connection (e.g. when pulling the cord). In these cases ping messages can be used as a means to verify that the remote endpoint is still responsive. ```js const WebSocket = require('ws'); function noop() {} function heartbeat() { this.isAlive = true; } const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', function connection(ws) { ws.isAlive = true; ws.on('pong', heartbeat); }); const interval = setInterval(function ping() { wss.clients.forEach(function each(ws) { if (ws.isAlive === false) return ws.terminate(); ws.isAlive = false; ws.ping(noop); }); }, 30000); ``` Pong messages are automatically sent in response to ping messages as required by the spec. Just like the server example above your clients might as well lose connection without knowing it. You might want to add a ping listener on your clients to prevent that. A simple implementation would be: ```js const WebSocket = require('ws'); function heartbeat() { clearTimeout(this.pingTimeout); // Use `WebSocket#terminate()` and not `WebSocket#close()`. Delay should be // equal to the interval at which your server sends out pings plus a // conservative assumption of the latency. this.pingTimeout = setTimeout(() => { this.terminate(); }, 30000 + 1000); } const client = new WebSocket('wss://echo.websocket.org/'); client.on('open', heartbeat); client.on('ping', heartbeat); client.on('close', function clear() { clearTimeout(this.pingTimeout); }); ``` ### How to connect via a proxy? Use a custom `http.Agent` implementation like [https-proxy-agent][] or [socks-proxy-agent][]. ## Changelog We're using the GitHub [releases][changelog] for changelog entries. ## License [MIT](LICENSE) [https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent [socks-proxy-agent]: https://github.com/TooTallNate/node-socks-proxy-agent [client-report]: http://websockets.github.io/ws/autobahn/clients/ [server-report]: http://websockets.github.io/ws/autobahn/servers/ [permessage-deflate]: https://tools.ietf.org/html/rfc7692 [changelog]: https://github.com/websockets/ws/releases [node-zlib-bug]: https://github.com/nodejs/node/issues/8871 [node-zlib-deflaterawdocs]: https://nodejs.org/api/zlib.html#zlib_zlib_createdeflateraw_options [ws-server-options]: https://github.com/websockets/ws/blob/master/doc/ws.md#new-websocketserveroptions-callback # simple-get [![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-get/master.svg [travis-url]: https://travis-ci.org/feross/simple-get [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) {}) ``` ### 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). # collect-v8-coverage Use this module to start and stop the V8 inspector manually and collect precise coverage. ```js const {CoverageInstrumenter} = require('collect-v8-coverage'); const instrumenter = new CoverageInstrumenter(); await instrumenter.startInstrumenting(); // require some modules, run some code const coverage = await instrumenter.stopInstrumenting(); ``` # 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._ # is-color-stop Check if a string is CSS color stop [![NPM version](https://img.shields.io/npm/v/is-color-stop.svg?style=flat)](https://npmjs.org/package/is-color-stop) [![Build Status](https://img.shields.io/travis/pigcan/is-color-stop.svg?style=flat)](https://travis-ci.org/pigcan/is-color-stop) [![Coverage Status](https://img.shields.io/coveralls/pigcan/is-color-stop.svg?style=flat)](https://coveralls.io/r/pigcan/is-color-stop) [![NPM downloads](http://img.shields.io/npm/dm/is-color-stop.svg?style=flat)](https://npmjs.org/package/is-color-stop) [![Dependency Status](https://david-dm.org/pigcan/is-color-stop.svg)](https://david-dm.org/pigcan/is-color-stop) ## Install ```shell $ npm install is-color-stop ``` ## Usage ```js const isColorStop = require('is-color-stop'); isColorStop('yellow') // true isColorStop('yellow', '12px') // true isColorStop('yellow', 'calc(100%)') // true isColorStop('yellow', 'px') // false isColorStop.isColor('red') // true isColorStop.isColor('rgb(255)') // false isColorStop.isRGB('rgb(255, 0, 0)') // true isColorStop.isRGB('rgb(255)') // false isColorStop.isRGBA('rgba(255, 0, 0, .8)') // true isColorStop.isRGBA('rgba(255, 0, 0)') // false isColorStop.isHSL('hsl(123, 45%, 67%)') // true isColorStop.isHSL('hsl(123, 45%)') // false isColorStop.isHSLA('hsla(123, 45%, 67%, 0.4)') // true isColorStop.isHSLA('hsla(123, 45%, 67%)') // false isColorStop.isHex('#fff') // true isColorStop.isHex('#ff') // false isColorStop.isCSSColorName('tomato') // true isColorStop.isCSSColorName('hoge') // false isColorStop.isCSSLengthUnit('px') // true isColorStop.isCSSLengthUnit('x') // false isColorStop.isTransparent('transparent') // true ``` ## License The MIT License (MIT) Copyright (c) 2017 Pigcan [![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 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')` # 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._ <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'); ``` <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 # 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 # [postcss][postcss]-unique-selectors > Ensure CSS selectors are unique. ## Install With [npm](https://npmjs.org/package/postcss-unique-selectors) do: ``` npm install postcss-unique-selectors --save ``` ## Example Selectors are sorted naturally, and deduplicated: ### Input ```css h1,h3,h2,h1 { color: red } ``` ### Output ```css h1,h2,h3 { color: red } ``` ## Usage See the [PostCSS documentation](https://github.com/postcss/postcss#usage) for examples for your environment. ## Contributors See [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md). ## License MIT © [Ben Briggs](http://beneb.info) [postcss]: https://github.com/postcss/postcss # merge-source-map [![npm-version](https://img.shields.io/npm/v/merge-source-map.svg?style=flat-square)](https://npmjs.org/package/merge-source-map) [![travis-ci](https://img.shields.io/travis/keik/merge-source-map.svg?style=flat-square)](https://travis-ci.org/keik/merge-source-map) [![Coverage Status](https://img.shields.io/coveralls/keik/merge-source-map.svg?style=flat-square)](https://coveralls.io/github/keik/merge-source-map) Merge old source map and new source map in multi-transform flow # API ```javascript var merge = require('merge-source-map') ``` ## `merge(oldMap, newMap)` Merge old source map and new source map and return merged. If old or new source map value is falsy, return another one as it is. <dl> <dt> <code>oldMap</code> : <code>object|undefined</code> </dt> <dd> old source map object </dd> <dt> <code>newmap</code> : <code>object|undefined</code> </dt> <dd> new source map object </dd> </dl> # Example ```javascript var esprima = require('esprima'), estraverse = require('estraverse'), escodegen = require('escodegen'), convert = require('convert-source-map'), merge = require('merge-source-map') const CODE = 'a = 1', FILEPATH = 'a.js' // create AST of original code var ast = esprima.parse(CODE, {sourceType: 'module', loc: true}) // transform AST of original code estraverse.replace(ast, { enter: function(node, parent) { /* change AST */ }, leave: function(node, parent) { /* change AST */ } }) // generate code and source map from transformed AST var gen = escodegen.generate(ast, { sourceMap: FILEPATH, sourceMapWithCode: true, sourceContent: CODE }) // merge old source map and new source map var oldMap = convert.fromSource(CODE) && convert.fromSource(CODE).toObject(), newMap = JSON.parse(gen.map.toString()), mergedMap = merge(oldMap, newMap), mapComment = convert.fromObject(mergedMap).toComment() // attach merge source map to transformed code var transformed = gen.code + '\n' + mapComment console.log(transformed); ``` # Test ``` % npm install % npm test ``` # License MIT (c) keik [![NPM][npm]][npm-url] [![Deps][deps]][deps-url] [![Tests][build]][build-url] [![Coverage][cover]][cover-url] [![Standard Code Style][code-style]][code-style-url] [![Twitter][twitter]][twitter-url] [![Chat][chat]][chat-url] # PostHTML <img align="right" width="220" height="200" title="PostHTML" src="http://posthtml.github.io/posthtml/logo.svg"> PostHTML is a tool for transforming HTML/XML with JS plugins. PostHTML itself is very small. It includes only a HTML parser, a HTML node tree API and a node tree stringifier. All HTML transformations are made by plugins. And these plugins are just small plain JS functions, which receive a HTML node tree, transform it, and return a modified tree. For more detailed information about PostHTML in general take a look at the [docs][docs-url]. ### Dependencies | Name | Status | Description | |:----:|:------:|:-----------:| |[posthtml-parser][parser]|[![npm][parser-badge]][parser-npm]| Parser HTML/XML to PostHTMLTree | |[posthtml-render][render]|[![npm][render-badge]][render-npm]| Render PostHTMLTree to HTML/XML | [docs]: https://github.com/posthtml/posthtml/blob/master/docs [parser]: https://github.com/posthtml/posthtml-parser [parser-badge]: https://img.shields.io/npm/v/posthtml-parser.svg [parser-npm]: https://npmjs.com/package/posthtml-parser [render]: https://github.com/posthtml/posthtml-render [render-badge]: https://img.shields.io/npm/v/posthtml-render.svg [render-npm]: https://npmjs.com/package/posthtml-render ## Install ```bash npm i -D posthtml ``` ## Usage ### API **Sync** ```js import posthtml from 'posthtml' const html = ` <component> <title>Super Title</title> <text>Awesome Text</text> </component> ` const result = posthtml() .use(require('posthtml-custom-elements')()) .process(html, { sync: true }) .html console.log(result) ``` ```html <div class="component"> <div class="title">Super Title</div> <div class="text">Awesome Text</div> </div> ``` > :warning: Async Plugins can't be used in sync mode and will throw an Error. It's recommended to use PostHTML asynchronously whenever possible. **Async** ```js import posthtml from 'posthtml' const html = ` <html> <body> <p class="wow">OMG</p> </body> </html> ` posthtml( [ require('posthtml-to-svg-tags')(), require('posthtml-extend-attrs')({ attrsTree: { '.wow' : { id: 'wow_id', fill: '#4A83B4', 'fill-rule': 'evenodd', 'font-family': 'Verdana' } } }) ]) .process(html/*, options */) .then((result) => console.log(result.html)) ``` ```html <svg xmlns="http://www.w3.org/2000/svg"> <text class="wow" id="wow_id" fill="#4A83B4" fill-rule="evenodd" font-family="Verdana"> OMG </text> </svg> ``` **Directives** ```js import posthtml from 'posthtml' const php = ` <component> <title><?php echo $title; ?></title> <text><?php echo $article; ?></text> </component> ` const result = posthtml() .use(require('posthtml-custom-elements')()) .process(html, { directives: [ { name: '?php', start: '<', end: '>' } ] }) .html console.log(result) ``` ```html <div class="component"> <div class="title"><?php echo $title; ?></div> <div class="text"><?php echo $article; ?></div> </div> ``` ### [CLI](https://npmjs.com/package/posthtml-cli) ```bash npm i posthtml-cli ``` ```json "scripts": { "posthtml": "posthtml -o output.html -i input.html -c config.json" } ``` ```bash npm run posthtml ``` ### [Gulp](https://gulpjs.com) ```bash npm i -D gulp-posthtml ``` ```js import tap from 'gulp-tap' import posthtml from 'gulp-posthtml' import { task, src, dest } from 'gulp' task('html', () => { let path const plugins = [ require('posthtml-include')({ root: `${path}` }) ] const options = {} src('src/**/*.html') .pipe(tap((file) => path = file.path)) .pipe(posthtml(plugins, options)) .pipe(dest('build/')) }) ``` Check [project-stub](https://github.com/posthtml/project-stub) for an example with Gulp ### [Grunt](https://gruntjs.com) ```bash npm i -D grunt-posthtml ``` ```js posthtml: { options: { use: [ require('posthtml-doctype')({ doctype: 'HTML 5' }), require('posthtml-include')({ root: './', encoding: 'utf-8' }) ] }, build: { files: [ { dot: true, cwd: 'html/', src: ['*.html'], dest: 'tmp/', expand: true, } ] } } ``` ### [Webpack](https://webpack.js.org) ```bash npm i -D html-loader posthtml-loader ``` #### v1.x **webpack.config.js** ```js const config = { module: { loaders: [ { test: /\.html$/, loader: 'html!posthtml' } ] }, posthtml: (ctx) => ({ parser: require('posthtml-pug'), plugins: [ require('posthtml-bem')() ] }) } export default config ``` #### v2.x **webpack.config.js** ```js import { LoaderOptionsPlugin } from 'webpack' const config = { module: { rules: [ { test: /\.html$/, use: [ { loader: 'html-loader', options: { minimize: true } }, { loader: 'posthtml-loader' } ] } ] }, plugins: [ new LoaderOptionsPlugin({ options: { posthtml(ctx) { return { parser: require('posthtml-pug'), plugins: [ require('posthtml-bem')() ] } } } }) ] } export default config ``` ### [Rollup](https://rollupjs.org/) ```bash $ npm i rollup-plugin-posthtml -D # or $ npm i rollup-plugin-posthtml-template -D ``` ```js import { join } from 'path'; import posthtml from 'rollup-plugin-posthtml-template'; // or // import posthtml from 'rollup-plugin-posthtml'; import sugarml from 'posthtml-sugarml'; // npm i posthtml-sugarml -D import include from 'posthtml-include'; // npm i posthtml-include -D export default { entry: join(__dirname, 'main.js'), dest: join(__dirname, 'bundle.js'), format: 'iife', plugins: [ posthtml({ parser: sugarml(), plugins: [include()], template: true // only rollup-plugin-posthtml-template }) ] }; ``` ## Parser ```js import pug from 'posthtml-pug' posthtml().process(html, { parser: pug(options) }).then((result) => result.html) ``` | Name |Status|Description| |:-----|:-----|:----------| |[posthtml-pug][pug]|[![npm][pug-badge]][pug-npm]|Pug Parser| |[sugarml][sugar]|[![npm][sugar-badge]][sugar-npm]|SugarML Parser| [pug]: https://github.com/posthtml/posthtml-pug [pug-badge]: https://img.shields.io/npm/v/posthtml-pug.svg [pug-npm]: https://npmjs.com/package/posthtml-pug [sugar]: https://github.com/posthtml/sugarml [sugar-badge]: https://img.shields.io/npm/v/sugarml.svg [sugar-npm]: https://npmjs.com/package/sugarml ## [Plugins](http://maltsev.github.io/posthtml-plugins) In case you want to develop your own plugin, we recommend using [posthtml-plugin-boilerplate][plugin] to get started. [plugin]: https://github.com/posthtml/posthtml-plugin-boilerplate #### TEXT | Name |Status|Description| |:-----|:-----|:----------| |[posthtml-md][md]|[![npm][md-badge]][md-npm]|Easily use context-sensitive markdown within HTML| |[posthtml-toc][toc]|[![npm][toc-badge]][toc-npm]|Table of contents| |[posthtml-lorem][lorem]|[![npm][lorem-badge]][lorem-npm]|Add lorem ipsum placeholder text to any document| |[posthtml-retext][text]|[![npm][text-badge]][text-npm]|Extensible system for analysing and manipulating natural language| |[prevent-widows][prevent-widows]|[![npm][prevent-widows-badge]][prevent-widows-npm]|Prevent widows from appearing at the end of paragraphs| |[posthtml-richtypo][richtypo]|[![npm][richtypo-badge]][richtypo-npm]|Process HTML node text with Richtypo| [md]: https://github.com/jonathantneal/posthtml-md [md-badge]: https://img.shields.io/npm/v/posthtml-md.svg [md-npm]: https://npmjs.com/package/posthtml-md [toc]: https://github.com/posthtml/posthtml-toc [toc-badge]: https://img.shields.io/npm/v/posthtml-toc.svg [toc-npm]: https://npmjs.com/package/posthtml-toc [text]: https://github.com/voischev/posthtml-retext [text-badge]: https://img.shields.io/npm/v/posthtml-retext.svg [text-npm]: https://npmjs.com/package/posthtml-retext [lorem]: https://github.com/jonathantneal/posthtml-lorem [lorem-badge]: https://img.shields.io/npm/v/posthtml-lorem.svg [lorem-npm]: https://npmjs.com/package/posthtml-lorem [prevent-widows]: https://github.com/bashaus/prevent-widows [prevent-widows-badge]: https://img.shields.io/npm/v/prevent-widows.svg [prevent-widows-npm]: https://npmjs.com/package/prevent-widows [richtypo]: https://github.com/Grawl/posthtml-richtypo [richtypo-badge]: https://img.shields.io/npm/v/posthtml-richtypo.svg [richtypo-npm]: https://npmjs.com/package/posthtml-richtypo #### HTML |Name|Status|Description| |:---|:----:|:----------| |[posthtml-doctype][doctype]|[![npm][doctype-badge]][doctype-npm]|Set !DOCTYPE| |[posthtml-head-elements][head]|[![npm][head-badge]][head-npm]|Include head elements from JSON file| |[posthtml-include][include]|[![npm][include-badge]][include-npm]|Include HTML| |[posthtml-modules][modules]|[![npm][modules-badge]][modules-npm]|Include and process HTML| |[posthtml-extend][extend]|[![npm][extend-badge]][extend-npm]|Extend Layout (Pug-like)| |[posthtml-extend-attrs][attrs]|[![npm][attrs-badge]][attrs-npm]|Extend Attrs| |[posthtml-expressions][exp]|[![npm][exp-badge]][exp-npm]|Template Expressions| |[posthtml-inline-assets][assets]|[![npm][assets-badge]][assets-npm]|Inline external scripts, styles, and images| |[posthtml-static-react][react]|[![npm][react-badge]][react-npm]| Render custom elements as static React components| |[posthtml-custom-elements][elem]|[![npm][elem-badge]][elem-npm]|Use custom elements| |[posthtml-web-component][web]|[![npm][web-badge]][web-npm]|Web Component server-side rendering, Component as a Service (CaaS)| |[posthtml-spaceless][spaceless]|[![npm][spaceless-badge]][spaceless-npm]|Remove whitespace between HTML tags| |[posthtml-cache][cache]|[![npm][cache-badge]][cache-npm]|Add a nanoid to links in your tags| |[posthtml-highlight][highlight]|[![npm][highlight-badge]][highlight-npm]|Syntax highlight code elements| |[posthtml-pseudo][pseudo]|[![npm][pseudo-badge]][pseudo-npm]|Add pseudo selector class names to elements| |[posthtml-noopener][noopener]|[![npm][noopener-badge]][noopener-npm]|Add rel="noopener noreferrer" to links that open in new tab| |[posthtml-noscript][noscript]|[![npm][noscript-badge]][noscript-npm]|Insert noscript content when JavaScript is disabled| |[posthtml-hash][hash]|[![npm][hash-badge]][hash-npm]|Hash static CSS/JS assets| |[posthtml-insert-at][insert-at]|[![npm][insert-at-badge]][insert-at-npm]|Append/prepend HTML to a selector| |[posthtml-plugin-remove-duplicates][plugin-remove-duplicates]|[![npm][plugin-remove-duplicates-badge]][plugin-remove-duplicates-npm]|Remove duplicated tags| |[posthtml-plugin-link-preload][plugin-link-preload]|[![npm][plugin-link-preload-badge]][plugin-link-preload-npm]|Add preload/prefetch tags (or return equivalent headers)| |[posthtml-prism][prism]|[![npm][prism-badge]][prism-npm]|Code syntax highlighting with Prism| |[posthtml-url-parameters][url-parameters]|[![npm][url-parameters-badge]][url-parameters-npm]|Add parameters to URLs| |[posthtml-safe-class-names][safe-class-names]|[![npm][safe-class-names-badge]][safe-class-names-npm]|Replace escaped characters in class names and CSS selectors| |[posthtml-fetch][fetch]|[![npm][fetch-badge]][fetch-npm]|Fetch and render remote content| |[posthtml-mso][mso]|[![npm][mso-badge]][mso-npm]|Makes it easy to write Outlook conditionals in HTML emails| |[posthtml-postcss-merge-longhand][longhand]|[![npm][longhand-badge]][longhand-npm]|Merge longhand inline CSS into shorthand| |[posthtml-markdownit][markdownit]|[![npm][markdownit-badge]][markdownit-npm]|Transform Markdown using markdown-it| |[posthtml-extra-attributes][extra-attributes]|[![npm][extra-attributes-badge]][extra-attributes-npm]|Add new attributes to elements in your HTML| [cache]: https://github.com/posthtml/posthtml-cache [cache-badge]: https://img.shields.io/npm/v/posthtml-cache.svg [cache-npm]: https://npmjs.com/package/posthtml-cache [spaceless]: https://github.com/posthtml/posthtml-spaceless [spaceless-badge]: https://img.shields.io/npm/v/posthtml-spaceless.svg [spaceless-npm]: https://npmjs.com/package/posthtml-spaceless [doctype]: https://github.com/posthtml/posthtml-doctype [doctype-badge]: https://img.shields.io/npm/v/posthtml-doctype.svg [doctype-npm]: https://npmjs.com/package/posthtml-doctype [head]: https://github.com/TCotton/posthtml-head-elements [head-badge]: https://img.shields.io/npm/v/posthtml-head-elements.svg [head-npm]: https://npmjs.com/package/posthtml-head-elements [include]: https://github.com/posthtml/posthtml-include [include-badge]: https://img.shields.io/npm/v/posthtml-include.svg [include-npm]: https://npmjs.com/package/posthtml-include [modules]: https://github.com/posthtml/posthtml-modules [modules-badge]: https://img.shields.io/npm/v/posthtml-modules.svg [modules-npm]: https://npmjs.com/package/posthtml-modules [content]: https://github.com/posthtml/posthtml-content [content-badge]: https://img.shields.io/npm/v/posthtml-content.svg [content-npm]: https://npmjs.com/package/posthtml-content [exp]: https://github.com/posthtml/posthtml-exp [exp-badge]: https://img.shields.io/npm/v/posthtml-exp.svg [exp-npm]: https://npmjs.com/package/posthtml-exp [extend]: https://github.com/posthtml/posthtml-extend [extend-badge]: https://img.shields.io/npm/v/posthtml-extend.svg [extend-npm]: https://npmjs.com/package/posthtml-extend [attrs]: https://github.com/theprotein/posthtml-extend-attrs [attrs-badge]: https://img.shields.io/npm/v/posthtml-extend-attrs.svg [attrs-npm]: https://npmjs.com/package/posthtml-extend-attrs [assets]: https://github.com/jonathantneal/posthtml-inline-assets [assets-badge]: https://img.shields.io/npm/v/posthtml-inline-assets.svg [assets-npm]: https://npmjs.com/package/posthtml-inline-assets [elem]: https://github.com/posthtml/posthtml-custom-elements [elem-badge]: https://img.shields.io/npm/v/posthtml-custom-elements.svg [elem-npm]: https://npmjs.com/package/posthtml-custom-elements [web]: https://github.com/island205/posthtml-web-component [web-badge]: https://img.shields.io/npm/v/posthtml-web-component.svg [web-npm]: https://npmjs.com/package/posthtml-web-components [prefix]: https://github.com/stevenbenisek/posthtml-prefix-class [prefix-badge]: https://img.shields.io/npm/v/posthtml-prefix-class.svg [prefix-npm]: https://npmjs.com/package/posthtml-prefix-class [react]: https://github.com/rasmusfl0e/posthtml-static-react [react-badge]: https://img.shields.io/npm/v/posthtml-static-react.svg [react-npm]: https://npmjs.com/package/posthtml-static-react [highlight]: https://github.com/caseyWebb/posthtml-highlight [highlight-badge]: https://img.shields.io/npm/v/posthtml-highlight.svg [highlight-npm]: https://npmjs.com/package/posthtml-highlight [pseudo]: https://github.com/kevinkace/posthtml-pseudo [pseudo-badge]: https://img.shields.io/npm/v/posthtml-pseudo.svg [pseudo-npm]: https://npmjs.com/package/posthtml-pseudo [noopener]: https://github.com/posthtml/posthtml-noopener [noopener-badge]: https://img.shields.io/npm/v/posthtml-noopener.svg [noopener-npm]: https://npmjs.com/package/posthtml-noopener [noscript]: https://github.com/posthtml/posthtml-noscript [noscript-badge]: https://img.shields.io/npm/v/posthtml-noscript.svg [noscript-npm]: https://npmjs.com/package/posthtml-noscript [hash]: https://github.com/posthtml/posthtml-hash [hash-badge]: https://img.shields.io/npm/v/posthtml-hash.svg [hash-npm]: https://npmjs.com/package/posthtml-hash [insert-at]: https://github.com/posthtml/posthtml-insert-at [insert-at-badge]: https://img.shields.io/npm/v/posthtml-insert-at.svg [insert-at-npm]: https://npmjs.com/package/posthtml-insert-at [plugin-remove-duplicates]: https://github.com/sithmel/posthtml-plugin-remove-duplicates [plugin-remove-duplicates-badge]: https://img.shields.io/npm/v/posthtml-plugin-remove-duplicates.svg [plugin-remove-duplicates-npm]: https://npmjs.com/package/posthtml-plugin-remove-duplicates [plugin-link-preload]: https://github.com/sithmel/posthtml-plugin-link-preload [plugin-link-preload-badge]: https://img.shields.io/npm/v/posthtml-plugin-link-preload.svg [plugin-link-preload-npm]: https://npmjs.com/package/posthtml-plugin-link-preload [prism]: https://github.com/posthtml/posthtml-prism [prism-badge]: https://img.shields.io/npm/v/posthtml-prism.svg [prism-npm]: https://npmjs.com/package/posthtml-prism [url-parameters]: https://github.com/posthtml/posthtml-url-parameters [url-parameters-badge]: https://img.shields.io/npm/v/posthtml-url-parameters.svg [url-parameters-npm]: https://npmjs.com/package/posthtml-url-parameters [safe-class-names]: https://github.com/posthtml/posthtml-safe-class-names [safe-class-names-badge]: https://img.shields.io/npm/v/posthtml-safe-class-names.svg [safe-class-names-npm]: https://npmjs.com/package/posthtml-safe-class-names [fetch]: https://github.com/posthtml/posthtml-fetch [fetch-badge]: https://img.shields.io/npm/v/posthtml-fetch.svg [fetch-npm]: https://npmjs.com/package/posthtml-fetch [mso]: https://github.com/posthtml/posthtml-mso [mso-badge]: https://img.shields.io/npm/v/posthtml-mso.svg [mso-npm]: https://npmjs.com/package/posthtml-mso [longhand]: https://github.com/posthtml/posthtml-postcss-merge-longhand [longhand-badge]: https://img.shields.io/npm/v/posthtml-postcss-merge-longhand.svg [longhand-npm]: https://npmjs.com/package/posthtml-postcss-merge-longhand [markdownit]: https://github.com/posthtml/posthtml-markdownit [markdownit-badge]: https://img.shields.io/npm/v/posthtml-markdownit.svg [markdownit-npm]: https://npmjs.com/package/posthtml-markdownit [extra-attributes]: https://github.com/posthtml/posthtml-extra-attributes [extra-attributes-badge]: https://img.shields.io/npm/v/posthtml-extra-attributes.svg [extra-attributes-npm]: https://npmjs.com/package/posthtml-extra-attributes #### CSS |Name|Status|Description| |:---|:-----|:----------| |[posthtml-bem][bem]|[![npm][bem-badge]][bem-npm]|Support BEM naming in html structure| |[posthtml-postcss][css]|[![npm][css-badge]][css-npm]|Use [PostCSS][css-gh] in HTML document| |[posthtml-px2rem][px2rem]|[![npm][px2rem-badge]][px2rem-npm]|Change px to rem in Inline CSS| |[posthtml-css-modules][css-modules]|[![npm][css-modules-badge]][css-modules-npm]|Use CSS modules in HTML| |[posthtml-postcss-modules][postcss-modules]|[![npm][postcss-modules-badge]][postcss-modules-npm]|CSS Modules in html| |[posthtml-classes][classes]|[![npm][classes-badge]][classes-npm]|Get a list of classes from HTML| |[posthtml-prefix-class][prefix]|[![npm][prefix-badge]][prefix-npm]|Prefix class names |[posthtml-modular-css][modular]|[![npm][modular-badge]][modular-npm]|Make CSS modular| |[posthtml-inline-css][in]|[![npm][in-badge]][in-npm]|CSS Inliner| |[posthtml-collect-styles][collect-styles]|[![npm][collect-styles-badge]][collect-styles-npm]|Collect styles from html and put it in the head| |[posthtml-collect-inline-styles][collect]|[![npm][collect-badge]][collect-npm]|Collect inline styles and insert to head tag| |[posthtml-style-expantion][style-expantion]|[![npm][style-expantion-badge]][style-expantion-npm]| PostHTML plugin expand link rel="stylesheet".| |[posthtml-style-to-file][style]|[![npm][style-badge]][style-npm]| Save HTML style nodes and attributes to CSS file| |[posthtml-color-shorthand-hex-to-six-digit][hex]|[![npm][hex-badge]][hex-npm]|Enforce all hex color codes to be 6-char long| |[posthtml-minify-classnames][minify]|[![npm][minify-badge]][minify-npm]|Rewrites classnames and ids inside of html and css files to reduce file size.| [bem]: https://github.com/rajdee/posthtml-bem [bem-badge]: https://img.shields.io/npm/v/posthtml-bem.svg [bem-npm]: https://npmjs.com/package/posthtml-bem [css]: https://github.com/posthtml/posthtml-postcss [css-badge]: https://img.shields.io/npm/v/posthtml-postcss.svg [css-npm]: https://npmjs.com/package/posthtml-postcss [css-gh]: https://github.com/postcss/postcss [postcss-modules]: https://github.com/posthtml/posthtml-postcss-modules [postcss-modules-badge]: https://img.shields.io/npm/v/posthtml-postcss-modules.svg [postcss-modules-npm]: https://npmjs.com/package/posthtml-postcss-modules [css-modules]: https://github.com/posthtml/posthtml-css-modules [css-modules-badge]: https://img.shields.io/npm/v/posthtml-css-modules.svg [css-modules-npm]: https://npmjs.com/package/posthtml-css-modules [collect-styles]: https://github.com/posthtml/posthtml-collect-styles [collect-styles-badge]: https://img.shields.io/npm/v/posthtml-collect-styles.svg [collect-styles-npm]: https://npmjs.com/package/posthtml-collect-styles [collect]: https://github.com/totora0155/posthtml-collect-inline-styles [collect-badge]: https://img.shields.io/npm/v/posthtml-collect-inline-styles.svg [collect-npm]: https://npmjs.com/package/posthtml-collect-inline-styles [px2rem]: https://github.com/weixin/posthtml-px2rem [px2rem-badge]: https://img.shields.io/npm/v/posthtml-px2rem.svg [px2rem-npm]: https://npmjs.com/package/posthtml-px2rem [classes]: https://github.com/rajdee/posthtml-classes [classes-badge]: https://img.shields.io/npm/v/posthtml-classes.svg [classes-npm]: https://npmjs.com/package/posthtml-classes [prefix]: https://github.com/stevenbenisek/posthtml-prefix-class [prefix-badge]: https://img.shields.io/npm/v/posthtml-prefix-class.svg [prefix-npm]: https://npmjs.com/package/posthtml-prefix-class [modular]: https://github.com/admdh/posthtml-modular-css [modular-badge]: https://img.shields.io/npm/v/posthtml-modular-css.svg [modular-npm]: https://npmjs.com/package/posthtml-modular-css [in]: https://github.com/posthtml/posthtml-inline-css [in-badge]: https://img.shields.io/npm/v/posthtml-inline-css.svg [in-npm]: https://npmjs.com/package/posthtml-inline-css [style-expantion]: https://github.com/renyamizuno/posthtml-style-expantion [style-expantion-badge]: https://img.shields.io/npm/v/posthtml-style-expansion.svg [style-expantion-npm]: https://npmjs.com/package/posthtml-style-expansion [style]: https://github.com/posthtml/posthtml-style-to-file [style-badge]: https://img.shields.io/npm/v/posthtml-style-to-file.svg [style-npm]: https://npmjs.com/package/posthtml-style-to-file [hex]: https://github.com/posthtml/posthtml-color-shorthand-hex-to-six-digit [hex-badge]: https://img.shields.io/npm/v/posthtml-color-shorthand-hex-to-six-digit.svg [hex-npm]: https://npmjs.com/package/posthtml-color-shorthand-hex-to-six-digit [minify]: https://github.com/simonlc/posthtml-minify-classnames [minify-badge]: https://img.shields.io/npm/v/posthtml-minify-classnames.svg [minify-npm]: https://npmjs.com/package/posthtml-minify-classnames #### IMG & SVG |Name|Status|Description| |:---|:-----|:----------| |[posthtml-img-autosize][img]|[![npm][img-badge]][img-npm]|Auto setting the width and height of \<img\>| |[posthtml-to-svg-tags][svg]|[![npm][svg-badge]][svg-npm]|Convert html tags to svg equivalents| |[posthtml-webp][webp]|[![npm][webp-badge]][webp-npm]|Add WebP support for images| |[posthtml-favicons][favicons]|[![npm][favicons-badge]][favicons-npm]|Generate Favicons and add related tags| |[posthtml-inline-svg][inline-svg]|[![npm][inline-svg-badge]][inline-svg-npm]|Inline svg icons in HTML| |[posthtml-inline-favicon][inline-favicon]|[![npm][inline-favicon-badge]][inline-svg-npm]|Inline favicons in HTML| [img]: https://github.com/posthtml/posthtml-img-autosize [img-badge]: https://img.shields.io/npm/v/posthtml-img-autosize.svg [img-npm]: https://npmjs.com/package/posthtml-img-autosize [svg]: https://github.com/theprotein/posthtml-to-svg-tags [svg-badge]: https://img.shields.io/npm/v/posthtml-to-svg-tags.svg [svg-npm]: https://npmjs.com/package/posthtml-to-svg-tags [webp]: https://github.com/posthtml/posthtml-webp [webp-badge]: https://img.shields.io/npm/v/posthtml-webp.svg [webp-npm]: https://npmjs.com/package/posthtml-webp [favicons]: https://github.com/mohsen1/posthtml-favicons [favicons-badge]: https://img.shields.io/npm/v/posthtml-favicons.svg [favicons-npm]: https://www.npmjs.com/package/posthtml-favicons [inline-svg]: https://github.com/andrey-hohlov/posthtml-inline-svg [inline-svg-badge]: https://img.shields.io/npm/v/posthtml-inline-svg.svg [inline-svg-npm]: https://www.npmjs.com/package/posthtml-inline-svg [inline-favicon]: https://github.com/posthtml/posthtml-inline-favicon [inline-favicon-badge]: https://img.shields.io/npm/v/posthtml-inline-favicon.svg [inline-favicon-npm]: https://www.npmjs.com/package/posthtml-inline-favicon #### Accessibility |Name|Status|Description| |:---|:-----|:----------| |[posthtml-aria-tabs][aria]|[![npm][aria-badge]][aria-npm]|Write accessible tabs with minimal markup| |[posthtml-alt-always][alt]|[![npm][alt-badge]][alt-npm]|Always add alt attribute for images that don't have it| |[posthtml-schemas][schemas]|[![npm][schemas-badge]][schemas-npm]| Add microdata to your HTML| [alt]: https://github.com/ismamz/posthtml-alt-always [alt-badge]: https://img.shields.io/npm/v/posthtml-alt-always.svg [alt-npm]: https://npmjs.com/package/posthtml-alt-always [aria]: https://github.com/jonathantneal/posthtml-aria-tabs [aria-badge]: https://img.shields.io/npm/v/posthtml-aria-tabs.svg [aria-npm]: https://npmjs.com/package/posthtml-aria-tabs [schemas]: https://github.com/jonathantneal/posthtml-schemas [schemas-badge]: https://img.shields.io/npm/v/posthtml-schemas.svg [schemas-npm]: https://npmjs.com/package/posthtml-schemas #### Optimization |Name|Status|Description| |:---|:-----|:----------| |[posthtml-shorten][shorten]|[![npm][shorten-badge]][shorten-npm]|Shorten URLs in HTML| |[posthtml-uglify][uglify]|[![npm][uglify-badge]][uglify-npm]|Shorten CSS in HTML| |[posthtml-minifier][minifier]|[![npm][minifier-badge]][minifier-npm]|Minify HTML| |[posthtml-remove-attributes][remove]|[![npm][remove-badge]][remove-npm]|Remove attributes unconditionally or with content match| |[posthtml-remove-tags][remove-tags]|[![npm][remove-tags-badge]][remove-tags-npm]|Remove tags with content match| |[posthtml-remove-duplicates][remove-duplicates]|[![npm][remove-duplicates-badge]][remove-duplicates-npm]|Remove duplicate elements from your html| |[posthtml-transformer][transform]|[![npm][transform-badge]][transform-npm]|Process HTML by directives in node attrs, such as inline scripts and styles, remove useless tags, concat scripts and styles etc.| |[htmlnano][nano]|[![npm][nano-badge]][nano-npm]|HTML Minifier| |[posthtml-link-noreferrer][noreferrer]|[![npm][noreferrer-badge]][noreferrer-npm]|Add `rel="noopener"` and `rel="noreferrer"` to all links that contain the attribute `target="_blank"` | |[posthtml-lazyload][lazyload]|[![npm][lazyload-badge]][lazyload-npm]|Add native lazyload attribute| |[posthtml-postcss-treeshaker][posthtml-postcss-treeshaker]|[![npm][posthtml-postcss-treeshaker-badge]][posthtml-postcss-treeshaker-npm]|Tree shake styles for classes and ids in `style` tag| [remove]: https://github.com/princed/posthtml-remove-attributes [remove-badge]: https://img.shields.io/npm/v/posthtml-remove-attributes.svg [remove-npm]: https://npmjs.com/package/posthtml-remove-attributes [remove-tags]: https://github.com/posthtml/posthtml-remove-tags [remove-tags-badge]: https://img.shields.io/npm/v/posthtml-remove-tags.svg [remove-tags-npm]: https://npmjs.com/package/posthtml-remove-tags [remove-duplicates]: https://github.com/canvaskisa/posthtml-remove-duplicates [remove-duplicates-badge]: https://img.shields.io/npm/v/posthtml-remove-duplicates.svg [remove-duplicates-npm]: https://npmjs.com/package/posthtml-remove-duplicates [minifier]: https://github.com/Rebelmail/posthtml-minifier [minifier-badge]: https://img.shields.io/npm/v/posthtml-minifier.svg [minifier-npm]: https://npmjs.com/package/posthtml-minifier [shorten]: https://github.com/Rebelmail/posthtml-shorten [shorten-badge]: https://img.shields.io/npm/v/posthtml-shorten.svg [shorten-npm]: https://npmjs.com/package/posthtml-shorten [uglify]: https://github.com/Rebelmail/posthtml-uglify [uglify-badge]: https://img.shields.io/npm/v/posthtml-uglify.svg [uglify-npm]: https://npmjs.com/package/posthtml-uglify [nano]: https://github.com/maltsev/htmlnano [nano-badge]: https://img.shields.io/npm/v/htmlnano.svg [nano-npm]: https://npmjs.com/package/htmlnano [transform]: https://github.com/flashlizi/posthtml-transformer [transform-badge]: https://img.shields.io/npm/v/posthtml-transformer.svg [transform-npm]: https://npmjs.com/package/posthtml-transformer [noreferrer]: https://github.com/webistomin/posthtml-link-noreferrer [noreferrer-badge]: https://img.shields.io/npm/v/posthtml-link-noreferrer.svg [noreferrer-npm]: https://www.npmjs.com/package/posthtml-link-noreferrer [lazyload]: https://github.com/webistomin/posthtml-lazyload [lazyload-badge]: https://img.shields.io/npm/v/posthtml-link-noreferrer.svg [lazyload-npm]: https://www.npmjs.com/package/posthtml-lazyload [posthtml-postcss-treeshaker]: https://github.com/anikethsaha/posthtml-postcss-treeshaker [posthtml-postcss-treeshaker-badge]: https://img.shields.io/npm/v/posthtml-postcss-treeshaker.svg [posthtml-postcss-treeshaker-npm]: https://img.shields.io/npm/v/posthtml-postcss-treeshaker.svg #### Workflow |Name|Status|Description| |:---|:-----|:----------| |[posthtml-load-plugins][plugins]|[![npm][plugins-badge]][plugins-npm]|Autoload Plugins |[posthtml-load-options][options]|[![npm][options-badge]][options-npm]|Autoload Options (Parser && Render)| |[posthtml-load-config][config]|[![npm][config-badge]][config-npm]|Autoload Config (Plugins && Options)| |[posthtml-w3c][w3c]|[![npm][w3c-badge]][w3c-npm]|Validate HTML with W3C Validation| |[posthtml-hint][hint]|[![npm][hint-badge]][hint-npm]|Lint HTML with HTML Hint| |[posthtml-tidy][tidy]|[![npm][tidy-badge]][tidy-npm]|Sanitize HTML with HTML Tidy| [options]: https://github.com/posthtml/posthtml-load-options [options-badge]: https://img.shields.io/npm/v/posthtml-load-options.svg [options-npm]: https://npmjs.com/package/posthtml-load-options [plugins]: https://github.com/posthtml/posthtml-load-plugins [plugins-badge]: https://img.shields.io/npm/v/posthtml-load-plugins.svg [plugins-npm]: https://npmjs.com/package/posthtml-load-plugins [config]: https://github.com/posthtml/posthtml-load-config [config-badge]: https://img.shields.io/npm/v/posthtml-load-config.svg [config-npm]: https://npmjs.com/package/posthtml-load-config [tidy]: https://github.com/michael-ciniawsky/posthtml-tidy [tidy-badge]: https://img.shields.io/npm/v/posthtml-tidy.svg [tidy-npm]: https://npmjs.com/package/posthtml-tidy [hint]: https://github.com/posthtml/posthtml-hint [hint-badge]: https://img.shields.io/npm/v/posthtml-hint.svg [hint-npm]: https://npmjs.com/package/posthtml-hint [w3c]: https://github.com/posthtml/posthtml-w3c [w3c-badge]: https://img.shields.io/npm/v/posthtml-w3c.svg [w3c-npm]: https://npmjs.com/package/posthtml-w3c ## Middleware |Name|Status|Description| |:---|:-----|:----------| |[koa-posthtml][koa]|[![npm][koa-badge]][koa-npm]|Koa Middleware| |[hapi-posthtml][hapi]|[![npm][hapi-badge]][hapi-npm]|Hapi Plugin| |[express-posthtml][express]|[![npm][express-badge]][express-npm]|Express Middleware| |[electron-posthtml][electron]|[![npm][electron-badge]][electron-npm]|Electron Plugin| |[metalsmith-posthtml][metalsmith]|[![npm][metalsmith-badge]][metalsmith-npm]|Metalsmith Plugin| [koa]: https://github.com/posthtml/koa-posthtml [koa-badge]: https://img.shields.io/npm/v/koa-posthtml.svg [koa-npm]: https://npmjs.com/package/koa-posthtml [hapi]: https://github.com/posthtml/hapi-posthtml [hapi-badge]: https://img.shields.io/npm/v/hapi-posthtml.svg [hapi-npm]: https://npmjs.com/package/hapi-posthtml [express]: https://github.com/posthtml/express-posthtml [express-badge]: https://img.shields.io/npm/v/express-posthtml.svg [express-npm]: https://npmjs.com/package/express-posthtml [electron]: https://github.com/posthtml/electron-posthtml [electron-badge]: https://img.shields.io/npm/v/electron-posthtml.svg [electron-npm]: https://npmjs.com/package/electron-posthtml [metalsmith]: https://github.com/posthtml/metalsmith-posthtml [metalsmith-badge]: https://img.shields.io/npm/v/metalsmith-posthtml.svg [metalsmith-npm]: https://npmjs.com/package/metalsmith-posthtml ## Maintainers <table> <tbody> <tr> <td align="center"> <img width="150 height="150" src="https://avatars0.githubusercontent.com/u/2789192?s=460&v=4"> <br /> <a href="https://github.com/scrum">Ivan Demidov</a> </td> <td align="center"> <img width="150 height="150" src="https://avatars.githubusercontent.com/u/1510217?v=3&s=150"> <br /> <a href="https://github.com/voischev">Ivan Voischev</a> </td> </tr> <tbody> </table> ## Contributing See [PostHTML Guidelines](plugins/guide.md) and [CONTRIBUTING](CONTRIBUTING.md). ## Contributors <a href="https://github.com/posthtml/posthtml/graphs/contributors"><img src="https://opencollective.com/posthtml/contributors.svg?width=890&button=false" /></a> ## LICENSE [MIT](LICENSE) [npm]: https://img.shields.io/npm/v/posthtml.svg [npm-url]: https://npmjs.com/package/posthtml [deps]: https://david-dm.org/posthtml/posthtml.svg [deps-url]: https://david-dm.org/posthtml/posthtml [build]: https://travis-ci.org/posthtml/posthtml.svg?branch=master [build-url]: https://travis-ci.org/posthtml/posthtml?branch=master [cover]: https://coveralls.io/repos/posthtml/posthtml/badge.svg?branch=master [cover-url]: https://coveralls.io/r/posthtml/posthtml?branch=master [code-style]: https://img.shields.io/badge/code%20style-standard-yellow.svg [code-style-url]: http://standardjs.com/ [twitter]: https://img.shields.io/badge/twitter-%40PostHTML-00ACEE.svg?style=flat [twitter-url]: https://twitter.com/PostHTML [chat]: https://badges.gitter.im/posthtml/posthtml.svg [chat-url]: https://gitter.im/posthtml/posthtml?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge" [docs-url]: https://github.com/posthtml/posthtml/tree/master/docs # jest-validate Generic configuration validation tool that helps you with warnings, errors and deprecation messages as well as showing users examples of correct configuration. ```bash npm install --save jest-validate ``` ## Usage ```js import {validate} from 'jest-validate'; validate((config: Object), (options: ValidationOptions)); // => {hasDeprecationWarnings: boolean, isValid: boolean} ``` Where `ValidationOptions` are: ```js type ValidationOptions = { blacklist?: Array<string>, comment?: string, condition?: (option: any, validOption: any) => boolean, deprecate?: ( config: Object, option: string, deprecatedOptions: Object, options: ValidationOptions, ) => true, deprecatedConfig?: {[key: string]: Function}, error?: ( option: string, received: any, defaultValue: any, options: ValidationOptions, ) => void, exampleConfig: Object, recursive?: boolean, title?: Title, unknown?: ( config: Object, exampleConfig: Object, option: string, options: ValidationOptions, ) => void, }; type Title = {| deprecation?: string, error?: string, warning?: string, |}; ``` `exampleConfig` is the only option required. ## API By default `jest-validate` will print generic warning and error messages. You can however customize this behavior by providing `options: ValidationOptions` object as a second argument: Almost anything can be overwritten to suite your needs. ### Options - `recursiveBlacklist` – optional array of string keyPaths that should be excluded from deep (recursive) validation. - `comment` – optional string to be rendered below error/warning message. - `condition` – an optional function with validation condition. - `deprecate`, `error`, `unknown` – optional functions responsible for displaying warning and error messages. - `deprecatedConfig` – optional object with deprecated config keys. - `exampleConfig` – the only **required** option with configuration against which you'd like to test. - `recursive` - optional boolean determining whether recursively compare `exampleConfig` to `config` (default: `true`). - `title` – optional object of titles for errors and messages. You will find examples of `condition`, `deprecate`, `error`, `unknown`, and `deprecatedConfig` inside source of this repository, named respectively. ## exampleConfig syntax `exampleConfig` should be an object with key/value pairs that contain an example of a valid value for each key. A configuration value is considered valid when: - it matches the JavaScript type of the example value, e.g. `string`, `number`, `array`, `boolean`, `function`, or `object` - it is `null` or `undefined` - it matches the Javascript type of any of arguments passed to `MultipleValidOptions(...)` The last condition is a special syntax that allows validating where more than one type is permissible; see example below. It's acceptable to have multiple values of the same type in the example, so you can also use this syntax to provide more than one example. When a validation failure occurs, the error message will show all other values in the array as examples. ## Examples Minimal example: ```js validate(config, {exampleConfig}); ``` Example with slight modifications: ```js validate(config, { comment: ' Documentation: http://custom-docs.com', deprecatedConfig, exampleConfig, title: { deprecation: 'Custom Deprecation', // leaving 'error' and 'warning' as default }, }); ``` This will output: #### Warning: ```bash ● Validation Warning: Unknown option transformx with value "<rootDir>/node_modules/babel-jest" was found. This is either a typing error or a user mistake. Fixing it will remove this message. Documentation: http://custom-docs.com ``` #### Error: ```bash ● Validation Error: Option transform must be of type: object but instead received: string Example: { "transform": { "^.+\\.js$": "<rootDir>/preprocessor.js" } } Documentation: http://custom-docs.com ``` ## Example validating multiple types ```js import {multipleValidOptions} from 'jest-validate'; validate(config, { // `bar` will accept either a string or a number bar: multipleValidOptions('string is ok', 2), }); ``` #### Error: ```bash ● Validation Error: Option foo must be of type: string or number but instead received: array Example: { "bar": "string is ok" } or { "bar": 2 } Documentation: http://custom-docs.com ``` #### Deprecation Based on `deprecatedConfig` object with proper deprecation messages. Note custom title: ```bash Custom Deprecation: Option scriptPreprocessor was replaced by transform, which support multiple preprocessors. Jest now treats your current configuration as: { "transform": {".*": "xxx"} } Please update your configuration. Documentation: http://custom-docs.com ``` # 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). # pstree.remy > Cross platform ps-tree (including unix flavours without ps) ## Installation ```shel npm install pstree.remy ``` ## Usage ```js const psTree = psTree require('pstree.remy'); psTree(PID, (err, pids) => { if (err) { console.error(err); } console.log(pids) }); console.log(psTree.hasPS ? "This platform has the ps shell command" : "This platform does not have the ps shell command"); ``` # postcss-normalize-charset Add necessary or remove extra charset with PostCSS ```css a{ content: "©"; } ``` ```css @charset "utf-8"; a{ content: "©"; } ``` ## API ### normalizeCharset([options]) #### options ##### add Type: `boolean` Default: `true` Pass `false` to stop the module from adding a `@charset` declaration if it was missing from the file (and the file contained non-ascii characters). ## Usage See the [PostCSS documentation](https://github.com/postcss/postcss#usage) for examples for your environment. ## Contributors See [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md). ## License MIT © [Bogdan Chadkin](mailto:trysound@yandex.ru) # 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._ Shims used when bundling asc for browser usage. # [postcss][postcss]-normalize-display-values > Normalize display property values with PostCSS. ## Install With [npm](https://npmjs.org/package/postcss-normalize-display-values) do: ``` npm install postcss-normalize-display-values --save ``` ## Example ### Input ```css div { display: inline flow-root } ``` ### Output ```css div { display: inline-block } ``` ## Usage See the [PostCSS documentation](https://github.com/postcss/postcss#usage) for examples for your environment. ## Contributors See [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md). ## License MIT © [Ben Briggs](http://beneb.info) [postcss]: https://github.com/postcss/postcss # 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._ # 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 # 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 messages 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. Generate new types for errors: `node gen_error_types.js` 3. `yarn fix` fix any issues with linter. 4. `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. # 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/become_a_patron_button@2x.png" 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._ # 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._ # RSVP.js [![Build Status](https://secure.travis-ci.org/tildeio/rsvp.js.svg?branch=master)](http://travis-ci.org/tildeio/rsvp.js) [![Inline docs](http://inch-ci.org/github/tildeio/rsvp.js.svg?branch=master)](http://inch-ci.org/github/tildeio/rsvp.js) RSVP.js provides simple tools for organizing asynchronous code. Specifically, it is a tiny implementation of Promises/A+. It works in node and the browser (IE9+, all the popular evergreen ones). ## downloads - rsvp ([latest](https://cdn.jsdelivr.net/npm/rsvp/dist/rsvp.js) | [4.x](https://cdn.jsdelivr.net/npm/rsvp@4/dist/rsvp.js)) - rsvp minified ([latest](https://cdn.jsdelivr.net/npm/rsvp/dist/rsvp.min.js) | [4.x](https://cdn.jsdelivr.net/npm/rsvp@4/dist/rsvp.min.js)) ## CDN ```html <script src="https://cdn.jsdelivr.net/npm/rsvp@4/dist/rsvp.min.js"></script> ``` ## Promises Although RSVP is ES6 compliant, it does bring along some extra toys. If you would prefer a strict ES6 subset, I would suggest checking out our sibling project https://github.com/stefanpenner/es6-promise, It is RSVP but stripped down to the ES6 spec features. ## Node ```sh yarn add --save rsvp # or ... npm install --save rsvp ``` `RSVP.Promise` is an implementation of [Promises/A+](http://promises-aplus.github.com/promises-spec/) that passes the [test suite](https://github.com/promises-aplus/promises-tests). It delivers all promises asynchronously, even if the value is already available, to help you write consistent code that doesn't change if the underlying data provider changes from synchronous to asynchronous. It is compatible with [TaskJS](https://github.com/mozilla/task.js), a library by Dave Herman of Mozilla that uses ES6 generators to allow you to write synchronous code with promises. It currently works in Firefox, and will work in any browser that adds support for ES6 generators. See the section below on TaskJS for more information. ### Basic Usage ```javascript var RSVP = require('rsvp'); var promise = new RSVP.Promise(function(resolve, reject) { // succeed resolve(value); // or reject reject(error); }); promise.then(function(value) { // success }).catch(function(error) { // failure }); ``` Once a promise has been resolved or rejected, it cannot be resolved or rejected again. Here is an example of a simple XHR2 wrapper written using RSVP.js: ```javascript var getJSON = function(url) { var promise = new RSVP.Promise(function(resolve, reject){ var client = new XMLHttpRequest(); client.open("GET", url); client.onreadystatechange = handler; client.responseType = "json"; client.setRequestHeader("Accept", "application/json"); client.send(); function handler() { if (this.readyState === this.DONE) { if (this.status === 200) { resolve(this.response); } else { reject(this); } } }; }); return promise; }; getJSON("/posts.json").then(function(json) { // continue }).catch(function(error) { // handle errors }); ``` ### Chaining One of the really awesome features of Promises/A+ promises are that they can be chained together. In other words, the return value of the first resolve handler will be passed to the second resolve handler. If you return a regular value, it will be passed, as is, to the next handler. ```javascript getJSON("/posts.json").then(function(json) { return json.post; }).then(function(post) { // proceed }); ``` The really awesome part comes when you return a promise from the first handler: ```javascript getJSON("/post/1.json").then(function(post) { // save off post return getJSON(post.commentURL); }).then(function(comments) { // proceed with access to post and comments }); ``` This allows you to flatten out nested callbacks, and is the main feature of promises that prevents "rightward drift" in programs with a lot of asynchronous code. Errors also propagate: ```javascript getJSON("/posts.json").then(function(posts) { }).catch(function(error) { // since no rejection handler was passed to the // first `.then`, the error propagates. }); ``` You can use this to emulate `try/catch` logic in synchronous code. Simply chain as many resolve callbacks as you want, and add a failure handler at the end to catch errors. ```javascript getJSON("/post/1.json").then(function(post) { return getJSON(post.commentURL); }).then(function(comments) { // proceed with access to posts and comments }).catch(function(error) { // handle errors in either of the two requests }); ``` ## Error Handling There are times when dealing with promises that it seems like any errors are being 'swallowed', and not properly raised. This makes it extremely difficult to track down where a given issue is coming from. Thankfully, `RSVP` has a solution for this problem built in. You can register functions to be called when an uncaught error occurs within your promises. These callback functions can be anything, but a common practice is to call `console.assert` to dump the error to the console. ```javascript RSVP.on('error', function(reason) { console.assert(false, reason); }); ``` `RSVP` allows Promises to be labeled: `Promise.resolve(value, 'I AM A LABEL')` If provided, this label is passed as the second argument to `RSVP.on('error')` ```javascript RSVP.on('error', function(reason, label) { if (label) { console.error(label); } console.assert(false, reason); }); ``` **NOTE:** promises do allow for errors to be handled asynchronously, so this callback may result in false positives. ## Finally `finally` will be invoked regardless of the promise's fate, just as native try/catch/finally behaves. ```js findAuthor().catch(function(reason){ return findOtherAuthor(); }).finally(function(){ // author was either found, or not }); ``` ## Arrays of promises Sometimes you might want to work with many promises at once. If you pass an array of promises to the `all()` method it will return a new promise that will be fulfilled when all of the promises in the array have been fulfilled; or rejected immediately if any promise in the array is rejected. ```javascript var promises = [2, 3, 5, 7, 11, 13].map(function(id){ return getJSON("/post/" + id + ".json"); }); RSVP.all(promises).then(function(posts) { // posts contains an array of results for the given promises }).catch(function(reason){ // if any of the promises fails. }); ``` ## Hash of promises If you need to reference many promises at once (like `all()`), but would like to avoid encoding the actual promise order you can use `hash()`. If you pass an object literal (where the values are promises) to the `hash()` method it will return a new promise that will be fulfilled when all of the promises have been fulfilled; or rejected immediately if any promise is rejected. The key difference to the `all()` function is that both the fulfillment value and the argument to the `hash()` function are object literals. This allows you to simply reference the results directly off the returned object without having to remember the initial order like you would with `all()`. ```javascript var promises = { posts: getJSON("/posts.json"), users: getJSON("/users.json") }; RSVP.hash(promises).then(function(results) { console.log(results.users) // print the users.json results console.log(results.posts) // print the posts.json results }); ``` ## All settled and hash settled Sometimes you want to work with several promises at once, but instead of rejecting immediately if any promise is rejected, as with `all()` or `hash()`, you want to be able to inspect the results of all your promises, whether they fulfill or reject. For this purpose, you can use `allSettled()` and `hashSettled()`. These work exactly like `all()` and `hash()`, except that they fulfill with an array or hash (respectively) of the constituent promises' result states. Each state object will either indicate fulfillment or rejection, and provide the corresponding value or reason. The states will take one of the following formats: ```javascript { state: 'fulfilled', value: value } or { state: 'rejected', reason: reason } ``` ## Deferred > The `RSVP.Promise` constructor is generally a better, less error-prone choice > than `RSVP.defer()`. Promises are recommended unless the specific > properties of deferred are needed. Sometimes one needs to create a deferred object, without immediately specifying how it will be resolved. These deferred objects are essentially a wrapper around a promise, whilst providing late access to the `resolve()` and `reject()` methods. A deferred object has this form: `{ promise, resolve(x), reject(r) }`. ```javascript var deferred = RSVP.defer(); // ... deferred.promise // access the promise // ... deferred.resolve(); ``` ## TaskJS The [TaskJS](https://github.com/mozilla/task.js) library makes it possible to take promises-oriented code and make it synchronous using ES6 generators. Let's review an earlier example: ```javascript getJSON("/post/1.json").then(function(post) { return getJSON(post.commentURL); }).then(function(comments) { // proceed with access to posts and comments }).catch(function(reason) { // handle errors in either of the two requests }); ``` Without any changes to the implementation of `getJSON`, you could write the following code with TaskJS: ```javascript spawn(function *() { try { var post = yield getJSON("/post/1.json"); var comments = yield getJSON(post.commentURL); } catch(error) { // handle errors } }); ``` In the above example, `function *` is new syntax in ES6 for [generators](http://wiki.ecmascript.org/doku.php?id=harmony:generators). Inside a generator, `yield` pauses the generator, returning control to the function that invoked the generator. In this case, the invoker is a special function that understands the semantics of Promises/A, and will automatically resume the generator as soon as the promise is resolved. The cool thing here is the same promises that work with current JavaScript using `.then` will work seamlessly with TaskJS once a browser has implemented it! ## Instrumentation ```js function listener (event) { event.guid // guid of promise. Must be globally unique, not just within the implementation event.childGuid // child of child promise (for chained via `then`) event.eventName // one of ['created', 'chained', 'fulfilled', 'rejected'] event.detail // fulfillment value or rejection reason, if applicable event.label // label passed to promise's constructor event.timeStamp // milliseconds elapsed since 1 January 1970 00:00:00 UTC up until now event.stack // stack at the time of the event. (if 'instrument-with-stack' is true) } RSVP.configure('instrument', true | false); // capturing the stacks is slow, so you also have to opt in RSVP.configure('instrument-with-stack', true | false); // events RSVP.on('created', listener); RSVP.on('chained', listener); RSVP.on('fulfilled', listener); RSVP.on('rejected', listener); ``` Events are only triggered when `RSVP.configure('instrument')` is true, although listeners can be registered at any time. ## Building & Testing Custom tasks: * `npm test` - build & test * `npm test:node` - build & test just node * `npm test:server` - build/watch & test * `npm run build` - Build * `npm run build:production` - Build production (with minified output) * `npm start` - build, watch and run interactive server at http://localhost:4200' ## Releasing Check what release-it will do by running `npm run-script dry-run-release`. To actually release, run `node_modules/.bin/release-it`. # 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. forever-agent ============= HTTP Agent that keeps socket connections alive between keep-alive requests. Formerly part of mikeal/request, now a standalone module. # 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._ # 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. # get-package-type [![NPM Version][npm-image]][npm-url] Determine the `package.json#type` which applies to a location. ## Usage ```js const getPackageType = require('get-package-type'); (async () => { console.log(await getPackageType('file.js')); console.log(getPackageType.sync('file.js')); })(); ``` This function does not validate the value found in `package.json#type`. Any truthy value found will be returned. Non-truthy values will be reported as `commonjs`. The argument must be a filename. ```js // This never looks at `dir1/`, first attempts to load `./package.json`. const type1 = await getPackageType('dir1/'); // This attempts to load `dir1/package.json`. const type2 = await getPackageType('dir1/index.cjs'); ``` The extension of the filename does not effect the result. The primary use case for this module is to determine if `myapp.config.js` should be loaded with `require` or `import`. [npm-image]: https://img.shields.io/npm/v/get-package-type.svg [npm-url]: https://npmjs.org/package/get-package-type # 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. Renders a DOM node or an array of DOM nodes to a string. # 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`/`es2019` 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` ## Security Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. [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 # 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._ # 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._ # 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._ # 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._ # 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. # jest-changed-files A module used internally by Jest to check which files have changed since you last committed in git or hg. ## Install ```sh $ npm install --save jest-changed-files ``` ## API ### `getChangedFilesForRoots(roots: <Array<string>>, options: ?object): Promise<?object>` Get the list of files and repos that have changed since the last commit. #### Parameters roots: Array of string paths gathered from [jest roots](https://jestjs.io/docs/configuration.html#roots-array-string). options: Object literal with keys - lastCommit: boolean - withAncestor: boolean ### findRepos(roots: <Array<string>>): Promise<?object> Get a set of git and hg repositories. #### Parameters roots: Array of string paths gathered from [jest roots](https://jestjs.io/docs/configuration.html#roots-array-string). ## Usage ```javascript import {getChangedFilesForRoots} from 'jest-changed-files'; getChangedFilesForRoots(['/path/to/test'], { lastCommit: true, withAncestor: true, }).then(files => { /* { repos: [], changedFiles: [] } */ }); ``` ```javascript import {findRepos} from 'jest-changed-files'; findRepos(['/path/to/test']).then(repos => { /* { git: Set<Path>, hg: Set<Path> } */ }); ``` # 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][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. ### 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`. <!-- 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 ### 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, no-undef, no-unused-vars --> ```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`. <!-- 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) [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 # 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._ # 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). 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> 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. # 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**. [![NPM](https://nodei.co/npm/readdirp.png)](https://www.npmjs.com/package/readdirp) ```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. 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.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. 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 # 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. # 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. # 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._ # 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 # 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 # 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._ 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 `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')` # 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 # 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) > A neat wrapper around Node.js fs.watch / fs.watchFile / FSEvents. [![NPM](https://nodei.co/npm/chokidar.png)](https://www.npmjs.com/package/chokidar) 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/) ## 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. 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. ## 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 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. Use with `await` to ensure bugs don't happen. * `.close()`: **async** Removes all listeners from watched files. Asynchronous, returns Promise. * `.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 fsevents@n.n.n` * 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.4 (Apr 26, 2020):** Support for directory-based symlinks. Macos file replacement fixes. - **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. # Shellwords Shellwords provides functions to manipulate strings according to the word parsing rules of the UNIX Bourne shell. It is based on [the Ruby module of the same name](http://www.ruby-doc.org/stdlib-1.9.3/libdoc/shellwords/rdoc/Shellwords.html). ## Installation Add "shellwords" to your `package.json` file and run `npm install`. ## Example ``` javascript var shellwords = require("shellwords"); shellwords.split("foo 'bar baz'"); // ["foo", "bar baz"] shellwords.escape("What's up, yo?"); // 'What\\\'s\\ up,\\ yo\\?' ``` # 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 }); } ``` # 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._ # exit [![Build Status](https://secure.travis-ci.org/cowboy/node-exit.png?branch=master)](http://travis-ci.org/cowboy/node-exit) A replacement for process.exit that ensures stdio are fully drained before exiting. To make a long story short, if `process.exit` is called on Windows, script output is often truncated when pipe-redirecting `stdout` or `stderr`. This module attempts to work around this issue by waiting until those streams have been completely drained before actually calling `process.exit`. See [Node.js issue #3584](https://github.com/joyent/node/issues/3584) for further reference. Tested in OS X 10.8, Windows 7 on Node.js 0.8.25 and 0.10.18. Based on some code by [@vladikoff](https://github.com/vladikoff). ## Getting Started Install the module with: `npm install exit` ```javascript var exit = require('exit'); // These lines should appear in the output, EVEN ON WINDOWS. console.log("omg"); console.error("yay"); // process.exit(5); exit(5); // These lines shouldn't appear in the output. console.log("wtf"); console.error("bro"); ``` ## Don't believe me? Try it for yourself. In Windows, clone the repo and cd to the `test\fixtures` directory. The only difference between [log.js](test/fixtures/log.js) and [log-broken.js](test/fixtures/log-broken.js) is that the former uses `exit` while the latter calls `process.exit` directly. This test was done using cmd.exe, but you can see the same results using `| grep "std"` in either PowerShell or git-bash. ``` C:\node-exit\test\fixtures>node log.js 0 10 stdout stderr 2>&1 | find "std" stdout 0 stderr 0 stdout 1 stderr 1 stdout 2 stderr 2 stdout 3 stderr 3 stdout 4 stderr 4 stdout 5 stderr 5 stdout 6 stderr 6 stdout 7 stderr 7 stdout 8 stderr 8 stdout 9 stderr 9 C:\node-exit\test\fixtures>node log-broken.js 0 10 stdout stderr 2>&1 | find "std" C:\node-exit\test\fixtures> ``` ## 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 2013-11-26 - v0.1.2 - Fixed a bug with hanging processes. 2013-09-26 - v0.1.1 - Fixed some bugs. It seems to actually work now! 2013-09-20 - v0.1.0 - Initial release. ## License Copyright (c) 2013 "Cowboy" Ben Alman Licensed under the MIT license. # saxes A sax-style non-validating parser for XML. Saxes is a fork of [sax](https://github.com/isaacs/sax-js) 1.2.4. All mentions of sax in this project's documentation are references to sax 1.2.4. Designed with [node](http://nodejs.org/) in mind, but should work fine in the browser or other CommonJS implementations. Saxes does not support Node versions older than 8. ## Notable Differences from Sax. * Saxes aims to be much stricter than sax with regards to XML well-formedness. Sax, even in its so-called "strict mode", is not strict. It silently accepts structures that are not well-formed XML. Projects that need better compliance with well-formedness constraints cannot use sax as-is. Saxes aims for conformance with [XML 1.0 fifth edition](https://www.w3.org/TR/2008/REC-xml-20081126/) and [XML Namespaces 1.0 third edition](http://www.w3.org/TR/2009/REC-xml-names-20091208/). Consequently, saxes does not support HTML, or pseudo-XML, or bad XML. * Saxes is much much faster than sax, mostly because of a substantial redesign of the internal parsing logic. The speed improvement is not merely due to removing features that were supported by sax. That helped a bit, but saxes adds some expensive checks in its aim for conformance with the XML specification. Redesigning the parsing logic is what accounts for most of the performance improvement. * Saxes does not aim to support antiquated platforms. We will not pollute the source or the default build with support for antiquated platforms. If you want support for IE 11, you are welcome to produce a PR that adds a *new build* transpiled to ES5. * Saxes handles errors differently from sax: it provides a default onerror handler which throws. You can replace it with your own handler if you want. If your handler does nothing, there is no `resume` method to call. * There's no `Stream` API. A revamped API may be introduced later. (It is still a "streaming parser" in the general sense that you write a character stream to it.) * Saxes does not have facilities for limiting the size the data chunks passed to event handlers. See the FAQ entry for more details. ## Limitations This is a non-validating parser so it only verifies whether the document is well-formed. We do aim to raise errors for all malformed constructs encountered. However, this parser does not parse the contents of DTDs. So malformedness errors caused by errors in DTDs cannot be reported. Also, the parser continues to parse even upon encountering errors, and does its best to continue reporting errors. You should heed all errors reported. **HOWEVER, ONCE AN ERROR HAS BEEN ENCOUNTERED YOU CANNOT RELY ON THE DATA PROVIDED THROUGH THE OTHER EVENT HANDLERS.** After an error, saxes tries to make sense of your document, but it may interpret it incorrectly. For instance ``<foo a=bc="d"/>`` is invalid XML. Did you mean to have ``<foo a="bc=d"/>`` or ``<foo a="b" c="d"/>`` or some other variation? Saxes takes an honest stab at figuring out your mangled XML. That's as good as it gets. ## 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. ## Documentation The source code contains JSDOC comments. Use them. **PAY CLOSE ATTENTION TO WHAT IS PUBLIC AND WHAT IS PRIVATE.** The elements of code that do not have JSDOC documentation, or have documentation with the ``@private`` tag, are private. If you use anything private, that's at your own peril. If there's a mistake in the documentation, raise an issue. If you just assume, you may assume incorrectly. ## Summary Usage Information ### Example ```javascript var saxes = require("./lib/saxes"), parser = new saxes.SaxesParser(); 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.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(); ``` ### Constructor Arguments Pass the following arguments to the parser function. All are optional. `opt` - Object bag of settings regarding string formatting. Settings supported: * `xmlns` - Boolean. If `true`, then namespaces are supported. Default is `false`. * `position` - Boolean. If `false`, then don't track line/col/position. Unset is treated as `true`. Default is unset. * `fileName` - String. Set a file name for error reporting. This is useful only when tracking positions. You may leave it unset, in which case the file name in error messages will be `undefined`. * `fragment` - Boolean. If `true`, parse the XML as an XML fragment. Default is `false`. * `additionalNamespaces` - A plain object whose key, value pairs define namespaces known before parsing the XML file. It is not legal to pass bindings for the namespaces `"xml"` or `"xmlns"`. ### 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. ### Properties The parser has the following properties: `line`, `column`, `position` - Indications of the position in the XML document where the parser currently is looking. `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. `opt` - Any options passed into the constructor. `xmlDecl` - The XML declaration for this document. It contains the fields `version`, `encoding` and `standalone`. They are all `undefined` before encountering the XML declaration. If they are undefined after the XML declaration, the corresponding value was not set by the declaration. There is no event associated with the XML declaration. In a well-formed document, the XML declaration may be preceded only by an optional BOM. So by the time any event generated by the parser happens, the declaration has been processed if present at all. Otherwise, you have a malformed document, and as stated above, you cannot rely on the parser data! ### Events To listen to an event, override `on<eventname>`. The list of supported events are also in the exported `EVENTS` array. See the JSDOC comments in the source code for a description of each supported event. ### Parsing XML Fragments The XML specification does not define any method by which to parse XML fragments. However, there are usage scenarios in which it is desirable to parse fragments. In order to allow this, saxes provides three initialization options. If you pass the option `fragment: true` to the parser constructor, the parser will expect an XML fragment. It essentially starts with a parsing state equivalent to the one it would be in if `parser.write("<foo">)` had been called right after initialization. In other words, it expects content which is acceptable inside an element. This also turns off well-formedness checks that are inappropriate when parsing a fragment. The option `additionalNamespaces` allows you to define additional prefix-to-URI bindings known before parsing starts. You would use this over `resolvePrefix` if you have at the ready a series of namespaces bindings to use. The option `resolvePrefix` allows you to pass a function which saxes will use if it is unable to resolve a namespace prefix by itself. You would use this over `additionalNamespaces` in a context where getting a complete list of defined namespaces is onerous. Note that you can use `additionalNamespaces` and `resolvePrefix` together if you want. `additionalNamespaces` applies before `resolvePrefix`. ## FAQ Q. Why has saxes dropped support for limiting the size of data chunks passed to event handlers? A. With sax you could set ``MAX_BUFFER_LENGTH`` to cause the parser to limit the size of data chunks passed to event handlers. So if you ran into a span of text above the limit, multiple ``text`` events with smaller data chunks were fired instead of a single event with a large chunk. However, that functionality had some problematic characteristics. It had an arbitrary default value. It was library-wide so all parsers created from a single instance of the ``sax`` library shared it. This could potentially cause conflicts among libraries running in the same VM but using sax for different purposes. These issues could have been easily fixed, but there were larger issues. The buffer limit arbitrarily applied to some events but not others. It would split ``text``, ``cdata`` and ``script`` events. However, if a ``comment``, ``doctype``, ``attribute`` or ``processing instruction`` were more than the limit, the parser would generate an error and you were left picking up the pieces. It was not intuitive to use. You'd think setting the limit to 1K would prevent chunks bigger than 1K to be passed to event handlers. But that was not the case. A comment in the source code told you that you might go over the limit if you passed large chunks to ``write``. So if you want a 1K limit, don't pass 64K chunks to ``write``. Fair enough. You know what limit you want so you can control the size of the data you pass to ``write``. So you limit the chunks to ``write`` to 1K at a time. Even if you do this, your event handlers may get data chunks that are 2K in size. Suppose on the previous ``write`` the parser has just finished processing an open tag, so it is ready for text. Your ``write`` passes 1K of text. You are not above the limit yet, so no event is generated yet. The next ``write`` passes another 1K of text. It so happens that sax checks buffer limits only once per ``write``, after the chunk of data has been processed. Now you've hit the limit and you get a ``text`` event with 2K of data. So even if you limit your ``write`` calls to the buffer limit you've set, you may still get events with chunks at twice the buffer size limit you've specified. We may consider reinstating an equivalent functionality, provided that it addresses the issues above and does not cause a huge performance drop for use-case scenarios that don't need it. # abab [![npm version](https://badge.fury.io/js/abab.svg)](https://www.npmjs.com/package/abab) [![Build Status](https://travis-ci.org/jsdom/abab.svg?branch=master)](https://travis-ci.org/jsdom/abab) A JavaScript module that implements `window.atob` and `window.btoa` according the forgiving-base64 algorithm in the [Infra Standard](https://infra.spec.whatwg.org/#forgiving-base64). The original code was forked from [w3c/web-platform-tests](https://github.com/w3c/web-platform-tests/blob/master/html/webappapis/atob/base64.html). Compatibility: Node.js version 3+ and all major browsers. Install with `npm`: ```sh npm install abab ``` ## API ### `btoa` (base64 encode) ```js const { btoa } = require('abab'); btoa('Hello, world!'); // 'SGVsbG8sIHdvcmxkIQ==' ``` ### `atob` (base64 decode) ```js const { atob } = require('abab'); atob('SGVsbG8sIHdvcmxkIQ=='); // 'Hello, world!' ``` #### Valid characters [Per the spec](https://html.spec.whatwg.org/multipage/webappapis.html#atob:dom-windowbase64-btoa-3), `btoa` will accept strings "containing only characters in the range `U+0000` to `U+00FF`." If passed a string with characters above `U+00FF`, `btoa` will return `null`. If `atob` is passed a string that is not base64-valid, it will also return `null`. In both cases when `null` is returned, the spec calls for throwing a `DOMException` of type `InvalidCharacterError`. ## Browsers If you want to include just one of the methods to save bytes in your client-side code, you can `require` the desired module directly. ```js const atob = require('abab/lib/atob'); const btoa = require('abab/lib/btoa'); ``` ## Development If you're **submitting a PR** or **deploying to npm**, please use the [checklists in CONTRIBUTING.md](CONTRIBUTING.md#checklists). ## Remembering what `atob` and `btoa` stand for Base64 comes from IETF [RFC 4648](https://tools.ietf.org/html/rfc4648#section-4) (2006). - **`btoa`**, the encoder function, stands for **binary** to **ASCII**, meaning it converts any binary input into a subset of **ASCII** (Base64). - **`atob`**, the decoder function, converts **ASCII** (or Base64) to its original **binary** format. [![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) ## Work in progress --- ### WebAssembly fixed length big numbers written on [AssemblyScript](https://github.com/AssemblyScript/assemblyscript) 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_ # NEAR CLI (command line interface) [![Build Status](https://travis-ci.com/near/near-cli.svg?branch=master)](https://travis-ci.com/near/near-cli) [![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 generate secure keys, connect to the NEAR platform and send transactions to the network on your behalf. > note that **Node.js version 10+** is required to run NEAR CLI ## Installation ```bash npm install -g near-cli ``` ## Usage In command line, from the directory with your project: ```bash near <command> ``` ### Commands #### For account: ```bash near login # logging in through NEAR protocol wallet near create-account <accountId> # create a developer account with --masterAccount (required), publicKey and initialBalance near state <accountId> # view account state near keys <accountId> # view account public keys near send <sender> <receiver> <amount> # send tokens to given receiver near stake <accountId> <stakingKey> <amount> # create staking transaction (stakingKey is base58 encoded) near delete <accountId> <beneficiaryId> # delete an account and transfer funds to beneficiary account near delete-key [accessKey] # delete access key ``` #### For smart contract: ```bash near deploy [accountId] [wasmFile] [initFunction] [initArgs] [initGas] [initDeposit] # deploy your smart contract near dev-deploy [wasmFile] # deploy your smart contract using temporary account (TestNet only) near call <contractName> <methodName> [args] # schedule smart contract call which can modify state near view <contractName> <methodName> [args] # make smart contract call which can view state near clean # clean the smart contract build locally (remove ./out ) ``` #### For transactions: ```bash near tx-status <hash> # lookup transaction status by hash ``` #### For validators: ```bash near validators <epoch> # lookup validating nodes by epoch(or "current", "next") near proposals # lookup current proposals ``` #### REPL: ``` near repl ``` Launch interactive Node.js shell with NEAR connection available to use. The repl's initial context contains `nearAPI`, `near`and `account` if an accountId cli argument is provided. To load a script into the repl use `.load script.js`. ##### Usage example: ``` near repl --acountId bob > console.log(account) > .load script.js ``` #### Misc: ```bash near repl # launch interactive Node.js shell with NEAR connection available to use near generate-key <account-id> # generate key locally (Note: this does not create another access key automatically) ``` ### Options | Option | Description | Type | Default | | --------------------------|:----------------------------------------------| :---------|:----------------------| | --help | Show help | [boolean] | | | --version | Show version number | [boolean] | | | --nodeUrl | NEAR node URL | [string] |"http://localhost:3030"| | --networkId | NEAR network ID for different keys by network | [string] |"default" | | --helperUrl | NEAR contract helper URL | [string] | | | --keyPath | Path to master account key | [string] | | | --accountId | Unique identifier for the account | [string] [required]| | | --masterAccount | Account used to create requested account. | [string] [required]| | | --publicKey | Public key to initialize the account with | [string] [required]| | | --initialBalance | Number of tokens to transfer to newly account | [string] [required]| | ## 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. # clone [![build status](https://secure.travis-ci.org/pvorb/clone.svg)](http://travis-ci.org/pvorb/clone) [![downloads](https://img.shields.io/npm/dt/clone.svg)](http://npm-stat.com/charts.html?package=clone) offers foolproof _deep cloning_ of objects, arrays, numbers, strings, maps, sets, promises, etc. in JavaScript. **XSS vulnerability detected** ## Installation npm install clone (It also works with browserify, ender or standalone. You may want to use the option `noParse` in browserify to reduce the resulting file size, since usually `Buffer`s are not needed in browsers.) ## Example ~~~ javascript var clone = require('clone'); var a, b; a = { foo: { bar: 'baz' } }; // initial value of a b = clone(a); // clone a -> b a.foo.bar = 'foo'; // change a console.log(a); // show a console.log(b); // show b ~~~ This will print: ~~~ javascript { foo: { bar: 'foo' } } { foo: { bar: 'baz' } } ~~~ **clone** masters cloning simple objects (even with custom prototype), arrays, Date objects, and RegExp objects. Everything is cloned recursively, so that you can clone dates in arrays in objects, for example. ## API `clone(val, circular, depth)` * `val` -- the value that you want to clone, any type allowed * `circular` -- boolean Call `clone` with `circular` set to `false` if you are certain that `obj` contains no circular references. This will give better performance if needed. There is no error if `undefined` or `null` is passed as `obj`. * `depth` -- depth to which the object is to be cloned (optional, defaults to infinity) * `prototype` -- sets the prototype to be used when cloning an object. (optional, defaults to parent prototype). * `includeNonEnumerable` -- set to `true` if the non-enumerable properties should be cloned as well. Non-enumerable properties on the prototype chain will be ignored. (optional, defaults to `false`) `clone.clonePrototype(obj)` * `obj` -- the object that you want to clone Does a prototype clone as [described by Oran Looney](http://oranlooney.com/functional-javascript/). ## Circular References ~~~ javascript var a, b; a = { hello: 'world' }; a.myself = a; b = clone(a); console.log(b); ~~~ This will print: ~~~ javascript { hello: "world", myself: [Circular] } ~~~ So, `b.myself` points to `b`, not `a`. Neat! ## Test npm test ## Changelog ### v2.1.2 #### 2018-03-21 - Use `Buffer.allocUnsafe()` on Node >= 4.5.0 (contributed by @ChALkeR) ### v2.1.1 #### 2017-03-09 - Fix build badge in README - Add support for cloning Maps and Sets on Internet Explorer ### v2.1.0 #### 2016-11-22 - Add support for cloning Errors - Exclude non-enumerable symbol-named object properties from cloning - Add option to include non-enumerable own properties of objects ### v2.0.0 #### 2016-09-28 - Add support for cloning ES6 Maps, Sets, Promises, and Symbols ### v1.0.3 #### 2017-11-08 - Close XSS vulnerability in the NPM package, which included the file `test-apart-ctx.html`. This vulnerability was disclosed by Juho Nurminen of 2NS - Second Nature Security. ### v1.0.2 (deprecated) #### 2015-03-25 - Fix call on getRegExpFlags - Refactor utilities - Refactor test suite ### v1.0.1 (deprecated) #### 2015-03-04 - Fix nodeunit version - Directly call getRegExpFlags ### v1.0.0 (deprecated) #### 2015-02-10 - Improve browser support - Improve browser testability - Move helper methods to private namespace ## Caveat Some special objects like a socket or `process.stdout`/`stderr` are known to not be cloneable. If you find other objects that cannot be cloned, please [open an issue](https://github.com/pvorb/clone/issues/new). ## Bugs and Issues If you encounter any bugs or issues, feel free to [open an issue at github](https://github.com/pvorb/clone/issues) or send me an email to <paul@vorba.ch>. I also always like to hear from you, if you’re using my code. ## License Copyright © 2011-2016 [Paul Vorbach](https://paul.vorba.ch/) and [contributors](https://github.com/pvorb/clone/graphs/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, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 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. 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. # 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](https://evilmartians.com/?utm_source=postcss) at <surrender@evilmartians.com>. [Abstract Syntax Tree]: https://en.wikipedia.org/wiki/Abstract_syntax_tree [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 ### Gulp Use [`gulp-postcss`] and [`gulp-sourcemaps`]. ```js gulp.task('css', function () { var postcss = require('gulp-postcss'); var 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 fs = require('fs'); const postcss = require('postcss'); const precss = require('precss'); const autoprefixer = require('autoprefixer'); 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 ## 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/ # 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. # 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) ``` # 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. 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. 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` <p align="center"> <a href="https://github.com/inikulin/parse5"> <img src="https://raw.github.com/inikulin/parse5/master/media/logo.png" alt="parse5" /> </a> </p> <div align="center"> <h1>parse5</h1> <i><b>HTML parser and serializer.</b></i> </div> <br> <div align="center"> <code>npm install --save parse5</code> </div> <br> <p align="center"> 📖 <a href="https://github.com/inikulin/parse5/tree/master/packages/parse5/docs/index.md"><b>Documentation</b></a> 📖 </p> --- <p align="center"> <a href="https://github.com/inikulin/parse5/tree/master/docs/list-of-packages.md">List of parse5 toolset packages</a> </p> <p align="center"> <a href="https://github.com/inikulin/parse5">GitHub</a> </p> <p align="center"> <a href="http://astexplorer.net/#/1CHlCXc4n4">Online playground</a> </p> <p align="center"> <a href="https://github.com/inikulin/parse5/tree/master/docs/version-history.md">Version history</a> </p> <h1 align="center"> <img width="100" height="100" src="logo.svg" alt=""><br> jsdom </h1> jsdom is a pure-JavaScript implementation of many web standards, notably the WHATWG [DOM](https://dom.spec.whatwg.org/) and [HTML](https://html.spec.whatwg.org/multipage/) Standards, for use with Node.js. In general, the goal of the project is to emulate enough of a subset of a web browser to be useful for testing and scraping real-world web applications. The latest versions of jsdom require Node.js v8 or newer. (Versions of jsdom below v12 still work with Node.js v6, but are unsupported.) ## Basic usage ```js const jsdom = require("jsdom"); const { JSDOM } = jsdom; ``` To use jsdom, you will primarily use the `JSDOM` constructor, which is a named export of the jsdom main module. Pass the constructor a string. You will get back a `JSDOM` object, which has a number of useful properties, notably `window`: ```js const dom = new JSDOM(`<!DOCTYPE html><p>Hello world</p>`); console.log(dom.window.document.querySelector("p").textContent); // "Hello world" ``` (Note that jsdom will parse the HTML you pass it just like a browser does, including implied `<html>`, `<head>`, and `<body>` tags.) The resulting object is an instance of the `JSDOM` class, which contains a number of useful properties and methods besides `window`. In general, it can be used to act on the jsdom from the "outside," doing things that are not possible with the normal DOM APIs. For simple cases, where you don't need any of this functionality, we recommend a coding pattern like ```js const { window } = new JSDOM(`...`); // or even const { document } = (new JSDOM(`...`)).window; ``` Full documentation on everything you can do with the `JSDOM` class is below, in the section "`JSDOM` Object API". _Important note: in the default configuration, JavaScript globals like `window.Date` or `window.Map` will not exist. Read the "Executing scripts" section below for more._ ## Customizing jsdom The `JSDOM` constructor accepts a second parameter which can be used to customize your jsdom in the following ways. ### Simple options ```js const dom = new JSDOM(``, { url: "https://example.org/", referrer: "https://example.com/", contentType: "text/html", includeNodeLocations: true, storageQuota: 10000000 }); ``` - `url` sets the value returned by `window.location`, `document.URL`, and `document.documentURI`, and affects things like resolution of relative URLs within the document and the same-origin restrictions and referrer used while fetching subresources. It defaults to `"about:blank"`. - `referrer` just affects the value read from `document.referrer`. It defaults to no referrer (which reflects as the empty string). - `contentType` affects the value read from `document.contentType`, and how the document is parsed: as HTML or as XML. Values that are not `"text/html"` or an [XML mime type](https://html.spec.whatwg.org/multipage/infrastructure.html#xml-mime-type) will throw. It defaults to `"text/html"`. - `includeNodeLocations` preserves the location info produced by the HTML parser, allowing you to retrieve it with the `nodeLocation()` method (described below). It also ensures that line numbers reported in exception stack traces for code running inside `<script>` elements are correct. It defaults to `false` to give the best performance, and cannot be used with an XML content type since our XML parser does not support location info. - `storageQuota` is the maximum size in code units for the separate storage areas used by `localStorage` and `sessionStorage`. Attempts to store data larger than this limit will cause a `DOMException` to be thrown. By default, it is set to 5,000,000 code units per origin, as inspired by the HTML specification. Note that both `url` and `referrer` are canonicalized before they're used, so e.g. if you pass in `"https:example.com"`, jsdom will interpret that as if you had given `"https://example.com/"`. If you pass an unparseable URL, the call will throw. (URLs are parsed and serialized according to the [URL Standard](http://url.spec.whatwg.org/).) ### Executing scripts jsdom's most powerful ability is that it can execute scripts inside the jsdom. These scripts can modify the content of the page and access all the web platform APIs jsdom implements. However, this is also highly dangerous when dealing with untrusted content. The jsdom sandbox is not foolproof, and code running inside the DOM's `<script>`s can, if it tries hard enough, get access to the Node.js environment, and thus to your machine. As such, the ability to execute scripts embedded in the HTML is disabled by default: ```js const dom = new JSDOM(`<body> <script>document.body.appendChild(document.createElement("hr"));</script> </body>`); // The script will not be executed, by default: dom.window.document.body.children.length === 1; ``` To enable executing scripts inside the page, you can use the `runScripts: "dangerously"` option: ```js const dom = new JSDOM(`<body> <script>document.body.appendChild(document.createElement("hr"));</script> </body>`, { runScripts: "dangerously" }); // The script will be executed and modify the DOM: dom.window.document.body.children.length === 2; ``` Again we emphasize to only use this when feeding jsdom code you know is safe. If you use it on arbitrary user-supplied code, or code from the Internet, you are effectively running untrusted Node.js code, and your machine could be compromised. If you want to execute _external_ scripts, included via `<script src="">`, you'll also need to ensure that they load them. To do this, add the option `resources: "usable"` [as described below](#loading-subresources). Note that event handler attributes, like `<div onclick="">`, will also not function unless `runScripts` is set to `"dangerously"`. (However, event handler _properties_, like `div.onclick = ...`, will function regardless of `runScripts`.) If you are simply trying to execute script "from the outside", instead of letting `<script>` elements (and inline event handlers) run "from the inside", you can use the `runScripts: "outside-only"` option, which enables all the JavaScript spec-provided globals to be installed on `window`. This includes things like `window.Array`, `window.Promise`, etc. It also, notably, includes `window.eval`, which allows running scripts, but with the jsdom `window` as the global: ```js const window = (new JSDOM(``, { runScripts: "outside-only" })).window; window.eval(`document.body.innerHTML = "<p>Hello, world!</p>";`); window.document.body.children.length === 1; ``` This is turned off by default for performance reasons, but is safe to enable. Note that we strongly advise against trying to "execute scripts" by mashing together the jsdom and Node global environments (e.g. by doing `global.window = dom.window`), and then executing scripts or test code inside the Node global environment. Instead, you should treat jsdom like you would a browser, and run all scripts and tests that need access to a DOM inside the jsdom environment, using `window.eval` or `runScripts: "dangerously"`. This might require, for example, creating a browserify bundle to execute as a `<script>` element—just like you would in a browser. Finally, for advanced use cases you can use the `dom.runVMScript(script)` method, documented below. ### Pretending to be a visual browser jsdom does not have the capability to render visual content, and will act like a headless browser by default. It provides hints to web pages through APIs such as `document.hidden` that their content is not visible. When the `pretendToBeVisual` option is set to `true`, jsdom will pretend that it is rendering and displaying content. It does this by: * Changing `document.hidden` to return `false` instead of `true` * Changing `document.visibilityState` to return `"visible"` instead of `"prerender"` * Enabling `window.requestAnimationFrame()` and `window.cancelAnimationFrame()` methods, which otherwise do not exist ```js const window = (new JSDOM(``, { pretendToBeVisual: true })).window; window.requestAnimationFrame(timestamp => { console.log(timestamp > 0); }); ``` Note that jsdom still [does not do any layout or rendering](#unimplemented-parts-of-the-web-platform), so this is really just about _pretending_ to be visual, not about implementing the parts of the platform a real, visual web browser would implement. ### Loading subresources #### Basic options By default, jsdom will not load any subresources such as scripts, stylesheets, images, or iframes. If you'd like jsdom to load such resources, you can pass the `resources: "usable"` option, which will load all usable resources. Those are: * Frames and iframes, via `<frame>` and `<iframe>` * Stylesheets, via `<link rel="stylesheet">` * Scripts, via `<script>`, but only if `runScripts: "dangerously"` is also set * Images, via `<img>`, but only if the `canvas` npm package is also installed (see "[Canvas Support](#canvas-support)" below) #### Advanced configuration _This resource loader system is new as of jsdom v12.0.0, and we'd love your feedback on whether it meets your needs and how easy it is to use. Please file an issue to discuss!_ To more fully customize jsdom's resource-loading behavior, you can pass an instance of the `ResourceLoader` class as the `resources` option value: ```js const resourceLoader = new jsdom.ResourceLoader({ proxy: "http://127.0.0.1:9001", strictSSL: false, userAgent: "Mellblomenator/9000", }); const dom = new JSDOM(``, { resources: resourceLoader }); ``` The three options to the `ResourceLoader` constructor are: - `proxy` is the address of an HTTP proxy to be used. - `strictSSL` can be set to false to disable the requirement that SSL certificates be valid. - `userAgent` affects the `User-Agent` header sent, and thus the resulting value for `navigator.userAgent`. It defaults to <code>\`Mozilla/5.0 (${process.platform || "unknown OS"}) AppleWebKit/537.36 (KHTML, like Gecko) jsdom/${jsdomVersion}\`</code>. You can further customize resource fetching by subclassing `ResourceLoader` and overriding the `fetch()` method. For example, here is a version that only returns results for requests to a trusted origin: ```js class CustomResourceLoader extends jsdom.ResourceLoader { fetch(url, options) { // Override the contents of this script to do something unusual. if (url === "https://example.com/some-specific-script.js") { return Promise.resolve(Buffer.from("window.someGlobal = 5;")); } return super.fetch(url, options); } } ``` jsdom will call your custom resource loader's `fetch()` method whenever it encounters a "usable" resource, per the above section. The method takes a URL string, as well as a few options which you should pass through unmodified if calling `super.fetch()`. It must return a promise for a Node.js `Buffer` object, or return `null` if the resource is intentionally not to be loaded. In general, most cases will want to delegate to `super.fetch()`, as shown. One of the options you will receive in `fetch()` will be the element (if applicable) that is fetching a resource. ```js class CustomResourceLoader extends jsdom.ResourceLoader { fetch(url, options) { if (options.element) { console.log(`Element ${options.element.localName} is requesting the url ${url}`); } return super.fetch(url, options); } } ``` ### Virtual consoles Like web browsers, jsdom has the concept of a "console". This records both information directly sent from the page, via scripts executing inside the document, as well as information from the jsdom implementation itself. We call the user-controllable console a "virtual console", to distinguish it from the Node.js `console` API and from the inside-the-page `window.console` API. By default, the `JSDOM` constructor will return an instance with a virtual console that forwards all its output to the Node.js console. To create your own virtual console and pass it to jsdom, you can override this default by doing ```js const virtualConsole = new jsdom.VirtualConsole(); const dom = new JSDOM(``, { virtualConsole }); ``` Code like this will create a virtual console with no behavior. You can give it behavior by adding event listeners for all the possible console methods: ```js virtualConsole.on("error", () => { ... }); virtualConsole.on("warn", () => { ... }); virtualConsole.on("info", () => { ... }); virtualConsole.on("dir", () => { ... }); // ... etc. See https://console.spec.whatwg.org/#logging ``` (Note that it is probably best to set up these event listeners *before* calling `new JSDOM()`, since errors or console-invoking script might occur during parsing.) If you simply want to redirect the virtual console output to another console, like the default Node.js one, you can do ```js virtualConsole.sendTo(console); ``` There is also a special event, `"jsdomError"`, which will fire with error objects to report errors from jsdom itself. This is similar to how error messages often show up in web browser consoles, even if they are not initiated by `console.error`. So far, the following errors are output this way: - Errors loading or parsing subresources (scripts, stylesheets, frames, and iframes) - Script execution errors that are not handled by a window `onerror` event handler that returns `true` or calls `event.preventDefault()` - Not-implemented errors resulting from calls to methods, like `window.alert`, which jsdom does not implement, but installs anyway for web compatibility If you're using `sendTo(c)` to send errors to `c`, by default it will call `c.error(errorStack[, errorDetail])` with information from `"jsdomError"` events. If you'd prefer to maintain a strict one-to-one mapping of events to method calls, and perhaps handle `"jsdomError"`s yourself, then you can do ```js virtualConsole.sendTo(c, { omitJSDOMErrors: true }); ``` ### Cookie jars Like web browsers, jsdom has the concept of a cookie jar, storing HTTP cookies. Cookies that have a URL on the same domain as the document, and are not marked HTTP-only, are accessible via the `document.cookie` API. Additionally, all cookies in the cookie jar will impact the fetching of subresources. By default, the `JSDOM` constructor will return an instance with an empty cookie jar. To create your own cookie jar and pass it to jsdom, you can override this default by doing ```js const cookieJar = new jsdom.CookieJar(store, options); const dom = new JSDOM(``, { cookieJar }); ``` This is mostly useful if you want to share the same cookie jar among multiple jsdoms, or prime the cookie jar with certain values ahead of time. Cookie jars are provided by the [tough-cookie](https://www.npmjs.com/package/tough-cookie) package. The `jsdom.CookieJar` constructor is a subclass of the tough-cookie cookie jar which by default sets the `looseMode: true` option, since that [matches better how browsers behave](https://github.com/whatwg/html/issues/804). If you want to use tough-cookie's utilities and classes yourself, you can use the `jsdom.toughCookie` module export to get access to the tough-cookie module instance packaged with jsdom. ### Intervening before parsing jsdom allows you to intervene in the creation of a jsdom very early: after the `Window` and `Document` objects are created, but before any HTML is parsed to populate the document with nodes: ```js const dom = new JSDOM(`<p>Hello</p>`, { beforeParse(window) { window.document.childNodes.length === 0; window.someCoolAPI = () => { /* ... */ }; } }); ``` This is especially useful if you are wanting to modify the environment in some way, for example adding shims for web platform APIs jsdom does not support. ## `JSDOM` object API Once you have constructed a `JSDOM` object, it will have the following useful capabilities: ### Properties The property `window` retrieves the `Window` object that was created for you. The properties `virtualConsole` and `cookieJar` reflect the options you pass in, or the defaults created for you if nothing was passed in for those options. ### Serializing the document with `serialize()` The `serialize()` method will return the [HTML serialization](https://html.spec.whatwg.org/#html-fragment-serialisation-algorithm) of the document, including the doctype: ```js const dom = new JSDOM(`<!DOCTYPE html>hello`); dom.serialize() === "<!DOCTYPE html><html><head></head><body>hello</body></html>"; // Contrast with: dom.window.document.documentElement.outerHTML === "<html><head></head><body>hello</body></html>"; ``` ### Getting the source location of a node with `nodeLocation(node)` The `nodeLocation()` method will find where a DOM node is within the source document, returning the [parse5 location info](https://www.npmjs.com/package/parse5#options-locationinfo) for the node: ```js const dom = new JSDOM( `<p>Hello <img src="foo.jpg"> </p>`, { includeNodeLocations: true } ); const document = dom.window.document; const bodyEl = document.body; // implicitly created const pEl = document.querySelector("p"); const textNode = pEl.firstChild; const imgEl = document.querySelector("img"); console.log(dom.nodeLocation(bodyEl)); // null; it's not in the source console.log(dom.nodeLocation(pEl)); // { startOffset: 0, endOffset: 39, startTag: ..., endTag: ... } console.log(dom.nodeLocation(textNode)); // { startOffset: 3, endOffset: 13 } console.log(dom.nodeLocation(imgEl)); // { startOffset: 13, endOffset: 32 } ``` Note that this feature only works if you have set the `includeNodeLocations` option; node locations are off by default for performance reasons. ### Running vm-created scripts with `runVMScript(script[, options])` The built-in `vm` module of Node.js allows you to create `Script` instances, which can be compiled ahead of time and then run multiple times on a given "VM context". Behind the scenes, a jsdom `Window` is indeed a VM context. To get access to this ability, use the `runVMScript()` method: ```js const { Script } = require("vm"); const dom = new JSDOM(``, { runScripts: "outside-only" }); const s = new Script(` if (!this.ran) { this.ran = 0; } ++this.ran; `); dom.runVMScript(s); dom.runVMScript(s); dom.runVMScript(s); dom.window.ran === 3; ``` This is somewhat-advanced functionality, and we advise sticking to normal DOM APIs (such as `window.eval()` or `document.createElement("script")`) unless you have very specific needs. `runVMScript()` also takes an `options` object as its second argument. See the [Node.js docs](https://nodejs.org/api/vm.html#vm_script_runincontext_contextifiedsandbox_options) for details. (This functionality does not work when [using jsdom in a web browser](running-jsdom-inside-a-web-browser).) ### Reconfiguring the jsdom with `reconfigure(settings)` The `top` property on `window` is marked `[Unforgeable]` in the spec, meaning it is a non-configurable own property and thus cannot be overridden or shadowed by normal code running inside the jsdom, even using `Object.defineProperty`. Similarly, at present jsdom does not handle navigation (such as setting `window.location.href = "https://example.com/"`); doing so will cause the virtual console to emit a `"jsdomError"` explaining that this feature is not implemented, and nothing will change: there will be no new `Window` or `Document` object, and the existing `window`'s `location` object will still have all the same property values. However, if you're acting from outside the window, e.g. in some test framework that creates jsdoms, you can override one or both of these using the special `reconfigure()` method: ```js const dom = new JSDOM(); dom.window.top === dom.window; dom.window.location.href === "about:blank"; dom.reconfigure({ windowTop: myFakeTopForTesting, url: "https://example.com/" }); dom.window.top === myFakeTopForTesting; dom.window.location.href === "https://example.com/"; ``` Note that changing the jsdom's URL will impact all APIs that return the current document URL, such as `window.location`, `document.URL`, and `document.documentURI`, as well as the resolution of relative URLs within the document, and the same-origin checks and referrer used while fetching subresources. It will not, however, perform navigation to the contents of that URL; the contents of the DOM will remain unchanged, and no new instances of `Window`, `Document`, etc. will be created. ## Convenience APIs ### `fromURL()` In addition to the `JSDOM` constructor itself, jsdom provides a promise-returning factory method for constructing a jsdom from a URL: ```js JSDOM.fromURL("https://example.com/", options).then(dom => { console.log(dom.serialize()); }); ``` The returned promise will fulfill with a `JSDOM` instance if the URL is valid and the request is successful. Any redirects will be followed to their ultimate destination. The options provided to `fromURL()` are similar to those provided to the `JSDOM` constructor, with the following additional restrictions and consequences: - The `url` and `contentType` options cannot be provided. - The `referrer` option is used as the HTTP `Referer` request header of the initial request. - The `resources` option also affects the initial request; this is useful if you want to, for example, configure a proxy (see above). - The resulting jsdom's URL, content type, and referrer are determined from the response. - Any cookies set via HTTP `Set-Cookie` response headers are stored in the jsdom's cookie jar. Similarly, any cookies already in a supplied cookie jar are sent as HTTP `Cookie` request headers. ### `fromFile()` Similar to `fromURL()`, jsdom also provides a `fromFile()` factory method for constructing a jsdom from a filename: ```js JSDOM.fromFile("stuff.html", options).then(dom => { console.log(dom.serialize()); }); ``` The returned promise will fulfill with a `JSDOM` instance if the given file can be opened. As usual in Node.js APIs, the filename is given relative to the current working directory. The options provided to `fromFile()` are similar to those provided to the `JSDOM` constructor, with the following additional defaults: - The `url` option will default to a file URL corresponding to the given filename, instead of to `"about:blank"`. - The `contentType` option will default to `"application/xhtml+xml"` if the given filename ends in `.xhtml` or `.xml`; otherwise it will continue to default to `"text/html"`. ### `fragment()` For the very simplest of cases, you might not need a whole `JSDOM` instance with all its associated power. You might not even need a `Window` or `Document`! Instead, you just need to parse some HTML, and get a DOM object you can manipulate. For that, we have `fragment()`, which creates a `DocumentFragment` from a given string: ```js const frag = JSDOM.fragment(`<p>Hello</p><p><strong>Hi!</strong>`); frag.childNodes.length === 2; frag.querySelector("strong").textContent === "Hi!"; // etc. ``` Here `frag` is a [`DocumentFragment`](https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment) instance, whose contents are created by parsing the provided string. The parsing is done using a `<template>` element, so you can include any element there (including ones with weird parsing rules like `<td>`). It's also important to note that the resulting `DocumentFragment` will not have [an associated browsing context](https://html.spec.whatwg.org/multipage/#concept-document-bc): that is, elements' `ownerDocument` will have a null `defaultView` property, resources will not load, etc. All invocations of the `fragment()` factory result in `DocumentFragment`s that share the same template owner `Document`. This allows many calls to `fragment()` with no extra overhead. But it also means that calls to `fragment()` cannot be customized with any options. Note that serialization is not as easy with `DocumentFragment`s as it is with full `JSDOM` objects. If you need to serialize your DOM, you should probably use the `JSDOM` constructor more directly. But for the special case of a fragment containing a single element, it's pretty easy to do through normal means: ```js const frag = JSDOM.fragment(`<p>Hello</p>`); console.log(frag.firstChild.outerHTML); // logs "<p>Hello</p>" ``` ## Other noteworthy features ### Canvas support jsdom includes support for using the [`canvas`](https://www.npmjs.com/package/canvas) package to extend any `<canvas>` elements with the canvas API. To make this work, you need to include `canvas` as a dependency in your project, as a peer of `jsdom`. If jsdom can find the `canvas` package, it will use it, but if it's not present, then `<canvas>` elements will behave like `<div>`s. Since jsdom v13, version 2.x of `canvas` is required; version 1.x is no longer supported. ### Encoding sniffing In addition to supplying a string, the `JSDOM` constructor can also be supplied binary data, in the form of a Node.js [`Buffer`](https://nodejs.org/docs/latest/api/buffer.html) or a standard JavaScript binary data type like `ArrayBuffer`, `Uint8Array`, `DataView`, etc. When this is done, jsdom will [sniff the encoding](https://html.spec.whatwg.org/multipage/syntax.html#encoding-sniffing-algorithm) from the supplied bytes, scanning for `<meta charset>` tags just like a browser does. This encoding sniffing also applies to `JSDOM.fromFile()` and `JSDOM.fromURL()`. In the latter case, just as in a browser, any `Content-Type` headers sent with the response will take priority. Note that in many cases supplying bytes in this fashion can be better than supplying a string. For example, if you attempt to use Node.js's `buffer.toString("utf-8")` API, Node.js will not strip any leading BOMs. If you then give this string to jsdom, it will interpret it verbatim, leaving the BOM intact. But jsdom's binary data decoding code will strip leading BOMs, just like a browser; in such cases, supplying `buffer` directly will give the desired result. ### Closing down a jsdom Timers in the jsdom (set by `window.setTimeout()` or `window.setInterval()`) will, by definition, execute code in the future in the context of the window. Since there is no way to execute code in the future without keeping the process alive, outstanding jsdom timers will keep your Node.js process alive. Similarly, since there is no way to execute code in the context of an object without keeping that object alive, outstanding jsdom timers will prevent garbage collection of the window on which they are scheduled. If you want to be sure to shut down a jsdom window, use `window.close()`, which will terminate all running timers (and also remove any event listeners on the window and document). ### Running jsdom inside a web browser jsdom has some support for being run inside a web browser, using [browserify](https://browserify.org/). That is, inside a web browser, you can use a browserified jsdom to create an entirely self-contained set of plain JavaScript objects which look and act much like the browser's existing DOM objects, while being entirely independent of them. "Virtual DOM", indeed! jsdom's primary target is still Node.js, and so we use language features that are only present in recent Node.js versions (namely, Node.js v8+). Thus, older browsers will likely not work. (Even transpilation will not help: we use `Proxy`s extensively throughout the jsdom codebase.) Notably, jsdom works well inside a web worker. The original contributor, [@lawnsea](https://github.com/lawnsea/), who made this possible, has [published a paper](https://pdfs.semanticscholar.org/47f0/6bb6607a975500a30e9e52d7c9fbc0034e27.pdf) about his project which uses this capability. Not everything works perfectly when running jsdom inside a web browser. Sometimes that is because of fundamental limitations (such as not having filesystem access), but sometimes it is simply because we haven't spent enough time making the appropriate small tweaks. Bug reports are certainly welcome. ### Debugging the DOM using Chrome Devtools As of Node.js v6 you can debug programs using Chrome Devtools. See the [official documentation](https://nodejs.org/en/docs/inspector/) for how to get started. By default jsdom elements are formatted as plain old JS objects in the console. To make it easier to debug, you can use [jsdom-devtools-formatter](https://github.com/viddo/jsdom-devtools-formatter), which lets you inspect them like real DOM elements. ## Caveats ### Asynchronous script loading People often have trouble with asynchronous script loading when using jsdom. Many pages load scripts asynchronously, but there is no way to tell when they're done doing so, and thus when it's a good time to run your code and inspect the resulting DOM structure. This is a fundamental limitation; we cannot predict what scripts on the web page will do, and so cannot tell you when they are done loading more scripts. This can be worked around in a few ways. The best way, if you control the page in question, is to use whatever mechanisms are given by the script loader to detect when loading is done. For example, if you're using a module loader like RequireJS, the code could look like: ```js // On the Node.js side: const window = (new JSDOM(...)).window; window.onModulesLoaded = () => { console.log("ready to roll!"); }; ``` ```html <!-- Inside the HTML you supply to jsdom --> <script> requirejs(["entry-module"], () => { window.onModulesLoaded(); }); </script> ``` If you do not control the page, you could try workarounds such as polling for the presence of a specific element. For more details, see the discussion in [#640](https://github.com/jsdom/jsdom/issues/640), especially [@matthewkastor](https://github.com/matthewkastor)'s [insightful comment](https://github.com/jsdom/jsdom/issues/640#issuecomment-22216965). ### Shared constructors and prototypes At the present time, for most web platform APIs, jsdom shares the same class definition between multiple seemingly-independent jsdoms. That means that, for example, the following situation can occur: ```js const dom1 = new JSDOM(); const dom2 = new JSDOM(); dom1.window.Element.prototype.expando = "blah"; console.log(dom2.window.document.createElement("frameset").expando); // logs "blah" ``` This is done mainly for performance and memory reasons: creating separate copies of all the many classes on the web platform, each time we create a jsdom, would be rather expensive. Nevertheless, we remain interested in one day providing an option to create an "independent" jsdom, at the cost of some performance. ### Unimplemented parts of the web platform Although we enjoy adding new features to jsdom and keeping it up to date with the latest web specs, it has many missing APIs. Please feel free to file an issue for anything missing, but we're a small and busy team, so a pull request might work even better. Beyond just features that we haven't gotten to yet, there are two major features that are currently outside the scope of jsdom. These are: - **Navigation**: the ability to change the global object, and all other objects, when clicking a link or assigning `location.href` or similar. - **Layout**: the ability to calculate where elements will be visually laid out as a result of CSS, which impacts methods like `getBoundingClientRects()` or properties like `offsetTop`. Currently jsdom has dummy behaviors for some aspects of these features, such as sending a "not implemented" `"jsdomError"` to the virtual console for navigation, or returning zeros for many layout-related properties. Often you can work around these limitations in your code, e.g. by creating new `JSDOM` instances for each page you "navigate" to during a crawl, or using `Object.defineProperty()` to change what various layout-related getters and methods return. Note that other tools in the same space, such as PhantomJS, do support these features. On the wiki, we have a more complete writeup about [jsdom vs. PhantomJS](https://github.com/jsdom/jsdom/wiki/jsdom-vs.-PhantomJS). ## Getting help If you need help with jsdom, please feel free to use any of the following venues: - The [mailing list](http://groups.google.com/group/jsdom) (best for "how do I" questions) - The [issue tracker](https://github.com/jsdom/jsdom/issues) (best for bug reports) - The IRC channel: [#jsdom on freenode](irc://irc.freenode.net/jsdom) # 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._ ![](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) # 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._ 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:dmitry@codingrobots.com).** 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/) # 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._ # 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 # undefsafe Simple *function* for retrieving deep object properties without getting "Cannot read property 'X' of undefined" Can also be used to safely set deep values. ## Usage ```js var object = { a: { b: { c: 1, d: [1,2,3], e: 'remy' } } }; console.log(undefsafe(object, 'a.b.e')); // "remy" console.log(undefsafe(object, 'a.b.not.found')); // undefined ``` Demo: [https://jsbin.com/eroqame/3/edit?js,console](https://jsbin.com/eroqame/3/edit?js,console) ## Setting ```js var object = { a: { b: [1,2,3] } }; // modified object var res = undefsafe(object, 'a.b.0', 10); console.log(object); // { a: { b: [10, 2, 3] } } console.log(res); // 1 - previous value ``` ## Star rules in paths As of 1.2.0, `undefsafe` supports a `*` in the path if you want to search all of the properties (or array elements) for a particular element. The function will only return a single result, either the 3rd argument validation value, or the first positive match. For example, the following github data: ```js const githubData = { commits: [{ modified: [ "one", "two" ] }, /* ... */ ] }; // first modified file found in the first commit console.log(undefsafe(githubData, 'commits.*.modified.0')); // returns `two` or undefined if not found console.log(undefsafe(githubData, 'commits.*.modified.*', 'two')); ``` # acorn-globals Detect global variables in JavaScript using acorn [Get supported acorn-globals with the Tidelift Subscription](https://tidelift.com/subscription/pkg/npm-acorn_globals?utm_source=npm-acorn-globals&utm_medium=referral&utm_campaign=readme) [![Build Status](https://img.shields.io/travis/ForbesLindesay/acorn-globals/master.svg)](https://travis-ci.org/ForbesLindesay/acorn-globals) [![Dependency Status](https://img.shields.io/david/ForbesLindesay/acorn-globals.svg)](https://david-dm.org/ForbesLindesay/acorn-globals) [![NPM version](https://img.shields.io/npm/v/acorn-globals.svg)](https://www.npmjs.org/package/acorn-globals) ## Installation npm install acorn-globals ## Usage detect.js ```js var fs = require('fs'); var detect = require('acorn-globals'); var src = fs.readFileSync(__dirname + '/input.js', 'utf8'); var scope = detect(src); console.dir(scope); ``` input.js ```js var x = 5; var y = 3, z = 2; w.foo(); w = 2; RAWR=444; RAWR.foo(); BLARG=3; foo(function () { var BAR = 3; process.nextTick(function (ZZZZZZZZZZZZ) { console.log('beep boop'); var xyz = 4; x += 10; x.zzzzzz; ZZZ=6; }); function doom () { } ZZZ.foo(); }); console.log(xyz); ``` output: ``` $ node example/detect.js [ { name: 'BLARG', nodes: [ [Object] ] }, { name: 'RAWR', nodes: [ [Object], [Object] ] }, { name: 'ZZZ', nodes: [ [Object], [Object] ] }, { name: 'console', nodes: [ [Object], [Object] ] }, { name: 'foo', nodes: [ [Object] ] }, { name: 'process', nodes: [ [Object] ] }, { name: 'w', nodes: [ [Object], [Object] ] }, { name: 'xyz', nodes: [ [Object] ] } ] ``` ## 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 # `babel-preset-current-node-syntax` > A Babel preset that enables parsing of proposals supported by the current Node.js version. ## Installation If you are using yarn: ``` yarn add --dev babel-preset-current-node-syntax ``` If you are using npm: ``` npm install --save-dev babel-preset-current-node-syntax ``` ## Contributing PRs are welcome! The codebase is so small that I didn't setup a linter, but try to match the style of the existing code. You can run tests with the following command: ``` yarn node test/index.js ``` The `test/fixtures.json` file contains a bunch of syntax tests, alongside with the minimum supported node version for each of them. Babel should throw on older versions, without support for that given syntax. All the tests are run using `@babel/parser@7.0.0`. # assert [![Build Status](https://travis-ci.org/browserify/commonjs-assert.svg?branch=master)](https://travis-ci.org/browserify/commonjs-assert) This module is used for writing unit tests for your applications, you can access it with `require('assert')`. It aims to be fully compatibe with the [node.js assert module](http://nodejs.org/api/assert.html), same API and same behavior, just adding support for web browsers. The API and code may contain traces of the [CommonJS Unit Testing 1.0 spec](http://wiki.commonjs.org/wiki/Unit_Testing/1.0) which they were based on, but both have evolved significantly since then. A `strict` and a `legacy` mode exist, while it is recommended to only use `strict mode`. ## Strict mode When using the `strict mode`, any `assert` function will use the equality used in the strict function mode. So `assert.deepEqual()` will, for example, work the same as `assert.deepStrictEqual()`. It can be accessed using: ```js const assert = require('assert').strict; ``` ## Legacy mode > Deprecated: Use strict mode instead. When accessing `assert` directly instead of using the `strict` property, the [Abstract Equality Comparison](https://tc39.github.io/ecma262/#sec-abstract-equality-comparison) will be used for any function without a "strict" in its name (e.g. `assert.deepEqual()`). It can be accessed using: ```js const assert = require('assert'); ``` It is recommended to use the `strict mode` instead as the Abstract Equality Comparison can often have surprising results. Especially in case of `assert.deepEqual()` as the used comparison rules there are very lax. E.g. ```js // WARNING: This does not throw an AssertionError! assert.deepEqual(/a/gi, new Date()); ``` ## 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.deepStrictEqual(actual, expected, [message]) Tests for deep equality, as determined by the strict equality operator ( === ) ## 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. # 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. # 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 # cssnano-util-get-match > Convert a list of keywords into a single keyword match. ## Contributors See [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md). ## License MIT © [Ben Briggs](http://beneb.info) # 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._ # 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"), ]); }); ``` # 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). # 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._ # 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 # 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 # 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._ # 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._ # 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._ # 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. # dotenv <img src="https://raw.githubusercontent.com/motdotla/dotenv/master/dotenv.png" alt="dotenv" align="right" /> Dotenv is a zero-dependency module that loads environment variables from a `.env` file into [`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env). Storing configuration in the environment separate from code is based on [The Twelve-Factor App](http://12factor.net/config) methodology. [![BuildStatus](https://img.shields.io/travis/motdotla/dotenv/master.svg?style=flat-square)](https://travis-ci.org/motdotla/dotenv) [![Build status](https://ci.appveyor.com/api/projects/status/rnba2pyi87hgc8xw/branch/master?svg=true)](https://ci.appveyor.com/project/maxbeatty/dotenv/branch/master) [![NPM version](https://img.shields.io/npm/v/dotenv.svg?style=flat-square)](https://www.npmjs.com/package/dotenv) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square)](https://github.com/feross/standard) [![Coverage Status](https://img.shields.io/coveralls/motdotla/dotenv/master.svg?style=flat-square)](https://coveralls.io/github/motdotla/dotenv?branch=coverall-intergration) ## Install ```bash npm install dotenv --save ``` ## Usage As early as possible in your application, require and configure dotenv. ```javascript require('dotenv').config() ``` Create a `.env` file in the root directory of your project. Add environment-specific variables on new lines in the form of `NAME=VALUE`. For example: ```dosini DB_HOST=localhost DB_USER=root DB_PASS=s1mpl3 ``` That's it. `process.env` now has the keys and values you defined in your `.env` file. ```javascript const db = require('db') db.connect({ host: process.env.DB_HOST, username: process.env.DB_USER, password: process.env.DB_PASS }) ``` ### Preload You can use the `--require` (`-r`) command line option to preload dotenv. By doing this, you do not need to require and load dotenv in your application code. This is the preferred approach when using `import` instead of `require`. ```bash $ node -r dotenv/config your_script.js ``` The configuration options below are supported as command line arguments in the format `dotenv_config_<option>=value` ```bash $ node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/your/env/vars ``` ## Config _Alias: `load`_ `config` will read your .env file, parse the contents, assign it to [`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env), and return an Object with a `parsed` key containing the loaded content or an `error` key if it failed. ```js const result = dotenv.config() if (result.error) { throw result.error } console.log(result.parsed) ``` You can additionally, pass options to `config`. ### Options #### Path Default: `path.resolve(process.cwd(), '.env')` You can specify a custom path if your file containing environment variables is named or located differently. ```js require('dotenv').config({path: '/full/custom/path/to/your/env/vars'}) ``` #### Encoding Default: `utf8` You may specify the encoding of your file containing environment variables using this option. ```js require('dotenv').config({encoding: 'base64'}) ``` ## Parse The engine which parses the contents of your file containing environment variables is available to use. It accepts a String or Buffer and will return an Object with the parsed keys and values. ```js const dotenv = require('dotenv') const buf = new Buffer('BASIC=basic') const config = dotenv.parse(buf) // will return an object console.log(typeof config, config) // object { BASIC : 'basic' } ``` ### Rules The parsing engine currently supports the following rules: - `BASIC=basic` becomes `{BASIC: 'basic'}` - empty lines are skipped - lines beginning with `#` are treated as comments - empty values become empty strings (`EMPTY=` becomes `{EMPTY: ''}`) - single and double quoted values are escaped (`SINGLE_QUOTE='quoted'` becomes `{SINGLE_QUOTE: "quoted"}`) - new lines are expanded if in double quotes (`MULTILINE="new\nline"` becomes ``` {MULTILINE: 'new line'} ``` - inner quotes are maintained (think JSON) (`JSON={"foo": "bar"}` becomes `{JSON:"{\"foo\": \"bar\"}"`) - whitespace is removed from both ends of the value (see more on [`trim`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)) (`FOO=" some value "` becomes `{FOO: 'some value'}`) ## FAQ ### Should I commit my `.env` file? No. We **strongly** recommend against committing your `.env` file to version control. It should only include environment-specific values such as database passwords or API keys. Your production database should have a different password than your development database. ### Should I have multiple `.env` files? No. We **strongly** recommend against having a "main" `.env` file and an "environment" `.env` file like `.env.test`. Your config should vary between deploys, and you should not be sharing values between environments. > In a twelve-factor app, env vars are granular controls, each fully orthogonal to other env vars. They are never grouped together as “environments”, but instead are independently managed for each deploy. This is a model that scales up smoothly as the app naturally expands into more deploys over its lifetime. > > – [The Twelve-Factor App](http://12factor.net/config) ### What happens to environment variables that were already set? We will never modify any environment variables that have already been set. In particular, if there is a variable in your `.env` file which collides with one that already exists in your environment, then that variable will be skipped. This behavior allows you to override all `.env` configurations with a machine-specific environment, although it is not recommended. If you want to override `process.env` you can do something like this: ```javascript const fs = require('fs') const dotenv = require('dotenv') const envConfig = dotenv.parse(fs.readFileSync('.env.override')) for (var k in envConfig) { process.env[k] = envConfig[k] } ``` ### Can I customize/write plugins for dotenv? For `dotenv@2.x.x`: Yes. `dotenv.config()` now returns an object representing the parsed `.env` file. This gives you everything you need to continue setting values on `process.env`. For example: ```js var dotenv = require('dotenv') var variableExpansion = require('dotenv-expand') const myEnv = dotenv.config() variableExpansion(myEnv) ``` ### What about variable expansion? For `dotenv@2.x.x`: Use [dotenv-expand](https://github.com/motdotla/dotenv-expand). For `dotenv@1.x.x`: We haven't been presented with a compelling use case for expanding variables and believe it leads to env vars that are not "fully orthogonal" as [The Twelve-Factor App](http://12factor.net/config) outlines.<sup>[[1](https://github.com/motdotla/dotenv/issues/39)][[2](https://github.com/motdotla/dotenv/pull/97)]</sup> Please open an issue if you have a compelling use case. ### How do I use dotenv with `import`? ES2015 and beyond offers modules that allow you to `export` any top-level `function`, `class`, `var`, `let`, or `const`. > When you run a module containing an `import` declaration, the modules it imports are loaded first, then each module body is executed in a depth-first traversal of the dependency graph, avoiding cycles by skipping anything already executed. > > – [ES6 In Depth: Modules](https://hacks.mozilla.org/2015/08/es6-in-depth-modules/) You must run `dotenv.config()` before referencing any environment variables. Here's an example of problematic code: `errorReporter.js`: ```js import { Client } from 'best-error-reporting-service' export const client = new Client(process.env.BEST_API_KEY) ``` `index.js`: ```js import dotenv from 'dotenv' dotenv.config() import errorReporter from './errorReporter' errorReporter.client.report(new Error('faq example')) ``` `client` will not be configured correctly because it was constructed before `dotenv.config()` was executed. There are (at least) 3 ways to make this work. 1. Preload dotenv: `node --require dotenv/config index.js` (_Note: you do not need to `import` dotenv with this approach_) 2. Import `dotenv/config` instead of `dotenv` (_Note: you do not need to call `dotenv.config()` and must pass options via the command line with this approach_) 3. Create a separate file that will execute `config` first as outlined in [this comment on #133](https://github.com/motdotla/dotenv/issues/133#issuecomment-255298822) ## Contributing Guide See [CONTRIBUTING.md](CONTRIBUTING.md) ## Change Log See [CHANGELOG.md](CHANGELOG.md) ## License See [LICENSE](LICENSE) ## Who's using dotenv Here's just a few of many repositories using dotenv: * [jaws](https://github.com/jaws-framework/jaws-core-js) * [node-lambda](https://github.com/motdotla/node-lambda) * [resume-cli](https://www.npmjs.com/package/resume-cli) * [phant](https://www.npmjs.com/package/phant) * [adafruit-io-node](https://github.com/adafruit/adafruit-io-node) * [mockbin](https://www.npmjs.com/package/mockbin) * [and many more...](https://www.npmjs.com/browse/depended/dotenv) ## Go well with dotenv Here's some projects that expand on dotenv. Check them out. * [require-environment-variables](https://github.com/bjoshuanoah/require-environment-variables) * [dotenv-safe](https://github.com/rolodato/dotenv-safe) * [envalid](https://github.com/af/envalid) * [lookenv](https://github.com/RodrigoEspinosa/lookenv) * [run.env](https://www.npmjs.com/package/run.env) * [dotenv-webpack](https://github.com/mrsteele/dotenv-webpack) # 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>. # 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._ # 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' ``` # 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 # **node-addon-api module** This module contains **header-only C++ wrapper classes** which simplify the use of the C based [N-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. N-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 N-API as it consists only of inline code that depends only on the stable API provided by N-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 N-API and/or `node-addon-api` exclusively and build against a version of Node.js that includes an implementation of N-API (meaning a version of Node.js newer than 6.14.2) 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 N-API ABI stability guarantee in particular. As new APIs are added to N-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 N-API handles so direct calls to N-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**. - **[Setup](#setup)** - **[API Documentation](#api)** - **[Examples](#examples)** - **[Tests](#tests)** - **[More resource and info about native Addons](#resources)** - **[Code of Conduct](CODE_OF_CONDUCT.md)** - **[Contributors](#contributors)** - **[License](#license)** ## **Current version: 1.7.2** (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> ## 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. - [Basic Types](doc/basic_types.md) - [Array](doc/basic_types.md#array) - [Symbol](doc/symbol.md) - [String](doc/string.md) - [Name](doc/basic_types.md#name) - [Number](doc/number.md) - [BigInt](doc/bigint.md) - [Boolean](doc/boolean.md) - [Env](doc/env.md) - [Value](doc/value.md) - [CallbackInfo](doc/callbackinfo.md) - [Reference](doc/reference.md) - [External](doc/external.md) - [Object](doc/object.md) - [ObjectReference](doc/object_reference.md) - [PropertyDescriptor](doc/property_descriptor.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) - [Working with JavaScript Values](doc/working_with_javascript_values.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) - [Memory Management](doc/memory_management.md) - [Async Operations](doc/async_operations.md) - [AsyncWorker](doc/async_worker.md) - [AsyncContext](doc/async_context.md) - [Thread-safe Functions](doc/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/master/1_hello_world/node-addon-api)** - **[Pass arguments to a function](https://github.com/nodejs/node-addon-examples/tree/master/2_function_arguments/node-addon-api)** - **[Callbacks](https://github.com/nodejs/node-addon-examples/tree/master/3_callbacks/node-addon-api)** - **[Object factory](https://github.com/nodejs/node-addon-examples/tree/master/4_object_factory/node-addon-api)** - **[Function factory](https://github.com/nodejs/node-addon-examples/tree/master/5_function_factory/node-addon-api)** - **[Wrapping C++ Object](https://github.com/nodejs/node-addon-examples/tree/master/6_object_wrap/node-addon-api)** - **[Factory of wrapped object](https://github.com/nodejs/node-addon-examples/tree/master/7_factory_wrap/node-addon-api)** - **[Passing wrapped object around](https://github.com/nodejs/node-addon-examples/tree/master/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 ``` ### **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/master/test)** <a name="resources"></a> ## **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. ### **More resource and info about native Addons** - **[C++ Addons](https://nodejs.org/dist/latest/docs/api/addons.html)** - **[N-API](https://nodejs.org/dist/latest/docs/api/n-api.html)** - **[N-API - Next Generation Node API for Native Modules](https://youtu.be/-Oniup60Afs)** <a name="contributors"></a> ## WG Members / Collaborators ### Active | Name | GitHub Link | | ------------------- | ----------------------------------------------------- | | Anna Henningsen | [addaleax](https://github.com/addaleax) | | Arunesh Chandra | [aruneshchandra](https://github.com/aruneshchandra) | | Gabriel Schulhof | [gabrielschulhof](https://github.com/gabrielschulhof) | | Hitesh Kanwathirtha | [digitalinfinity](https://github.com/digitalinfinity) | | Jim Schlight | [jschlight](https://github.com/jschlight) | | Michael Dawson | [mhdawson](https://github.com/mhdawson) | | Nicola Del Gobbo | [NickNaso](https://github.com/NickNaso) | | Taylor Woll | [boingoing](https://github.com/boingoing) | ### Emeritus | Name | GitHub Link | | ------------------- | ----------------------------------------------------- | | Benjamin Byholm | [kkoopa](https://github.com/kkoopa) | | Jason Ginchereau | [jasongin](https://github.com/jasongin) | | Sampson Gao | [sampsongao](https://github.com/sampsongao) | <a name="license"></a> Licensed under [MIT](./LICENSE.md) [ABI stability guide]: https://nodejs.org/en/docs/guides/abi-stability/ # 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](https://evilmartians.com/?utm_source=postcss) at <surrender@evilmartians.com>. [Abstract Syntax Tree]: https://en.wikipedia.org/wiki/Abstract_syntax_tree [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 ### Gulp Use [`gulp-postcss`] and [`gulp-sourcemaps`]. ```js gulp.task('css', function () { var postcss = require('gulp-postcss'); var 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 fs = require('fs'); const postcss = require('postcss'); const precss = require('precss'); const autoprefixer = require('autoprefixer'); 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 ## 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/ [![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 # 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._ # 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 <surrender@evilmartians.com>. [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> ## Sponsorship PostCSS needs your support. We are accepting donations [at Open Collective](https://opencollective.com/postcss/). <a href="https://tailwindcss.com/"> <img src="https://refactoringui.nyc3.cdn.digitaloceanspaces.com/tailwind-logo.svg" alt="Sponsored by Tailwind CSS" width="273" height="64"> </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 ### 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 ### Parcel [Parcel] has built-in PostCSS support. It already uses Autoprefixer and cssnano. If you want to change plugins, create `postcss.config.js` in project’s root: ```js module.exports = { plugins: [ require('autoprefixer'), require('postcss-nested') ] } ``` Parcel will even automatically install these plugins for you. > Please, be aware of [the several issues in Version 1](https://github.com/parcel-bundler/parcel/labels/CSS%20Preprocessing). Notice, [Version 2](https://github.com/parcel-bundler/parcel/projects/5) may resolve the issues via [issue #2157](https://github.com/parcel-bundler/parcel/issues/2157). [Parcel]: https://parceljs.org ### 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 ### 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') ] } ``` ## Contributing [Our contributing guidelines](./CONTRIBUTING.md) will help you with making pull request to this project. ## Editors & IDE Integration ### VS Code * [`csstools.postcss`] adds support for PostCSS, `postcss-preset-env` and CSS Modules. [`csstools.postcss`]: https://marketplace.visualstudio.com/items?itemName=csstools.postcss ### 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/ ## 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 ## For Enterprise Available as part of the Tidelift Subscription. The maintainers of `postcss` 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-postcss?utm_source=npm-postcss&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) 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. # 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 ``` This is [Unicode Normalizer] in a Common JS module. I'm not affiliated with Matsuza, the original author of Unicode Normalizer. [![Build Status](https://travis-ci.org/walling/unorm.png?branch=master)](https://travis-ci.org/walling/unorm) Installation ------------ ```bash npm install unorm ``` Polyfill -------- You can use this module as a polyfill for [String.prototype.normalize], for example: ```javascript console.log('æøåäüö'.normalize('NFKD')); ``` The module uses some [EcmaScript 5](http://kangax.github.io/es5-compat-table/) features. Other browsers should use a compability shim, e.g. [es5-shim](https://github.com/kriskowal/es5-shim). Functions --------- This module exports four functions: `nfc`, `nfd`, `nfkc`, and `nfkd`; one for each Unicode normalization. In the browser the functions are exported in the `unorm` global. In CommonJS environments you just require the module. Functions: * `unorm.nfd(str)` – Canonical Decomposition * `unorm.nfc(str)` – Canonical Decomposition, followed by Canonical Composition * `unorm.nfkd(str)` – Compatibility Decomposition * `unorm.nfkc(str)` – Compatibility Decomposition, followed by Canonical Composition Node.JS example --------------- For a longer example, see `examples` directory. ```javascript var unorm = require('unorm'); var text = 'The \u212B symbol invented by A. J. \u00C5ngstr\u00F6m ' + '(1814, L\u00F6gd\u00F6, \u2013 1874) denotes the length ' + '10\u207B\u00B9\u2070 m.'; var combining = /[\u0300-\u036F]/g; // Use XRegExp('\\p{M}', 'g'); see example.js. console.log('Regular: ' + text); console.log('NFC: ' + unorm.nfc(text)); console.log('NFD: ' + unorm.nfd(text)); console.log('NFKC: ' + unorm.nfkc(text)); console.log('NFKD: * ' + unorm.nfkd(text).replace(combining, '')); console.log(' * = Combining characters removed from decomposed form.'); ``` Road map -------- As of November 2013. Longer term: - Look at possible optimizations (speed primarely, module size secondarily) - Adding functions to quick check normalizations: `is_nfc`, `is_nfd`, etc. Contributers ------------ - **Oleg Grenrus** is helping to maintain this library. He cleaned up the code base, fixed JSHint errors, created a test suite and updated the normalization data to Unicode 6.3. Development notes ----------------- - [Unicode normalization forms report](http://www.unicode.org/reports/tr15/) - Unicode data can be found from http://www.unicode.org/Public/UCD/latest/ucd To generate new unicode data, run: ```sh cd src/data/src javac UnormNormalizerBuilder.java java UnormNormalizerBuilder ``` produced `unormdata.js` contains needed table Execute `node benchmark/benchmark.js` to run simple benchmarks, if you do any changes which may affect performance. License ------- This project includes the software package **Unicode Normalizer 1.0.0**. The software dual licensed under the MIT and GPL licenses. Here is the MIT license: Copyright (c) 2008-2013 Matsuza <matsuza@gmail.com>, Bjarke Walling <bwp@bwp.dk> 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. [Unicode Normalizer]: http://coderepos.org/share/browser/lang/javascript/UnicodeNormalizer [String.prototype.normalize]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/normalize <!-- -- 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](#react-native) - **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 `uuid@3.x`?** Your code is probably okay, but check out [Upgrading From `uuid@3.x`](#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 `uuid@8.3` | | [`uuid.parse()`](#uuidparsestr) | Convert UUID string to array of bytes | New in `uuid@8.3` | | [`uuid.stringify()`](#uuidstringifyarr-offset) | Convert array of bytes to UUID string | New in `uuid@8.3` | | [`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 `uuid@8.3` | | [`uuid.version()`](#uuidversionstr) | Detect RFC version of a UUID | New in `uuid@8.3` | ## 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 | Example: ```javascript import { parse as uuidParse } from 'uuid'; uuidParse('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ // Uint8Array(16) [ // 110, 192, 189, 127, 17, // 192, 67, 218, 151, 94, // 42, 138, 217, 235, 174, // 11 // ] ``` ### 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 | Example: ```javascript import { stringify as uuidStringify } from 'uuid'; const uuidBytes = [110, 192, 189, 127, 17, 192, 67, 218, 151, 94, 42, 138, 217, 235, 174, 11]; 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]]) Createa 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 ``` ### 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 1. Install [`react-native-get-random-values`](https://github.com/LinusU/react-native-get-random-values#readme) 1. Import it before `uuid`: ```javascript import 'react-native-get-random-values'; import { v4 as uuidv4 } from 'uuid'; ``` ### 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 `uuid@7.x` ### Only Named Exports Supported When Using with Node.js ESM `uuid@7.x` 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 `uuid@7.x`](#deep-requires-now-deprecated) are no longer supported. ## Upgrading From `uuid@3.x` "_Wait... what happened to `uuid@4.x` - `uuid@6.x`?!?_" 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 `uuid@3.x` 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 `uuid@7.x` 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 `uuid@3.x` was exporting the Version 4 UUID method as a default export: ```javascript const uuid = require('uuid'); // <== REMOVED! ``` This usage pattern was already discouraged in `uuid@3.x` and has been removed in `uuid@7.x`. ---- Markdown generated from [README_js.md](README_js.md) by [![RunMD Logo](http://i.imgur.com/h0FVyzU.png)](https://github.com/broofa/runmd) # expect This package exports the `expect` function used in [Jest](https://jestjs.io/). You can find its documentation [on Jest's website](https://jestjs.io/docs/en/expect.html). # jest-mock ## API ### `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. # 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. 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). # 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._ [![Travis CI](https://travis-ci.org/digitaldesignlabs/es6-promisify.svg)](https://travis-ci.org/digitaldesignlabs/es6-promisify) # es6-promisify Converts callback-based functions to Promise-based functions. ## Install Install with [npm](https://npmjs.org/package/es6-promisify) ```bash npm install --save es6-promisify ``` ## Example ```js "use strict"; // Declare variables const promisify = require("es6-promisify"); const fs = require("fs"); // Convert the stat function const stat = promisify(fs.stat); // Now usable as a promise! stat("example.txt").then(function (stats) { console.log("Got stats", stats); }).catch(function (err) { console.error("Yikes!", err); }); ``` ## Promisify methods ```js "use strict"; // Declare variables const promisify = require("es6-promisify"); const redis = require("redis").createClient(6379, "localhost"); // Create a promise-based version of send_command const client = promisify(redis.send_command, redis); // Send commands to redis and get a promise back client("ping").then(function (pong) { console.log("Got", pong); }).catch(function (err) { console.error("Unexpected error", err); }).then(function () { redis.quit(); }); ``` ## Handle callback multiple arguments ```js "use strict"; // Declare functions function test(cb) { return cb(undefined, 1, 2, 3); } // Declare variables const promisify = require("es6-promisify"); // Create promise-based version of test const single = promisify(test); const multi = promisify(test, {multiArgs: true}); // Discards additional arguments single().then(function (result) { console.log(result); // 1 }); // Returns all arguments as an array multi().then(function (result) { console.log(result); // [1, 2, 3] }); ``` ### Tests Test with nodeunit ```bash $ npm test ``` Published under the [MIT License](http://opensource.org/licenses/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 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._ # 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`/`es2019` 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` ## Security Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. [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 # 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 more than three 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 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><img src="https://terser.org/img/terser-banner-logo.png" alt="Terser" width="400"></h1> [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Travis Build][travis-image]][travis-url] [![Opencollective financial contributors][opencollective-contributors]][opencollective-url] 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/become_a_patron_button@2x.png" alt="patron" width="100px" height="auto"></a>. Check out [PATRONS.md](https://github.com/terser/terser/blob/master/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). Find the changelog in [CHANGELOG.md](https://github.com/terser/terser/blob/master/CHANGELOG.md) [npm-image]: https://img.shields.io/npm/v/terser.svg [npm-url]: https://npmjs.org/package/terser [downloads-image]: https://img.shields.io/npm/dm/terser.svg [downloads-url]: https://npmjs.org/package/terser [travis-image]: https://img.shields.io/travis/terser/terser/master.svg [travis-url]: https://travis-ci.org/terser/terser [opencollective-contributors]: https://opencollective.com/terser/tiers/badge.svg [opencollective-url]: https://opencollective.com/terser 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 mostly 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 and DOM API props. `debug` Add debug prefix and suffix. `keep_quoted` Only mangle unquoted properties, quoted properties are automatically reserved. `strict` disables quoted properties being automatically reserved. `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. `wrap_func_args` Wrap function arguments in parenthesis. -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 - `false` to omit comments in the output - 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, 2015, 2016, etc. -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 end 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 passes=2 -m --mangle-props ``` ```javascript var x={o:3,t:1,i:function(){return this.t+this.o},s:2};console.log(x.i()); ``` Mangle all properties except for `reserved` properties (still very unsafe): ```bash $ terser example.js -c passes=2 -m --mangle-props reserved=[foo_,bar_] ``` ```javascript var x={o:3,foo_:1,t:function(){return this.foo_+this.o},bar_:2};console.log(x.t()); ``` Mangle all properties matching a `regex` (not as unsafe but still unsafe): ```bash $ terser example.js -c passes=2 -m --mangle-props regex=/_$/ ``` ```javascript var x={o:3,t:1,calc:function(){return this.t+this.o},i:2};console.log(x.calc()); ``` Combining mangle properties options: ```bash $ terser example.js -c passes=2 -m --mangle-props regex=/_$/,reserved=[bar_] ``` ```javascript var x={o:3,t:1,calc:function(){return this.t+this.o},bar_:2};console.log(x.calc()); ``` In order for this to be of any use, we avoid mangling standard JS names and DOM API properties by default (`--mangle-props builtins` to override). 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 `uglify-js@2.x`, 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`, `2015`, `2016`, etc to override `parse`, `compress` and `output`'s `ecma` 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, 2015, 2016, etc. 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`. If you happen to need the source map as a raw object, set `sourceMap.asObject` to `true`. ## Parse options - `bare_returns` (default `false`) -- support top level `return` statements - `ecma` (default: `2017`) -- specify one of `5`, `2015`, `2016` or `2017`. Note: this setting is not presently enforced except for ES8 optional trailing commas in function parameter lists and calls with `ecma` `2017`. - `html5_comments` (default `true`) - `shebang` (default `true`) -- support `#!command` as the first line ## Compress options - `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. - `arrows` (default: `true`) -- Class and object literal methods are converted will also be converted to arrow expressions if the resultant code is shorter: `m(){return x}` becomes `m:()=>x`. To do this to regular ES5 functions which don't use `this` or `arguments`, see `unsafe_arrows`. - `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 - `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 `2015` 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 function 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` (legacy option, safely ignored for backwards compatibility). - `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 function calls 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 `2015` 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_symbols` (default: `false`) -- removes keys from native Symbol declarations, e.g `Symbol("kDog")` becomes `Symbol()`. - `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. - `true` -- Quoted property names are automatically reserved and any unquoted property names will not be mangled. - `"strict"` -- Advanced, all unquoted property names are mangled unless explicitly reserved. - `regex` (default: `null`) — Pass a [RegExp literal or pattern string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) to only mangle property matching the regular expression. - `reserved` (default: `[]`) — Do not mangle property names listed in the `reserved` array. - `undeclared` (default: `false`) - Mangle those names when they are accessed as properties of known top level variables but their declarations are never found in input code. May be useful when only minifying parts of a project. See [#397](https://github.com/terser/terser/issues/397) for more details. ## 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 `"some"`) -- by default it keeps JSDoc-style comments that contain "@license" or "@preserve", pass `true` or `"all"` to preserve all comments, `false` to omit comments in the output, a regular expression string (e.g. `/^!/`) or a function. - `ecma` (default `5`) -- set output printing mode. Set `ecma` to `2015` 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_numbers` (default `false`) -- keep number literals as it was in original code (disables optimizations like converting `1000000` into `1e6`) - `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 - `preserve_annotations` -- (default `false`) -- Preserve [Terser annotations](#annotations) in the output. - `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. - `wrap_func_args` (default `true`) -- pass `false` if you do not want to wrap function expressions that are passed as arguments, in parenthesis. See [OptimizeJS](https://github.com/nolanlawson/optimize-js) 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. ``` ### Annotations Annotations in Terser are a way to tell it to treat a certain function call differently. The following annotations are available: * `/*@__INLINE__*/` - forces a function to be inlined somewhere. * `/*@__NOINLINE__*/` - Makes sure the called function is not inlined into the call site. * `/*@__PURE__*/` - Marks a function call as pure. That means, it can safely be dropped. You can use either a `@` sign at the start, or a `#`. Here are some examples on how to use them: ```javascript /*@__INLINE__*/ function_always_inlined_here() /*#__NOINLINE__*/ function_cant_be_inlined_into_here() const x = /*#__PURE__*/i_am_dropped_if_x_is_not_used() ``` ### 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 | - | | terser@3.7.5 mangle=false, compress=false | 316,600 | 85,245 | 0.82 | | terser@3.7.5 mangle=true, compress=false | 220,216 | 72,730 | 1.45 | | terser@3.7.5 mangle=true, compress=true | 212,046 | 70,954 | 5.87 | | babili@0.1.4 | 210,713 | 72,140 | 12.64 | | babel-minify@0.4.3 | 210,321 | 72,242 | 48.67 | | babel-minify@0.5.0-alpha.01eac1c3 | 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()`). - `document.all` is not `== null` - Assigning properties to a class doesn't have side effects and does not throw. ### 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/fabiosantoscode"><img src="https://c5.patreon.com/external/logo/become_a_patron_button@2x.png" alt="patron" width="100px" height="auto"></a>. Check out [PATRONS.md](https://github.com/terser/terser/blob/master/PATRONS.md) for our first-tier patrons. These are the second-tier patrons. Great thanks for your support! * 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) ## Contributors ### Code Contributors This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)]. <a href="https://github.com/terser/terser/graphs/contributors"><img src="https://opencollective.com/terser/contributors.svg?width=890&button=false" /></a> ### Financial Contributors Become a financial contributor and help us sustain our community. [[Contribute](https://opencollective.com/terser/contribute)] #### Individuals <a href="https://opencollective.com/terser"><img src="https://opencollective.com/terser/individuals.svg?width=890"></a> #### Organizations Support this project with your organization. Your logo will show up here with a link to your website. [[Contribute](https://opencollective.com/terser/contribute)] <a href="https://opencollective.com/terser/organization/0/website"><img src="https://opencollective.com/terser/organization/0/avatar.svg"></a> <a href="https://opencollective.com/terser/organization/1/website"><img src="https://opencollective.com/terser/organization/1/avatar.svg"></a> <a href="https://opencollective.com/terser/organization/2/website"><img src="https://opencollective.com/terser/organization/2/avatar.svg"></a> <a href="https://opencollective.com/terser/organization/3/website"><img src="https://opencollective.com/terser/organization/3/avatar.svg"></a> <a href="https://opencollective.com/terser/organization/4/website"><img src="https://opencollective.com/terser/organization/4/avatar.svg"></a> <a href="https://opencollective.com/terser/organization/5/website"><img src="https://opencollective.com/terser/organization/5/avatar.svg"></a> <a href="https://opencollective.com/terser/organization/6/website"><img src="https://opencollective.com/terser/organization/6/avatar.svg"></a> <a href="https://opencollective.com/terser/organization/7/website"><img src="https://opencollective.com/terser/organization/7/avatar.svg"></a> <a href="https://opencollective.com/terser/organization/8/website"><img src="https://opencollective.com/terser/organization/8/avatar.svg"></a> <a href="https://opencollective.com/terser/organization/9/website"><img src="https://opencollective.com/terser/organization/9/avatar.svg"></a> # unquote Remove wrapping quotes from a string. Returns an empty string if the first arg is falsey. ## Installation ``` npm install unquote ``` ## Usage Example ```js var unquote = require('unquote') unquote('"hello, world"') // 'hello, world' unquote('\'hello, world\'') // 'hello, world' ``` ## Running Tests ``` npm test ``` ## License ([The MIT License](LICENSE)) Copyright 2017 Cameron Lakenen [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. ### `.canonicalizedDomain()` ### `.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. ### `.removeAllCookies(cb(err))` Removes all cookies from the jar. This is a new backwards-compatible feature of `tough-cookie` version 2.5, so not all Stores will implement it efficiently. For Stores that do not implement `removeAllCookies`, the fallback is to call `removeCookie` after `getAllCookies`. If `getAllCookies` fails or isn't implemented in the Store, that error is returned. If one or more of the `removeCookie` calls fail, only the first error is returned. ### `.removeAllCookiesSync()` Sync version of `.removeAllCookies()` ## 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.removeAllCookies(cb(err))` _Optional_. Removes all cookies from the store. Pass an error if one or more cookies can't be removed. **Note**: New method as of `tough-cookie` version 2.5, so not all Stores will implement this, plus some stores may choose not to implement this. ### `store.getAllCookies(cb(err, cookies))` _Optional_. 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. **Note**: not all Stores can implement this due to technical limitations, so it is optional. ## 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. Supports serialization, `getAllCookies`, and `removeAllCookies`. ## 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: 'tough-cookie@1.x.y', // 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 BSD-3-Clause: ```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. ``` # 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 # <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/ # 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. # 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._ <img align="right" width="111" height="111" alt="CSSTree logo" src="https://cloud.githubusercontent.com/assets/270491/19243723/6f9136c6-8f21-11e6-82ac-eeeee4c6c452.png"/> # CSSTree [![NPM version](https://img.shields.io/npm/v/css-tree.svg)](https://www.npmjs.com/package/css-tree) [![Build Status](https://travis-ci.org/csstree/csstree.svg?branch=master)](https://travis-ci.org/csstree/csstree) [![Coverage Status](https://coveralls.io/repos/github/csstree/csstree/badge.svg?branch=master)](https://coveralls.io/github/csstree/csstree?branch=master) [![NPM Downloads](https://img.shields.io/npm/dm/css-tree.svg)](https://www.npmjs.com/package/css-tree) [![Twitter](https://img.shields.io/badge/Twitter-@csstree-blue.svg)](https://twitter.com/csstree) CSSTree is a tool set to work with CSS, including [fast](https://github.com/postcss/benchmark) detailed parser (string->AST), walker (AST traversal), generator (AST->string) and lexer (validation and matching) based on knowledge of spec and browser implementations. The main goal is to be efficient and W3C spec compliant, with focus on CSS analyzing and source-to-source transforming tasks. > NOTE: The project is in alpha stage since some parts need further improvements, AST format and API are subjects to change. However it's stable enough and used by packages like [CSSO](https://github.com/css/csso) (CSS minifier) and [SVGO](https://github.com/svg/svgo) (SVG optimizer) in production. ## Features - **Detailed parsing with an adjustable level of detail** By default CSSTree parses CSS as detailed as possible, i.e. each single logical part is representing with its own AST node (see [AST format](docs/ast.md) for all possible node types). The parsing detail level can be changed through [parser options](docs/parsing.md#parsesource-options), for example, you can disable parsing of selectors or declaration values for component parts. - **Tolerant to errors by design** Parser behaves as [spec says](https://www.w3.org/TR/css-syntax-3/#error-handling): "When errors occur in CSS, the parser attempts to recover gracefully, throwing away only the minimum amount of content before returning to parsing as normal". The only thing the parser departs from the specification is that it doesn't throw away bad content, but wraps it in a special node type (`Raw`) that allows processing it later. - **Fast and efficient** CSSTree is created with focus on performance and effective memory consumption. Therefore it's [one of the fastest CSS parsers](https://github.com/postcss/benchmark) at the moment. - **Syntax validation** The build-in lexer can test CSS against syntaxes defined by W3C. CSSTree uses [mdn/data](https://github.com/mdn/data/) as a basis for lexer's dictionaries and extends it with vendor specific and legacy syntaxes. Lexer can only check the declaration values currently, but this feature will be extended to other parts of the CSS in the future. ## Docs - [AST format](docs/ast.md) - [Parsing CSS into AST](docs/parsing.md) - [Generate CSS from AST](docs/generate.md) - [AST traversal](docs/traversal.md) - [Utils for AST](docs/utils.md) - [Working with definition syntax](docs/definition-syntax.md) ## Tools * [AST Explorer](https://astexplorer.net/#/gist/244e2fb4da940df52bf0f4b94277db44/e79aff44611020b22cfd9708f3a99ce09b7d67a8) – explore CSSTree AST format with zero setup * [CSS syntax reference](https://csstree.github.io/docs/syntax.html) * [CSS syntax validator](https://csstree.github.io/docs/validator.html) ## Related projects * [csstree-validator](https://github.com/csstree/validator) – NPM package to validate CSS * [stylelint-csstree-validator](https://github.com/csstree/stylelint-validator) – plugin for stylelint to validate CSS * [Grunt plugin](https://github.com/sergejmueller/grunt-csstree-validator) * [Gulp plugin](https://github.com/csstree/gulp-csstree) * [Sublime plugin](https://github.com/csstree/SublimeLinter-contrib-csstree) * [VS Code plugin](https://github.com/csstree/vscode-plugin) * [Atom plugin](https://github.com/csstree/atom-plugin) ## Usage Install with npm: ``` > npm install css-tree ``` Basic usage: ```js var csstree = require('css-tree'); // parse CSS to AST var ast = csstree.parse('.example { world: "!" }'); // traverse AST and modify it csstree.walk(ast, function(node) { if (node.type === 'ClassSelector' && node.name === 'example') { node.name = 'hello'; } }); // generate CSS from AST console.log(csstree.generate(ast)); // .hello{world:"!"} ``` Syntax matching: ```js // parse CSS to AST as a declaration value var ast = csstree.parse('red 1px solid', { context: 'value' }); // march to syntax of `border` property var matchResult = csstree.lexer.matchProperty('border', ast); // check first value node is a <color> console.log(matchResult.isType(ast.children.first(), 'color')); // true // get a type list matched to a node console.log(matchResult.getTrace(ast.children.first())); // [ { type: 'Property', name: 'border' }, // { type: 'Type', name: 'color' }, // { type: 'Type', name: 'named-color' }, // { type: 'Keyword', name: 'red' } ] ``` ## Top level API ![API map](https://cdn.rawgit.com/csstree/csstree/master/docs/api-map.svg) ## 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/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. # 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. # 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 # 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 [![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). # 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** # 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._ 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')` # 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.) # 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() ``` # cssnano-preset-default > Safe defaults for cssnano which require minimal configuration. ## Table of Contents - [Overview](#overview) - [Usage](#usage) - [Install](#install) - [Configuration](#configuration) - [Plugins](#plugins) - [cssnano-util-raw-cache](#cssnano-util-raw-cache) - [postcss-calc (external)](#postcss-calc-external) - [postcss-colormin](#postcss-colormin) - [postcss-convert-values](#postcss-convert-values) - [postcss-discard-comments](#postcss-discard-comments) - [postcss-discard-duplicates](#postcss-discard-duplicates) - [postcss-discard-empty](#postcss-discard-empty) - [postcss-discard-overridden](#postcss-discard-overridden) - [postcss-merge-longhand](#postcss-merge-longhand) - [postcss-merge-rules](#postcss-merge-rules) - [postcss-minify-font-values](#postcss-minify-font-values) - [postcss-minify-gradients](#postcss-minify-gradients) - [postcss-minify-params](#postcss-minify-params) - [postcss-minify-selectors](#postcss-minify-selectors) - [postcss-normalize-charset](#postcss-normalize-charset) - [postcss-normalize-display-values](#postcss-normalize-display-values) - [postcss-normalize-positions](#postcss-normalize-positions) - [postcss-normalize-repeat-style](#postcss-normalize-repeat-style) - [postcss-normalize-string](#postcss-normalize-string) - [postcss-normalize-timing-functions](#postcss-normalize-timing-functions) - [postcss-normalize-unicode](#postcss-normalize-unicode) - [postcss-normalize-url](#postcss-normalize-url) - [postcss-normalize-whitespace](#postcss-normalize-whitespace) - [postcss-ordered-values](#postcss-ordered-values) - [postcss-reduce-initial](#postcss-reduce-initial) - [postcss-reduce-transforms](#postcss-reduce-transforms) - [postcss-svgo](#postcss-svgo) - [postcss-unique-selectors](#postcss-unique-selectors) - [Contributors](#contributors) - [License](#license) ## Overview This default preset for cssnano only includes transforms that make no assumptions about your CSS other than what is passed in. In previous iterations of cssnano, assumptions were made about your CSS which caused output to look different in certain use cases, but not others. These transforms have been moved from the defaults to other presets, to make this preset require only minimal configuration. ## Usage ### Install Note that this preset comes bundled with cssnano _by default_, so you don't need to install it separately. ### Configuration If you would like to use the default configuration, then you don't need to add anything to your `package.json`. But should you wish to customise this, you can pass an array with the second parameter as the options object to use. For example, to remove all comments: ```diff { "name": "awesome-application", + "cssnano": { + "preset": [ + "default", + {"discardComments": {"removeAll": true}} + ] + } } ``` Depending on your usage, the JSON configuration might not work for you, such as in cases where you would like to use options with customisable function parameters. For this use case, we recommend a `cssnano.config.js` at the same location as your `package.json`. You can then load a preset and export it with your custom parameters: ```js const defaultPreset = require('cssnano-preset-default'); module.exports = defaultPreset({ discardComments: { remove: comment => comment[0] === "@" } }); ``` Note that you may wish to publish your own preset to npm for reusability, should it differ a lot from this one. This is highly encouraged! ## Plugins ### [`css-declaration-sorter`](https://github.com/Siilwyn/css-declaration-sorter) (external) > Sorts CSS declarations fast and automatically in a certain order. This plugin is loaded with its default configuration. ### [`cssnano-util-raw-cache`](https://github.com/cssnano/cssnano/tree/master/packages/cssnano-util-raw-cache) > Manages the raw value formatting for generated AST nodes. This plugin is loaded with its default configuration. ### [`postcss-calc`](https://github.com/postcss/postcss-calc) (external) > PostCSS plugin to reduce calc() This plugin is loaded with its default configuration. ### [`postcss-colormin`](https://github.com/cssnano/cssnano/tree/master/packages/postcss-colormin) > Minify colors in your CSS files with PostCSS. This plugin is loaded with its default configuration. ### [`postcss-convert-values`](https://github.com/cssnano/cssnano/tree/master/packages/postcss-convert-values) > Convert values with PostCSS (e.g. ms -> s) This plugin is loaded with the following configuration: ```js { length: false } ``` ### [`postcss-discard-comments`](https://github.com/cssnano/cssnano/tree/master/packages/postcss-discard-comments) > Discard comments in your CSS files with PostCSS. This plugin is loaded with its default configuration. ### [`postcss-discard-duplicates`](https://github.com/cssnano/cssnano/tree/master/packages/postcss-discard-duplicates) > Discard duplicate rules in your CSS files with PostCSS. This plugin is loaded with its default configuration. ### [`postcss-discard-empty`](https://github.com/cssnano/cssnano/tree/master/packages/postcss-discard-empty) > Discard empty rules and values with PostCSS. This plugin is loaded with its default configuration. ### [`postcss-discard-overridden`](https://github.com/cssnano/cssnano/tree/master/packages/postcss-discard-overridden) > PostCSS plugin to discard overridden @keyframes or @counter-style. This plugin is loaded with its default configuration. ### [`postcss-merge-longhand`](https://github.com/cssnano/cssnano/tree/master/packages/postcss-merge-longhand) > Merge longhand properties into shorthand with PostCSS. This plugin is loaded with its default configuration. ### [`postcss-merge-rules`](https://github.com/cssnano/cssnano/tree/master/packages/postcss-merge-rules) > Merge CSS rules with PostCSS. This plugin is loaded with its default configuration. ### [`postcss-minify-font-values`](https://github.com/cssnano/cssnano/tree/master/packages/postcss-minify-font-values) > Minify font declarations with PostCSS This plugin is loaded with its default configuration. ### [`postcss-minify-gradients`](https://github.com/cssnano/cssnano/tree/master/packages/postcss-minify-gradients) > Minify gradient parameters with PostCSS. This plugin is loaded with its default configuration. ### [`postcss-minify-params`](https://github.com/cssnano/cssnano/tree/master/packages/postcss-minify-params) > Minify at-rule params with PostCSS This plugin is loaded with its default configuration. ### [`postcss-minify-selectors`](https://github.com/cssnano/cssnano/tree/master/packages/postcss-minify-selectors) > Minify selectors with PostCSS. This plugin is loaded with its default configuration. ### [`postcss-normalize-charset`](https://github.com/cssnano/cssnano/tree/master/packages/postcss-normalize-charset) > Add necessary or remove extra charset with PostCSS This plugin is loaded with the following configuration: ```js { add: false } ``` ### [`postcss-normalize-display-values`](https://github.com/cssnano/cssnano/tree/master/packages/postcss-normalize-display-values) > Normalize multiple value display syntaxes into single values. This plugin is loaded with its default configuration. ### [`postcss-normalize-positions`](https://github.com/cssnano/cssnano/tree/master/packages/postcss-normalize-positions) > Normalize keyword values for position into length values. This plugin is loaded with its default configuration. ### [`postcss-normalize-repeat-style`](https://github.com/cssnano/cssnano/tree/master/packages/postcss-normalize-repeat-style) > Convert two value syntax for repeat-style into one value. This plugin is loaded with its default configuration. ### [`postcss-normalize-string`](https://github.com/cssnano/cssnano/tree/master/packages/postcss-normalize-string) > Normalize wrapping quotes for CSS string literals. This plugin is loaded with its default configuration. ### [`postcss-normalize-timing-functions`](https://github.com/cssnano/cssnano/tree/master/packages/postcss-normalize-timing-functions) > Normalize CSS animation/transition timing functions. This plugin is loaded with its default configuration. ### [`postcss-normalize-unicode`](https://github.com/cssnano/cssnano/tree/master/packages/postcss-normalize-unicode) > Normalize unicode-range descriptors, and can convert to wildcard ranges. This plugin is loaded with its default configuration. ### [`postcss-normalize-url`](https://github.com/cssnano/cssnano/tree/master/packages/postcss-normalize-url) > Normalize URLs with PostCSS This plugin is loaded with its default configuration. ### [`postcss-normalize-whitespace`](https://github.com/cssnano/cssnano/tree/master/packages/postcss-normalize-whitespace) > Trim whitespace inside and around CSS rules & declarations. This plugin is loaded with its default configuration. ### [`postcss-ordered-values`](https://github.com/cssnano/cssnano/tree/master/packages/postcss-ordered-values) > Ensure values are ordered consistently in your CSS. This plugin is loaded with its default configuration. ### [`postcss-reduce-initial`](https://github.com/cssnano/cssnano/tree/master/packages/postcss-reduce-initial) > Reduce initial definitions to the actual initial value, where possible. This plugin is loaded with its default configuration. ### [`postcss-reduce-transforms`](https://github.com/cssnano/cssnano/tree/master/packages/postcss-reduce-transforms) > Reduce transform functions with PostCSS. This plugin is loaded with its default configuration. ### [`postcss-svgo`](https://github.com/cssnano/cssnano/tree/master/packages/postcss-svgo) > Optimise inline SVG with PostCSS. This plugin is loaded with its default configuration. ### [`postcss-unique-selectors`](https://github.com/cssnano/cssnano/tree/master/packages/postcss-unique-selectors) > Ensure CSS selectors are unique. This plugin is loaded with its default configuration. ## Contributors See [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md). ## License MIT © [Ben Briggs](http://beneb.info) # 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/LTS # 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] } ``` <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._ # 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. # rgba-regex [![Build Status](https://secure.travis-ci.org/regexps/rgba-regex.png?branch=master)](https://travis-ci.org/regexps/rgba-regex) Regex for matching RGBA color strings. ## Installation ```bash npm install --save rgba-regex ``` ## Usage ```javascript var rgbaRegex = require('rgba-regex'); rgbaRegex({ exact: true }).test('rgba(12, 34, 56, .8)'); // => true rgbaRegex({ exact: true }).test('unicorns'); // -> false rgbaRegex({ exact: true }).test('rgba(,,,)'); // => false rgbaRegex().exec('rgba(12, 34, 56, .8)'); // => [ // '12', // '34', // '56', // '.8' // index: 0, // input: 'rgba(12,34,56, .8)' // ] 'rgba(12, 34, 56, .8) cats and dogs'.match(rgbaRegex()); // = ['rgba(12, 34, 56, .8)'] ``` ## License MIT ## 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. Create new Pull Request Crafted with <3 by John Otander ([@4lpine](https://twitter.com/4lpine)). *** > This package was initially generated with [yeoman](http://yeoman.io) and the [p generator](https://github.com/johnotander/generator-p.git). # HAR Validator [![license][license-img]][license-url] [![version][npm-img]][npm-url] [![super linter][super-linter-img]][super-linter-url] [![test][test-img]][test-url] [![release][release-img]][release-url] [license-url]: LICENSE [license-img]: https://badgen.net/github/license/ahmadnassri/node-har-validator [npm-url]: https://www.npmjs.com/package/har-validator [npm-img]: https://badgen.net/npm/v/har-validator [super-linter-url]: https://github.com/ahmadnassri/node-har-validator/actions?query=workflow%3Asuper-linter [super-linter-img]: https://github.com/ahmadnassri/node-har-validator/workflows/super-linter/badge.svg [test-url]: https://github.com/ahmadnassri/node-har-validator/actions?query=workflow%3Atest [test-img]: https://github.com/ahmadnassri/node-har-validator/workflows/test/badge.svg [release-url]: https://github.com/ahmadnassri/node-har-validator/actions?query=workflow%3Arelease [release-img]: https://github.com/ahmadnassri/node-har-validator/workflows/release/badge.svg > 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)_ # 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> # 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."`) If we are dealing with multiple JavaScript realms (such as those created using Node.js' [vm](https://nodejs.org/api/vm.html) module or the HTML `iframe` element), and exceptions from another realm need to be thrown, one can supply an object option `globals` containing the following properties: ```js { globals: { Number, String, TypeError } } ``` Those specific functions will be used when throwing exceptions. 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) - [Buffer source types](https://heycam.github.io/webidl/#es-buffer-source-types), which can additionally be provided with the boolean option `{ allowShared }` as a second parameter Additionally, for convenience, the following derived type definitions are implemented: - [`ArrayBufferView`](https://heycam.github.io/webidl/#ArrayBufferView), which can additionally be provided with the boolean option `{ allowShared }` as a second parameter - [`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. Conversions are still accurate as we make use of BigInt in the conversion process, but in the case of `unsigned long long` we simply cannot represent some possible output values in JavaScript. For example, converting the JavaScript number `-1` to a Web IDL `unsigned long long` is supposed to produce the Web IDL value `18446744073709551615`. Since we are representing our Web IDL values in JavaScript, we can't represent `18446744073709551615`, so we instead the best we could do is `18446744073709551616` as the output. To mitigate this, we could return the raw BigInt value from the conversion function, but right now it is not implemented. If your use case requires such precision, [file an issue](https://github.com/jsdom/webidl-conversions/issues/new). On the other hand, `long long` conversion is always accurate, since the input value can never be more precise than the output value. ### A note on `BufferSource` types All of the `BufferSource` types will throw when the relevant `ArrayBuffer` has been detached. This technically is not part of the [specified conversion algorithm](https://heycam.github.io/webidl/#es-buffer-source-types), but instead part of the [getting a reference/getting a copy](https://heycam.github.io/webidl/#ref-for-dfn-get-buffer-source-reference%E2%91%A0) algorithms. We've consolidated them here for convenience and ease of implementation, but if there is a need to separate them in the future, please open an issue so we can investigate. ## 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/jsdom/jsdom) project. <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 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) ## 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: 'joe.bloggs@example.com' } ``` `$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 6.0.0](https://github.com/ajv-validator/ajv/releases/tag/v6.0.0). [Version 5.0.0](https://github.com/ajv-validator/ajv/releases/tag/5.0.0). [Version 4.0.0](https://github.com/ajv-validator/ajv/releases/tag/4.0.0). [Version 3.0.0](https://github.com/ajv-validator/ajv/releases/tag/3.0.0). [Version 2.0.0](https://github.com/ajv-validator/ajv/releases/tag/2.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 ajv.validator@gmail.com - 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) 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 ## 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 iconv@2.1.4 iconv-lite@0.4.7 ---------------------------------------------------------- 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 git@github.com: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 ``` # [postcss][postcss]-normalize-repeat-style > Normalize repeat styles with PostCSS. ## Install With [npm](https://npmjs.org/package/postcss-normalize-repeat-style) do: ``` npm install postcss-normalize-repeat-style --save ``` ## Example ### Input ```css h1 { background: url(image.jpg) repeat no-repeat } ``` ### Output ```css h1 { background: url(image.jpg) repeat-x } ``` ## Usage See the [PostCSS documentation](https://github.com/postcss/postcss#usage) for examples for your environment. ## Contributors See [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md). ## License MIT © [Ben Briggs](http://beneb.info) [postcss]: https://github.com/postcss/postcss # 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). # 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) ``` # PostCSS [![Travis Build Status][travis-img]][travis] [![AppVeyor Build Status][appveyor-img]][appveyor] [![Gitter][chat-img]][chat] <img align="right" width="95" height="95" title="Philosopher’s stone, logo of PostCSS" src="http://postcss.github.io/postcss/logo.svg"> [appveyor-img]: https://img.shields.io/appveyor/ci/ai/postcss.svg?label=windows [travis-img]: https://img.shields.io/travis/postcss/postcss.svg?label=unix [chat-img]: https://img.shields.io/badge/Gitter-Join_the_PostCSS_chat-brightgreen.svg [appveyor]: https://ci.appveyor.com/project/ai/postcss [travis]: https://travis-ci.org/postcss/postcss [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. Twitter account: [@postcss](https://twitter.com/postcss). VK.com page: [postcss](https://vk.com/postcss). Support / Discussion: [Gitter](https://gitter.im/postcss/postcss). For PostCSS commercial support (consulting, improving the front-end culture of your company, PostCSS plugins), contact [Evil Martians](https://evilmartians.com/?utm_source=postcss) at <surrender@evilmartians.com>. [Autoprefixer]: https://github.com/postcss/autoprefixer <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-cssnext`] allows you to use future CSS features today (includes `autoprefixer`). * [`postcss-image-set-polyfill`] emulates [`image-set`] function logic for all browsers ### 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 [`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-cssnext`]: http://cssnext.io [`postcss-image-set-polyfill`]: https://github.com/SuperOl3g/postcss-image-set-polyfill [`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 [`image-set`]: https://drafts.csswg.org/css-images-3/#image-set-notation ## 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-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. [`sugarss`]: https://github.com/postcss/sugarss [`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-less-engine`]: https://github.com/Crunch/postcss-less [`postcss-js`]: https://github.com/postcss/postcss-js [`postcss-safe-parser`]: https://github.com/postcss/postcss-safe-parser [`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 ### Gulp Use [`gulp-postcss`] and [`gulp-sourcemaps`]. ```js gulp.task('css', function () { var postcss = require('gulp-postcss'); var 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/ [webpack]: https://webpack.github.io/ [CSS-in-JS]: https://github.com/MicheleBertoli/css-in-js ### 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) * **Fly**: [`fly-postcss`](https://github.com/postcss/fly-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 fs = require('fs'); const postcss = require('postcss'); const precss = require('precss'); const autoprefixer = require('autoprefixer'); 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); if ( result.map ) fs.writeFile('dest/app.css.map', result.map); }); }); ``` 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 ## 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/ 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> # serialize-to-js > serialize objects to javascript [![NPM version](https://badge.fury.io/js/serialize-to-js.svg)](https://www.npmjs.com/package/serialize-to-js/) [![Build Status](https://secure.travis-ci.org/commenthol/serialize-to-js.svg?branch=master)](https://travis-ci.org/commenthol/serialize-to-js) Serialize objects into a string while checking circular structures and respecting references. The following Objects are supported - String - Number - Boolean - Object - Array - RegExp - Error - Date - Buffer - Int8Array, Uint8Array, Uint8ClampedArray - Int16Array, Uint16Array - Int32Array, Uint32Array, Float32Array - Float64Array - Set - Map ## Table of Contents <!-- !toc (minlevel=2 omit="Table of Contents") --> * [Methods](#methods) * [serialize](#serialize) * [Contribution and License Agreement](#contribution-and-license-agreement) * [License](#license) <!-- toc! --> ## Methods ### serialize `serialize(source, opts, opts.ignoreCircular, opts.reference)` serializes an object to javascript #### Example - serializing regex, date, buffer, ... ```js const serialize = require('serialize-to-js') const obj = { str: '<script>var a = 0 > 1</script>', num: 3.1415, bool: true, nil: null, undef: undefined, obj: { foo: 'bar' }, arr: [1, '2'], regexp: /^test?$/, date: new Date(), buffer: new Buffer('data'), set: new Set([1, 2, 3]), map: new Map([['a': 1],['b': 2]]) } console.log(serialize(obj)) //> '{str: "\u003Cscript\u003Evar a = 0 \u003E 1\u003C\u002Fscript\u003E", //> num: 3.1415, bool: true, nil: null, undef: undefined, //> obj: {foo: "bar"}, arr: [1, "2"], regexp: new RegExp("^test?$", ""), //> date: new Date("2019-12-29T10:37:36.613Z"), //> buffer: Buffer.from("ZGF0YQ==", "base64"), set: new Set([1, 2, 3]), //> map: new Map([["a", 1], ["b", 2]])}' ``` #### Example - serializing while respecting references ```js var serialize = require('serialize-to-js') var obj = { object: { regexp: /^test?$/ } }; obj.reference = obj.object; var opts = { reference: true }; console.log(serialize(obj, opts)); //> {object: {regexp: /^test?$/}} console.log(opts.references); //> [ [ '.reference', '.object' ] ] ``` **Parameters** **source**: `Object | Array | function | Any`, source to serialize **opts**: `Object`, options **opts.ignoreCircular**: `Boolean`, ignore circular objects **opts.reference**: `Boolean`, reference instead of a copy (requires post-processing of opts.references) **opts.unsafe**: `Boolean`, do not escape chars `<>/` **Returns**: `String`, serialized representation of `source` ## Contribution and License Agreement If you contribute code to this project, you are implicitly allowing your code to be distributed under the MIT license. You are also implicitly verifying that all code is your original work or correctly attributed with the source of its origin and licence. ## License Copyright (c) 2016- commenthol (MIT License) See [LICENSE][] for more info. [LICENSE]: ./LICENSE # babel-plugin-jest-hoist Babel plugin to hoist `jest.disableAutomock`, `jest.enableAutomock`, `jest.unmock`, `jest.mock`, calls above `import` statements. This plugin is automatically included when using [babel-jest](https://github.com/facebook/jest/tree/master/packages/babel-jest). ## Installation ```sh $ yarn add --dev babel-plugin-jest-hoist ``` ## Usage ### Via `babel.config.js` (Recommended) ```js module.exports = { plugins: ['jest-hoist'], }; ``` ### Via CLI ```sh $ babel --plugins jest-hoist script.js ``` ### Via Node API ```javascript require('@babel/core').transform('code', { plugins: ['jest-hoist'], }); ``` # babel-plugin-istanbul [![Greenkeeper badge](https://badges.greenkeeper.io/istanbuljs/babel-plugin-istanbul.svg)](https://greenkeeper.io/) [![Build Status](https://travis-ci.org/istanbuljs/babel-plugin-istanbul.svg?branch=master)](https://travis-ci.org/istanbuljs/babel-plugin-istanbul) [![Coverage Status](https://coveralls.io/repos/github/istanbuljs/babel-plugin-istanbul/badge.svg?branch=master)](https://coveralls.io/github/istanbuljs/babel-plugin-istanbul?branch=master) [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) [![community slack](http://devtoolscommunity.herokuapp.com/badge.svg)](http://devtoolscommunity.herokuapp.com) _Having problems? want to contribute? join our [community slack](http://devtoolscommunity.herokuapp.com)_. A Babel plugin that instruments your code with Istanbul coverage. It can instantly be used with [karma-coverage](https://github.com/karma-runner/karma-coverage) and mocha on Node.js (through [nyc](https://github.com/bcoe/nyc)). __Note:__ This plugin does not generate any report or save any data to any file; it only adds instrumenting code to your JavaScript source code. To integrate with testing tools, please see the [Integrations](#integrations) section. ## Usage Install it: ``` npm install --save-dev babel-plugin-istanbul ``` Add it to `.babelrc` in test mode: ```js { "env": { "test": { "plugins": [ "istanbul" ] } } } ``` Optionally, use [cross-env](https://www.npmjs.com/package/cross-env) to set `NODE_ENV=test`: ```json { "scripts": { "test": "cross-env NODE_ENV=test nyc --reporter=lcov --reporter=text mocha test/*.js" } } ``` ## Integrations ### karma It _just works_ with Karma. First, make sure that the code is already transpiled by Babel (either using `karma-babel-preprocessor`, `karma-webpack`, or `karma-browserify`). Then, simply set up [karma-coverage](https://github.com/karma-runner/karma-coverage) according to the docs, but __don’t add the `coverage` preprocessor.__ This plugin has already instrumented your code, and Karma should pick it up automatically. It has been tested with [bemusic/bemuse](https://codecov.io/github/bemusic/bemuse) project, which contains ~2400 statements. ### mocha on node.js (through nyc) Configure Mocha to transpile JavaScript code using Babel, then you can run your tests with [`nyc`](https://github.com/bcoe/nyc), which will collect all the coverage report. babel-plugin-istanbul respects the `include`/`exclude` configuration options from nyc, but you also need to __configure NYC not to instrument your code__ by adding these settings in your `package.json`: ```js "nyc": { "sourceMap": false, "instrument": false }, ``` ## Ignoring files You don't want to cover your test files as this will skew your coverage results. You can configure this by providing plugin options matching nyc's [`exclude`/`include` rules](https://github.com/bcoe/nyc#excluding-files): ```json { "env": { "test": { "plugins": [ ["istanbul", { "exclude": [ "**/*.spec.js" ] }] ] } } } ``` If you don't provide options in your Babel config, the plugin will look for `exclude`/`include` config under an `"nyc"` key in `package.json`. You can also use [istanbul's ignore hints](https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes) to specify specific lines of code to skip instrumenting. ## Source Maps By default, this plugin will pick up inline source maps and attach them to the instrumented code such that code coverage can be remapped back to the original source, even for multi-step build processes. This can be memory intensive. Set `useInlineSourceMaps` to prevent this behavior. ```json { "env": { "test": { "plugins": [ ["istanbul", { "useInlineSourceMaps": false }] ] } } } ``` If you're instrumenting code programatically, you can pass a source map explicitly. ```js import babelPluginIstanbul from 'babel-plugin-istanbul'; function instrument(sourceCode, sourceMap, fileName) { return babel.transform(sourceCode, { filename, plugins: [ [babelPluginIstanbul, { inputSourceMap: sourceMap }] ] }) } ``` ## Credit where credit is due The approach used in `babel-plugin-istanbul` was inspired by [Thai Pangsakulyanont](https://github.com/dtinth)'s original library [`babel-plugin-__coverage__`](https://github.com/dtinth/babel-plugin-__coverage__). ## `babel-plugin-istanbul` for enterprise Available as part of the Tidelift Subscription. The maintainers of `babel-plugin-istanbul` 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-babel-plugin-istanbul?utm_source=npm-babel-plugin-istanbul&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) 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) # 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. 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 ``` # 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', new Buffer("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 ``` # 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 ``` ### 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 [![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`. # node-libs-browser The node core libs for in-browser usage. NOTE: This library is deprecated and won't accept Pull Requests that include Breaking Changes or new Features. Only bugfixes are accepted. [![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/buffer@4.x because feross/buffer@5.x 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/punycode.js@1.x because bestiejs/punycode.js@2.x 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 # 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"; ``` ## Building ``` npm install npm build 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. # istanbul-lib-report [![Greenkeeper badge](https://badges.greenkeeper.io/istanbuljs/istanbul-lib-report.svg)](https://greenkeeper.io/) [![Build Status](https://travis-ci.org/istanbuljs/istanbul-lib-report.svg?branch=master)](https://travis-ci.org/istanbuljs/istanbul-lib-report) Core reporting utilities for istanbul. ## Example usage ```js const libReport = require('istanbul-lib-report'); const reports = require('istanbul-reports'); // coverageMap, for instance, obtained from istanbul-lib-coverage const coverageMap; const configWatermarks = { statements: [50, 80], functions: [50, 80], branches: [50, 80], lines: [50, 80] }; // create a context for report generation const context = libReport.createContext({ dir: 'report/output/dir', // The summarizer to default to (may be overridden by some reports) // values can be nested/flat/pkg. Defaults to 'pkg' defaultSummarizer: 'nested', watermarks: configWatermarks, coverageMap, }) // create an instance of the relevant report class, passing the // report name e.g. json/html/html-spa/text const report = reports.create('json', { skipEmpty: configSkipEmpty, skipFull: configSkipFull }) // call execute to synchronously create and write the report to disk report.execute(context) ``` # <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 # 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. <img align="right" width="111" height="111" alt="CSSTree logo" src="https://cloud.githubusercontent.com/assets/270491/19243723/6f9136c6-8f21-11e6-82ac-eeeee4c6c452.png"/> # CSSTree [![NPM version](https://img.shields.io/npm/v/css-tree.svg)](https://www.npmjs.com/package/css-tree) [![Build Status](https://travis-ci.org/csstree/csstree.svg?branch=master)](https://travis-ci.org/csstree/csstree) [![Coverage Status](https://coveralls.io/repos/github/csstree/csstree/badge.svg?branch=master)](https://coveralls.io/github/csstree/csstree?branch=master) [![NPM Downloads](https://img.shields.io/npm/dm/css-tree.svg)](https://www.npmjs.com/package/css-tree) [![Twitter](https://img.shields.io/badge/Twitter-@csstree-blue.svg)](https://twitter.com/csstree) CSSTree is a tool set to work with CSS, including [fast](https://github.com/postcss/benchmark) detailed parser (string->AST), walker (AST traversal), generator (AST->string) and lexer (validation and matching) based on knowledge of spec and browser implementations. The main goal is to be efficient and W3C spec compliant, with focus on CSS analyzing and source-to-source transforming tasks. > NOTE: The project is in alpha stage since some parts need further improvements, AST format and API are subjects to change. However it's stable enough and used by packages like [CSSO](https://github.com/css/csso) (CSS minifier) and [SVGO](https://github.com/svg/svgo) (SVG optimizer) in production. ## Features - **Detailed parsing with an adjustable level of detail** By default CSSTree parses CSS as detailed as possible, i.e. each single logical part is representing with its own AST node (see [AST format](docs/ast.md) for all possible node types). The parsing detail level can be changed through [parser options](docs/parsing.md#parsesource-options), for example, you can disable parsing of selectors or declaration values for component parts. - **Tolerant to errors by design** Parser behaves as [spec says](https://www.w3.org/TR/css-syntax-3/#error-handling): "When errors occur in CSS, the parser attempts to recover gracefully, throwing away only the minimum amount of content before returning to parsing as normal". The only thing the parser departs from the specification is that it doesn't throw away bad content, but wraps it in a special node type (`Raw`) that allows processing it later. - **Fast and efficient** CSSTree is created with focus on performance and effective memory consumption. Therefore it's [one of the fastest CSS parsers](https://github.com/postcss/benchmark) at the moment. - **Syntax validation** The build-in lexer can test CSS against syntaxes defined by W3C. CSSTree uses [mdn/data](https://github.com/mdn/data/) as a basis for lexer's dictionaries and extends it with vendor specific and legacy syntaxes. Lexer can only check the declaration values currently, but this feature will be extended to other parts of the CSS in the future. ## Docs - [AST format](docs/ast.md) - [Parsing CSS into AST](docs/parsing.md) - [Generate CSS from AST](docs/generate.md) - [AST traversal](docs/traversal.md) - [Utils for AST](docs/utils.md) - [Working with definition syntax](docs/definition-syntax.md) ## Tools * [AST Explorer](https://astexplorer.net/#/gist/244e2fb4da940df52bf0f4b94277db44/e79aff44611020b22cfd9708f3a99ce09b7d67a8) – explore CSSTree AST format with zero setup * [CSS syntax reference](https://csstree.github.io/docs/syntax.html) * [CSS syntax validator](https://csstree.github.io/docs/validator.html) ## Related projects * [csstree-validator](https://github.com/csstree/validator) – NPM package to validate CSS * [stylelint-csstree-validator](https://github.com/csstree/stylelint-validator) – plugin for stylelint to validate CSS * [Grunt plugin](https://github.com/sergejmueller/grunt-csstree-validator) * [Gulp plugin](https://github.com/csstree/gulp-csstree) * [Sublime plugin](https://github.com/csstree/SublimeLinter-contrib-csstree) * [VS Code plugin](https://github.com/csstree/vscode-plugin) * [Atom plugin](https://github.com/csstree/atom-plugin) ## Usage Install with npm: ``` > npm install css-tree ``` Basic usage: ```js var csstree = require('css-tree'); // parse CSS to AST var ast = csstree.parse('.example { world: "!" }'); // traverse AST and modify it csstree.walk(ast, function(node) { if (node.type === 'ClassSelector' && node.name === 'example') { node.name = 'hello'; } }); // generate CSS from AST console.log(csstree.generate(ast)); // .hello{world:"!"} ``` Syntax matching: ```js // parse CSS to AST as a declaration value var ast = csstree.parse('red 1px solid', { context: 'value' }); // march to syntax of `border` property var matchResult = csstree.lexer.matchProperty('border', ast); // check first value node is a <color> console.log(matchResult.isType(ast.children.first(), 'color')); // true // get a type list matched to a node console.log(matchResult.getTrace(ast.children.first())); // [ { type: 'Property', name: 'border' }, // { type: 'Type', name: 'color' }, // { type: 'Type', name: 'named-color' }, // { type: 'Keyword', name: 'red' } ] ``` ## Top level API ![API map](https://cdn.rawgit.com/csstree/csstree/master/docs/api-map.svg) ## License MIT # core-util-is The `util.is*` functions introduced in Node v0.12. # 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._ # 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. # is-directory [![NPM version](https://img.shields.io/npm/v/is-directory.svg?style=flat)](https://www.npmjs.com/package/is-directory) [![NPM downloads](https://img.shields.io/npm/dm/is-directory.svg?style=flat)](https://npmjs.org/package/is-directory) [![Build Status](https://img.shields.io/travis/jonschlinkert/is-directory.svg?style=flat)](https://travis-ci.org/jonschlinkert/is-directory) Returns true if a filepath exists on the file system and it's directory. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install is-directory --save ``` ## Usage ```js var isDirectory = require('is-directory'); isDirectory('node_modules', function(err, dir) { if (err) throw err; console.log(dir); //=> true }); isDirectory.sync('README.md'); //=> false ``` ## Related projects You might also be interested in these projects: * [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) * [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://www.npmjs.com/package/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob) * [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) ## Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/is-directory/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/is-directory/blob/master/LICENSE). *** _This file was generated by [verb](https://github.com/verbose/verb), v0.9.0, on May 21, 2016._ # 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"] }); ``` # Array Equal Check if two arrays are equal: ```js var equals = require('array-equal') assert(equals([1, 2, 3], [1, 2, 3])) // => true assert(equals([1, 2, 3], [1, 2, 3, 4])) // => false ``` # 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) # 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._ 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 go half-insane just trying to manage them all, and put it off 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 , "many" : [String, 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: ```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 1000 -fp # unknown opts are ok. { blatzk: 1000, flag: true, pick: true } $ node my-program.js --blatzk true -fp # but they need a value { blatzk: true, 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 --many 1 --many null --many foo { many: ["1", "null", "foo"] } $ node my-program.js --many foo { many: ["foo"] } ``` 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, and numeric values will be interpreted as a number. 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. 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 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. # 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. # 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 # 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 #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 # lines-and-columns Maps lines and columns to character offsets and back. This is useful for parsers and other text processors that deal in character ranges but process text with meaningful lines and columns. ## Install ``` $ npm install [--save] lines-and-columns ``` ## Usage ```js import LinesAndColumns from 'lines-and-columns'; const lines = new LinesAndColumns( `table { border: 0 }`); lines.locationForIndex(9); // { line: 1, column: 1 } lines.indexForLocation({ line: 1, column: 2 }); // 10 ``` ## 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>` ## 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 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;nathan@tootallnate.net&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 # 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;calvin.metcalf@gmail.com&gt; - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 * **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) &lt;mathiasbuus@gmail.com&gt; * **Matteo Collina** ([@mcollina](https://github.com/mcollina)) &lt;matteo.collina@gmail.com&gt; - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E * **Irina Shestak** ([@lrlna](https://github.com/lrlna)) &lt;shestak.irina@gmail.com&gt; * **Yoshua Wyuts** ([@yoshuawuyts](https://github.com/yoshuawuyts)) &lt;yoshuawuyts@gmail.com&gt; [sauce]: https://saucelabs.com # 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). # 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._ # 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;calvin.metcalf@gmail.com&gt; - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 * **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) &lt;mathiasbuus@gmail.com&gt; * **Matteo Collina** ([@mcollina](https://github.com/mcollina)) &lt;matteo.collina@gmail.com&gt; - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E * **Irina Shestak** ([@lrlna](https://github.com/lrlna)) &lt;shestak.irina@gmail.com&gt; * **Yoshua Wyuts** ([@yoshuawuyts](https://github.com/yoshuawuyts)) &lt;yoshuawuyts@gmail.com&gt; [sauce]: https://saucelabs.com # 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> # regenerator-runtime Standalone runtime for [Regenerator](https://github.com/facebook/regenerator)-compiled generator and `async` functions. To import the runtime as a module (recommended), either of the following import styles will work: ```js // CommonJS const regeneratorRuntime = require("regenerator-runtime"); // ECMAScript 2015 import regeneratorRuntime from "regenerator-runtime"; ``` To ensure that `regeneratorRuntime` is defined globally, either of the following styles will work: ```js // CommonJS require("regenerator-runtime/runtime"); // ECMAScript 2015 import "regenerator-runtime/runtime.js"; ``` To get the absolute file system path of `runtime.js`, evaluate the following expression: ```js require("regenerator-runtime/path").path ``` # postcss-minify-font-values [![Build Status][ci-img]][ci] > Minify font declarations with PostCSS. This module will try to minimise the `font-family`, `font-weight` and `font` shorthand properties; it can unquote font families where necessary, detect & remove duplicates, and cut short a declaration after it finds a keyword. For more examples, see the [tests](test). ```css h1 { font:bold 2.2rem/.9 "Open Sans Condensed", sans-serif; } p { font-family: "Helvetica Neue", Arial, sans-serif, Helvetica; font-weight: normal; } ``` ```css h1 { font:700 2.2rem/.9 Open Sans Condensed,sans-serif } p { font-family: Helvetica Neue,Arial,sans-serif; font-weight: 400; } ``` ## API ### minifyFontValues([options]) #### options ##### removeAfterKeyword Type: `boolean` Default: `false` Pass `true` to remove font families after the module encounters a font keyword, for example `sans-serif`. ##### removeDuplicates Type: `boolean` Default: `true` Pass `false` to disable the module from removing duplicated font families. ##### removeQuotes Type: `boolean` Default: `true` Pass `false` to disable the module from removing quotes from font families. Note that oftentimes, this is a *safe optimisation* & is done safely. For more details, see [Mathias Bynens' article][mathias]. ## Usage ```js postcss([ require('postcss-minify-font-values') ]) ``` See [PostCSS] docs for examples for your environment. ## Contributors See [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md). # License MIT © [Bogdan Chadkin](mailto:trysound@yandex.ru) [mathias]: https://mathiasbynens.be/notes/unquoted-font-family [PostCSS]: https://github.com/postcss/postcss [ci-img]: https://travis-ci.org/cssnano/postcss-minify-font-values.svg [ci]: https://travis-ci.org/cssnano/postcss-minify-font-values 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 # 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 #object.assign <sup>[![Version Badge][npm-version-svg]][npm-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]][npm-url] [![browser support][testling-png]][testling-url] An Object.assign shim. Invoke its "shim" method to shim Object.assign if it is unavailable. 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](http://www.ecma-international.org/ecma-262/6.0/#sec-object.assign). In an ES6 environment, it will also work properly with `Symbol`s. Takes a minimum of 2 arguments: `target` and `source`. Takes a variable sized list of source arguments - at least 1, as many as you want. Throws a TypeError if the `target` argument is `null` or `undefined`. Most common usage: ```js var assign = require('object.assign').getPolyfill(); // returns native method if compliant /* or */ var assign = require('object.assign/polyfill')(); // returns native method if compliant ``` ## Example ```js var assert = require('assert'); // Multiple sources! var target = { a: true }; var source1 = { b: true }; var source2 = { c: true }; var sourceN = { n: true }; var expected = { a: true, b: true, c: true, n: true }; assign(target, source1, source2, sourceN); assert.deepEqual(target, expected); // AWESOME! ``` ```js var target = { a: true, b: true, c: true }; var source1 = { c: false, d: false }; var sourceN = { e: false }; var assigned = assign(target, source1, sourceN); assert.equal(target, assigned); // returns the target object assert.deepEqual(assigned, { a: true, b: true, c: false, d: false, e: false }); ``` ```js /* when Object.assign is not present */ delete Object.assign; var shimmedAssign = require('object.assign').shim(); /* or */ var shimmedAssign = require('object.assign/shim')(); assert.equal(shimmedAssign, assign); var target = { a: true, b: true, c: true }; var source = { c: false, d: false, e: false }; var assigned = assign(target, source); assert.deepEqual(Object.assign(target, source), assign(target, source)); ``` ```js /* when Object.assign is present */ var shimmedAssign = require('object.assign').shim(); assert.equal(shimmedAssign, Object.assign); var target = { a: true, b: true, c: true }; var source = { c: false, d: false, e: false }; assert.deepEqual(Object.assign(target, source), assign(target, source)); ``` ## Tests Simply clone the repo, `npm install`, and run `npm test` [npm-url]: https://npmjs.org/package/object.assign [npm-version-svg]: http://versionbadg.es/ljharb/object.assign.svg [travis-svg]: https://travis-ci.org/ljharb/object.assign.svg [travis-url]: https://travis-ci.org/ljharb/object.assign [deps-svg]: https://david-dm.org/ljharb/object.assign.svg?theme=shields.io [deps-url]: https://david-dm.org/ljharb/object.assign [dev-deps-svg]: https://david-dm.org/ljharb/object.assign/dev-status.svg?theme=shields.io [dev-deps-url]: https://david-dm.org/ljharb/object.assign#info=devDependencies [testling-png]: https://ci.testling.com/ljharb/object.assign.png [testling-url]: https://ci.testling.com/ljharb/object.assign [npm-badge-png]: https://nodei.co/npm/object.assign.png?downloads=true&stars=true [license-image]: http://img.shields.io/npm/l/object.assign.svg [license-url]: LICENSE [downloads-image]: http://img.shields.io/npm/dm/object.assign.svg [downloads-url]: http://npm-stat.com/charts.html?package=object.assign # ts-mixer [![npm version](https://badgen.net/npm/v/ts-mixer)](https://npmjs.com/package/ts-mixer) [![Build Status](https://travis-ci.org/tannerntannern/ts-mixer.svg?branch=master)](https://travis-ci.org/tannerntannern/ts-mixer) [![Coverage Status](https://coveralls.io/repos/github/tannerntannern/ts-mixer/badge.svg?branch=master)](https://coveralls.io/github/tannerntannern/ts-mixer?branch=master) [![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, `@dectorator` 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) # Author Tanner Nielsen <tannerntannern@gmail.com> * Website - [tannernielsen.com](http://tannernielsen.com) * Github - [tannerntannern](https://github.com/tannerntannern) # lodash.clone v4.5.0 The [lodash](https://lodash.com/) method `_.clone` exported as a [Node.js](https://nodejs.org/) module. ## Installation Using npm: ```bash $ {sudo -H} npm i -g npm $ npm i --save lodash.clone ``` In Node.js: ```js var clone = require('lodash.clone'); ``` See the [documentation](https://lodash.com/docs#clone) or [package source](https://github.com/lodash/lodash/blob/4.5.0-npm-packages/lodash.clone) for more details. # 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 # console-browserify [![Build Status](https://travis-ci.org/browserify/console-browserify.png?branch=master)](https://travis-ci.org/browserify/console-browserify) Emulate console for all the browsers ## Install You usually do not have to install `console-browserify` yourself! If your code runs in Node.js, `console` 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 `console-browserify` module when you do `require('console')`. But if none of those apply, with npm do: ``` npm install console-browserify ``` ## Usage ```js var console = require("console") // Or when manually using console-browserify directly: // var console = require("console-browserify") console.log("hello world!") ``` ## API See the [Node.js Console docs](https://nodejs.org/api/console.html). `console-browserify` does not support creating new `Console` instances and does not support the Inspector-only methods. ## Contributing PRs are very welcome! The main way to contribute to `console-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 `console` 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 `console` module and this module, please open an issue! ## Contributors - Raynos ## License [MIT](./LICENSE) [![build status](https://secure.travis-ci.org/dankogai/js-base64.png)](http://travis-ci.org/dankogai/js-base64) # base64.js Yet another [Base64] transcoder. [Base64]: http://en.wikipedia.org/wiki/Base64 ## HEADS UP In version 3.0 `js-base64` switch to ES2015 module so it is no longer compatible with legacy browsers like IE (see below). And 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`. ## 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/js-base64@3.5.2/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/js-base64@3.5.2/base64.mjs'; </script> ``` ```html <script type="module"> // or if you prefer no Base64 namespace import { encode, decode } from 'https://cdn.jsdelivr.net/npm/js-base64@3.5.2/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.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.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-');// 小飼弾 ``` ### 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 String.prototype Base64.extendString(); // 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 IE11. Do the following in your shell. ```shell $ make base64.es5.js ``` # regenerator-runtime Standalone runtime for [Regenerator](https://github.com/facebook/regenerator)-compiled generator and `async` functions. To import the runtime as a module (recommended), either of the following import styles will work: ```js // CommonJS const regeneratorRuntime = require("regenerator-runtime"); // ECMAScript 2015 import regeneratorRuntime from "regenerator-runtime"; ``` To ensure that `regeneratorRuntime` is defined globally, either of the following styles will work: ```js // CommonJS require("regenerator-runtime/runtime"); // ECMAScript 2015 import "regenerator-runtime/runtime"; ``` To get the absolute file system path of `runtime.js`, evaluate the following expression: ```js require("regenerator-runtime/path").path ``` 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) # 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) _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 from 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 without the use of [lookbehind assertions](https://mathiasbynens.be/notes/es-regexp-proposals#lookbehinds), which aren't yet widely supported. 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. # 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._ # [postcss][postcss]-normalize-string > Normalize strings with PostCSS. ## Install With [npm](https://npmjs.org/package/postcss-normalize-string) do: ``` npm install postcss-normalize-string --save ``` ## Example ### Input ```css p:after{ content: '\\'string\\' is intact' } ``` ### Output ```css p:after{ content:"'string' is intact" } ``` ## Usage See the [PostCSS documentation](https://github.com/postcss/postcss#usage) for examples for your environment. ## API ### normalize([options]) #### options ##### preferredQuote Type: `string` Default: `double` Sets what type of quote to prefer. Possible values are `single` and `double`. ```js var css = 'p:after{content:""}'; console.log(postcss(normalize({preferredQuote: 'single'})).process(css).css); //=> p:after{content:''} ``` ## Contributors See [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md). ## License MIT © [Ben Briggs](http://beneb.info) [postcss]: https://github.com/postcss/postcss # dotenv-expand <img src="https://raw.githubusercontent.com/motdotla/dotenv-expand/master/dotenv-expand.png" alt="dotenv-expand" align="right" /> Dotenv-expand adds variable expansion on top of [dotenv](http://github.com/motdotla/dotenv). If you find yourself needing to expand environment variables already existing on your machine, then dotenv-expand is your tool. [![BuildStatus](https://img.shields.io/travis/motdotla/dotenv-expand/master.svg?style=flat-square)](https://travis-ci.org/motdotla/dotenv-expand) [![NPM version](https://img.shields.io/npm/v/dotenv-expand.svg?style=flat-square)](https://www.npmjs.com/package/dotenv-expand) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square)](https://github.com/feross/standard) ## Install ```bash npm install dotenv --save npm install dotenv-expand --save ``` ## Usage As early as possible in your application, require dotenv and dotenv-expand, and wrap dotenv-expand around dotenv. ```js var dotenv = require('dotenv') var dotenvExpand = require('dotenv-expand') var myEnv = dotenv.config() dotenvExpand(myEnv) ``` See [test/.env](./test/.env) for examples of variable expansion in your `.env` file. # 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) ## `buffer` for enterprise Available as part of the Tidelift Subscription. The maintainers of `buffer` 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-buffer?utm_source=npm-buffer&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) ## 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-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._ # [postcss][postcss]-colormin > Minify colors in your CSS files with PostCSS. ## Install With [npm](https://npmjs.org/package/postcss-colormin) do: ``` npm install postcss-colormin --save ``` ## Example ```js var postcss = require('postcss') var colormin = require('postcss-colormin'); var css = 'h1 {color: rgba(255, 0, 0, 1)}'; console.log(postcss(colormin()).process(css).css); // => 'h1 {color:red}' ``` For more examples see the [tests](src/__tests__/index.js). ## Usage See the [PostCSS documentation](https://github.com/postcss/postcss#usage) for examples for your environment. ## Contributors See [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md). ## License MIT © [Ben Briggs](http://beneb.info) [postcss]: https://github.com/postcss/postcss [![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. # Jest 🃏 Delightful JavaScript Testing - **👩🏻‍💻 Developer Ready**: Complete and ready to set-up JavaScript testing solution. Works out of the box for any React project. - **🏃🏽 Instant Feedback**: Failed tests run first. Fast interactive mode can switch between running all tests or only test files related to changed files. - **📸 Snapshot Testing**: Jest can [capture snapshots](https://jestjs.io/docs/snapshot-testing.html) of React trees or other serializable values to simplify UI testing. Read More: https://jestjs.io/ 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> # nth-check [![Build Status](https://travis-ci.org/fb55/nth-check.svg)](https://travis-ci.org/fb55/nth-check) A performant nth-check parser & compiler. ### About This module can be used to parse & compile nth-checks, as they are found in CSS 3's `nth-child()` and `nth-last-of-type()`. `nth-check` focusses on speed, providing optimized functions for different kinds of nth-child formulas, while still following the [spec](http://www.w3.org/TR/css3-selectors/#nth-child-pseudo). ### API ```js var nthCheck = require("nth-check"); ``` ##### `nthCheck(formula)` First parses, then compiles the formula. ##### `nthCheck.parse(formula)` Parses the expression, throws a `SyntaxError` if it fails, otherwise returns an array containing two elements. __Example:__ ```js nthCheck.parse("2n+3") //[2, 3] ``` ##### `nthCheck.compile([a, b])` Takes an array with two elements (as returned by `.parse`) and returns a highly optimized function. If the formula doesn't match any elements, it returns [`boolbase`](https://github.com/fb55/boolbase)'s `falseFunc`, otherwise, a function accepting an _index_ is returned, which returns whether or not a passed _index_ matches the formula. (Note: The spec starts counting at `1`, the returned function at `0`). __Example:__ ```js var check = nthCheck.compile([2, 3]); check(0) //false check(1) //false check(2) //true check(3) //false check(4) //true check(5) //false check(6) //true ``` --- License: BSD ## Escodegen [![npm version](https://badge.fury.io/js/escodegen.svg)](http://badge.fury.io/js/escodegen) [![Build Status](https://secure.travis-ci.org/estools/escodegen.svg)](http://travis-ci.org/estools/escodegen) [![Dependency Status](https://david-dm.org/estools/escodegen.svg)](https://david-dm.org/estools/escodegen) [![devDependency Status](https://david-dm.org/estools/escodegen/dev-status.svg)](https://david-dm.org/estools/escodegen#info=devDependencies) Escodegen ([escodegen](http://github.com/estools/escodegen)) is an [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) (also popularly known as [JavaScript](http://en.wikipedia.org/wiki/JavaScript)) code generator from [Mozilla's Parser API](https://developer.mozilla.org/en/SpiderMonkey/Parser_API) AST. See the [online generator](https://estools.github.io/escodegen/demo/index.html) for a demo. ### Install Escodegen can be used in a web browser: <script src="escodegen.browser.js"></script> escodegen.browser.js can be found in tagged revisions on GitHub. Or in a Node.js application via npm: npm install escodegen ### Usage A simple example: the program escodegen.generate({ type: 'BinaryExpression', operator: '+', left: { type: 'Literal', value: 40 }, right: { type: 'Literal', value: 2 } }); produces the string `'40 + 2'`. See the [API page](https://github.com/estools/escodegen/wiki/API) for options. To run the tests, execute `npm test` in the root directory. ### Building browser bundle / minified browser bundle At first, execute `npm install` to install the all dev dependencies. After that, npm run-script build will generate `escodegen.browser.js`, which can be used in browser environments. And, npm run-script build-min will generate the minified file `escodegen.browser.min.js`. ### License #### Escodegen Copyright (C) 2012 [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. # [postcss][postcss]-merge-rules > Merge CSS rules with PostCSS. ## Install With [npm](https://npmjs.org/package/postcss-merge-rules) do: ``` npm install postcss-merge-rules --save ``` ## Examples This module will attempt to merge *adjacent* CSS rules: ### By declarations #### Input ```css a { color: blue; font-weight: bold } p { color: blue; font-weight: bold } ``` #### Output ```css a,p { color: blue; font-weight: bold } ``` ### By selectors #### Input ```css a { color: blue } a { font-weight: bold } ``` #### Output ```css a { color: blue; font-weight: bold } ``` ### By partial declarations #### Input ```css a { font-weight: bold } p { color: blue; font-weight: bold } ``` #### Output ```css a,p { font-weight: bold } p { color: blue } ``` ## Usage See the [PostCSS documentation](https://github.com/postcss/postcss#usage) for examples for your environment. ## Contributors See [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md). ## License MIT © [Ben Briggs](http://beneb.info) [postcss]: https://github.com/postcss/postcss # 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 # [postcss][postcss]-normalize-timing-functions > Normalize timing functions with PostCSS. ## Install With [npm](https://npmjs.org/package/postcss-normalize-timing-functions) do: ``` npm install postcss-normalize-timing-functions --save ``` ## Example ### Input ```css div { animate: fade 3s cubic-bezier(0.42, 0, 1, 1) } ``` ### Output ```css div { animate: fade 3s ease-in } ``` ## Usage See the [PostCSS documentation](https://github.com/postcss/postcss#usage) for examples for your environment. ## Contributors See [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md). ## License MIT © [Ben Briggs](http://beneb.info) [postcss]: https://github.com/postcss/postcss # physical-cpu-count Returns the number of physical CPU cores. ## Example ```js const physicalCpuCount = require('physical-cpu-count') // 4 const logicalCpuCount = require('os').cpus().length // 8 ``` ## Use Case Working with clusters of Node.js processes it is common to see code using `os.cpus().length` as the number of child workers to fork. For some workloads this can negatively impact performance on CPUs that use simultaneous multithreading (SMT). Latency is doubled because two processes share the same physical CPU core to get their work done. Additionally there is memory spent for each running worker, as well as time to spawn their processes. It is better to fork no more child processes than there are physical cores. ## Known Limitations Implemented for Linux, macOS, and Windows. Other platforms use a naive approach that only looks at Intel CPUs, and assumes every Intel CPU supports, and has enabled, Hyper-Threading with two threads per physical core. These assumptions are not always correct. Power management might also make CPU cores unavailable. ## See also: - [Issue `nodejs/node#7730` to implement physical core detection natively in Node.js.](https://github.com/nodejs/node/issues/7730) - [Relevant Stack Overflow answer for macOS and Linux.](https://stackoverflow.com/a/23378780) - [Solutions for Windows WMIC from the command prompt.](http://superuser.com/questions/226552/how-to-tell-how-many-cpus-cores-you-have-on-windows-7) # 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. # 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 <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) * [.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#L250) Create a regular expression from a parsed glob pattern. **Params** * `state` **{String}**: The object returned from the `.parse` method. * `options` **{Object}** * `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#L318) 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` | `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` | 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. | ### 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). [![Codecov](https://img.shields.io/codecov/c/github/ehmicky/human-signals.svg?label=tested&logo=codecov)](https://codecov.io/gh/ehmicky/human-signals) [![Travis](https://img.shields.io/badge/cross-platform-4cc61e.svg?logo=travis)](https://travis-ci.org/ehmicky/human-signals) [![Node](https://img.shields.io/node/v/human-signals.svg?logo=node.js)](https://www.npmjs.com/package/human-signals) [![Gitter](https://img.shields.io/gitter/room/ehmicky/human-signals.svg?logo=gitter)](https://gitter.im/ehmicky/human-signals) [![Twitter](https://img.shields.io/badge/%E2%80%8B-twitter-4cc61e.svg?logo=twitter)](https://twitter.com/intent/follow?screen_name=ehmicky) [![Medium](https://img.shields.io/badge/%E2%80%8B-medium-4cc61e.svg?logo=medium)](https://medium.com/@ehmicky) Human-friendly process signals. This is a map of known process signals with some information about each signal. Unlike [`os.constants.signals`](https://nodejs.org/api/os.html#os_signal_constants) this includes: - human-friendly [descriptions](#description) - [default actions](#action), including whether they [can be prevented](#forced) - whether the signal is [supported](#supported) by the current OS # Example ```js const { signalsByName, signalsByNumber } = require('human-signals') console.log(signalsByName.SIGINT) // { // name: 'SIGINT', // number: 2, // description: 'User interruption with CTRL-C', // supported: true, // action: 'terminate', // forced: false, // standard: 'ansi' // } console.log(signalsByNumber[8]) // { // name: 'SIGFPE', // number: 8, // description: 'Floating point arithmetic error', // supported: true, // action: 'core', // forced: false, // standard: 'ansi' // } ``` # Install ```bash npm install human-signals ``` # Usage ## signalsByName _Type_: `object` Object whose keys are signal [names](#name) and values are [signal objects](#signal). ## signalsByNumber _Type_: `object` Object whose keys are signal [numbers](#number) and values are [signal objects](#signal). ## signal _Type_: `object` Signal object with the following properties. ### name _Type_: `string` Standard name of the signal, for example `'SIGINT'`. ### number _Type_: `number` Code number of the signal, for example `2`. While most `number` are cross-platform, some are different between different OS. ### description _Type_: `string` Human-friendly description for the signal, for example `'User interruption with CTRL-C'`. ### supported _Type_: `boolean` Whether the current OS can handle this signal in Node.js using [`process.on(name, handler)`](https://nodejs.org/api/process.html#process_signal_events). The list of supported signals [is OS-specific](https://github.com/ehmicky/cross-platform-node-guide/blob/master/docs/6_networking_ipc/signals.md#cross-platform-signals). ### action _Type_: `string`<br>_Enum_: `'terminate'`, `'core'`, `'ignore'`, `'pause'`, `'unpause'` What is the default action for this signal when it is not handled. ### forced _Type_: `boolean` Whether the signal's default action cannot be prevented. This is `true` for `SIGTERM`, `SIGKILL` and `SIGSTOP`. ### standard _Type_: `string`<br>_Enum_: `'ansi'`, `'posix'`, `'bsd'`, `'systemv'`, `'other'` Which standard defined that signal. # Support If you found a bug or would like a new feature, _don't hesitate_ to [submit an issue on GitHub](../../issues). For other questions, feel free to [chat with us on Gitter](https://gitter.im/ehmicky/human-signals). Everyone is welcome regardless of personal background. We enforce a [Code of conduct](CODE_OF_CONDUCT.md) in order to promote a positive and inclusive environment. # Contributing This project was made with ❤️. The simplest way to give back is by starring and sharing it online. If the documentation is unclear or has a typo, please click on the page's `Edit` button (pencil icon) and suggest a correction. If you would like to help us fix a bug or add a new feature, please check our [guidelines](CONTRIBUTING.md). Pull requests are welcome! <!-- Thanks go to our wonderful contributors: --> <!-- ALL-CONTRIBUTORS-LIST:START --> <!-- prettier-ignore --> <table><tr><td align="center"><a href="https://twitter.com/ehmicky"><img src="https://avatars2.githubusercontent.com/u/8136211?v=4" width="100px;" alt="ehmicky"/><br /><sub><b>ehmicky</b></sub></a><br /><a href="https://github.com/ehmicky/human-signals/commits?author=ehmicky" title="Code">💻</a> <a href="#design-ehmicky" title="Design">🎨</a> <a href="#ideas-ehmicky" title="Ideas, Planning, & Feedback">🤔</a> <a href="https://github.com/ehmicky/human-signals/commits?author=ehmicky" title="Documentation">📖</a></td></tr></table> <!-- ALL-CONTRIBUTORS-LIST:END --> # jest-serializer Module for serializing and deserializing object into memory and disk. By default, the `v8` implementations are used, but if not present, it defaults to `JSON` implementation. Both serializers have the advantage of being able to serialize `Map`, `Set`, `undefined`, `NaN`, etc, although the JSON one does it through a replacer/reviver. ## Install ```sh $ yarn add jest-serializer ``` ## API Three kinds of API groups are exposed: ### In-memory serialization: `serialize` and `deserialize` This set of functions take or return a `Buffer`. All the process happens in memory. This is useful when willing to transfer over HTTP, TCP or via UNIX pipes. ```javascript import {deserialize, serialize} from 'jest-serializer'; const myObject = { foo: 'bar', baz: [0, true, '2', [], {}], }; const buffer = serialize(myObject); const myCopyObject = deserialize(buffer); ``` ### Synchronous persistent filesystem: `readFileSync` and `writeFileSync` This set of functions allow to send to disk a serialization result and retrieve it back, in a synchronous way. It mimics the `fs` API so it looks familiar. ```javascript import {readFileSync, writeFileSync} from 'jest-serializer'; const myObject = { foo: 'bar', baz: [0, true, '2', [], {}], }; const myFile = '/tmp/obj'; writeFileSync(myFile, myObject); const myCopyObject = readFileSync(myFile); ``` 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/express.svg)](https://github.com/jprichardson/node-fs-extra/blob/master/LICENSE) [![build status](https://img.shields.io/travis/jprichardson/node-fs-extra/master.svg)](http://travis-ci.org/jprichardson/node-fs-extra) [![windows Build status](https://img.shields.io/appveyor/ci/jprichardson/node-fs-extra/master.svg?label=windows%20build)](https://ci.appveyor.com/project/jprichardson/node-fs-extra/branch/master) [![downloads per month](http://img.shields.io/npm/dm/fs-extra.svg)](https://www.npmjs.org/package/fs-extra) [![Coverage Status](https://img.shields.io/coveralls/github/jprichardson/node-fs-extra/master.svg)](https://coveralls.io/github/jprichardson/node-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()`](docs/fs-read-write.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 ----------- ### 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. See coveralls output for more info. 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 Utilities for determining whether characters belong to character classes defined by the XML specs. ## Organization It used to be that the library was contained in a single file and you could just import/require/what-have-you the `xmlchars` module. However, that setup did not work well for people who cared about code optimization. Importing `xmlchars` meant importing *all* of the library and because of the way the code was generated there was no way to shake the resulting code tree. Different modules cover different standards. At the time this documentation was last updated, we had: * `xmlchars/xml/1.0/ed5` which covers XML 1.0 edition 5. * `xmlchars/xml/1.0/ed4` which covers XML 1.0 edition 4. * `xmlchars/xml/1.1/ed2` which covers XML 1.0 edition 2. * `xmlchars/xmlns/1.0/ed3` which covers XML Namespaces 1.0 edition 3. ## Features The "things" each module contains can be categorized as follows: 1. "Fragments": these are parts and pieces of regular expressions that correspond to the productions defined in the standard that the module covers. You'd use these to *build regular expressions*. 2. Regular expressions that correspond to the productions defined in the standard that the module covers. 3. Lists: these are arrays of characters that correspond to the productions. 4. Functions that test code points to verify whether they fit a production. 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); ``` # prebuild-install > A command line tool to easily install prebuilt binaries for multiple version of node/iojs on a specific platform. [![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) [![Build Status](https://travis-ci.org/prebuild/prebuild-install.svg?branch=master)](https://travis-ci.org/prebuild/prebuild-install) [![Build status](https://ci.appveyor.com/api/projects/status/6v6hxxwgjrr99pc8/branch/master?svg=true)](https://ci.appveyor.com/project/mathiask88/prebuild-install) [![david](https://david-dm.org/prebuild/prebuild-install.svg)](https://david-dm.org/prebuild/prebuild-install) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/) `prebuild-install` supports installing prebuilt binaries from GitHub by default. ## Usage Change your package.json install script to: ```json { "scripts": { "install": "prebuild-install || node-gyp rebuild" } } ``` ### Requirements You need to provide prebuilds made by [`prebuild`](https://github.com/prebuild/prebuild). ### 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) --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` and `--download`, may be passed through via arguments given to the `npm` command. ### 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 `leveldown@1.2.3` the resulting url will be: ``` http://overriden-host.com/overriden-path/v1.2.3/leveldown-v1.2.3-node-v57-win32-x64.tar.gz ``` ### 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` ## License MIT # 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:pass@host.com: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:pass@host.com: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' # 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. # 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._ # 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). # Parse, serialize, and manipulate MIME types This package will parse [MIME types](https://mimesniff.spec.whatwg.org/#understanding-mime-types) into a structured format, which can then be manipulated and serialized: ```js const MIMEType = require("whatwg-mimetype"); const mimeType = new MIMEType(`Text/HTML;Charset="utf-8"`); console.assert(mimeType.toString() === "text/html;charset=utf-8"); console.assert(mimeType.type === "text"); console.assert(mimeType.subtype === "html"); console.assert(mimeType.essence === "text/html"); console.assert(mimeType.parameters.get("charset") === "utf-8"); mimeType.parameters.set("charset", "windows-1252"); console.assert(mimeType.parameters.get("charset") === "windows-1252"); console.assert(mimeType.toString() === "text/html;charset=windows-1252"); console.assert(mimeType.isHTML() === true); console.assert(mimeType.isXML() === false); ``` Parsing is a fairly complex process; see [the specification](https://mimesniff.spec.whatwg.org/#parsing-a-mime-type) for details (and similarly [for serialization](https://mimesniff.spec.whatwg.org/#serializing-a-mime-type)). This package's algorithms conform to those of the WHATWG [MIME Sniffing Standard](https://mimesniff.spec.whatwg.org/), and is aligned up to commit [126286a](https://github.com/whatwg/mimesniff/commit/126286ab2dcf3e2d541349ed93539a88bf394ad5). ## `MIMEType` API This package's main module's default export is a class, `MIMEType`. Its constructor takes a string which it will attempt to parse into a MIME type; if parsing fails, an `Error` will be thrown. ### The `parse()` static factory method As an alternative to the constructor, you can use `MIMEType.parse(string)`. The only difference is that `parse()` will return `null` on failed parsing, whereas the constructor will throw. It thus makes the most sense to use the constructor in cases where unparseable MIME types would be exceptional, and use `parse()` when dealing with input from some unconstrained source. ### Properties - `type`: the MIME type's [type](https://mimesniff.spec.whatwg.org/#mime-type-type), e.g. `"text"` - `subtype`: the MIME type's [subtype](https://mimesniff.spec.whatwg.org/#mime-type-subtype), e.g. `"html"` - `essence`: the MIME type's [essence](https://mimesniff.spec.whatwg.org/#mime-type-essence), e.g. `"text/html"` - `parameters`: an instance of `MIMETypeParameters`, containing this MIME type's [parameters](https://mimesniff.spec.whatwg.org/#mime-type-parameters) `type` and `subtype` can be changed. They will be validated to be non-empty and only contain [HTTP token code points](https://mimesniff.spec.whatwg.org/#http-token-code-point). `essence` is only a getter, and cannot be changed. `parameters` is also a getter, but the contents of the `MIMETypeParameters` object are mutable, as described below. ### Methods - `toString()` serializes the MIME type to a string - `isHTML()`: returns true if this instance represents [a HTML MIME type](https://mimesniff.spec.whatwg.org/#html-mime-type) - `isXML()`: returns true if this instance represents [an XML MIME type](https://mimesniff.spec.whatwg.org/#xml-mime-type) - `isJavaScript({ allowParameters })`: returns true if this instance represents [a JavaScript MIME type](https://html.spec.whatwg.org/multipage/scripting.html#javascript-mime-type); `allowParameters` can be set to true to allow arbitrary parameters, instead of their presence causing the method to return `false` _Note: the `isHTML()`, `isXML()`, and `isJavaScript()` methods are speculative, and may be removed or changed in future major versions. See [whatwg/mimesniff#48](https://github.com/whatwg/mimesniff/issues/48) for brainstorming in this area. Currently we implement these mainly because they are useful in jsdom._ ## `MIMETypeParameters` API The `MIMETypeParameters` class, instances of which are returned by `mimeType.parameters`, has equivalent surface API to a [JavaScript `Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map). However, `MIMETypeParameters` methods will always interpret their arguments as appropriate for MIME types, so e.g. parameter names will be lowercased, and attempting to set invalid characters will throw. Some examples: ```js const mimeType = new MIMEType(`x/x;a=b;c=D;E="F"`); // Logs: // a b // c D // e F for (const [name, value] of mimeType.parameters) { console.log(name, value); } console.assert(mimeType.parameters.has("a")); console.assert(mimeType.parameters.has("A")); console.assert(mimeType.parameters.get("A") === "b"); mimeType.parameters.set("Q", "X"); console.assert(mimeType.parameters.get("q") === "X"); console.assert(mimeType.toString() === "x/x;a=b;c=d;e=F;q=X"); // Throws: mimeType.parameters.set("@", "x"); ``` ## Raw parsing/serialization APIs If you want primitives on which to build your own API, you can get direct access to the parsing and serialization algorithms as follows: ```js const parse = require("whatwg-mimetype/parser"); const serialize = require("whatwg-mimetype/serialize"); ``` `parse(string)` returns an object containing the `type` and `subtype` strings, plus `parameters`, which is a `Map`. This is roughly our equivalent of the spec's [MIME type record](https://mimesniff.spec.whatwg.org/#mime-type). If parsing fails, it instead returns `null`. `serialize(record)` operates on the such an object, giving back a string according to the serialization algorithm. # micromatch [![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/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) > 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/): ```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](#advanced-globbing)** - Supports [extglobs](#extglobs), [braces](#braces), 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** * **{String|Array<string>}**: list List of strings to match. * **{String|Array<string>}**: patterns One or more glob patterns to use for matching. * **{Object}**: options 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#L98) 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#L117) Returns true if **any** of the given glob `patterns` match the specified `string`. **Params** * **{String}**: 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 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#L136) 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#L176) 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#L218) 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#L247) 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 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#L283) 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 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#L322) 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#L349) 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` **{Boolean}**: 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#L375) 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#L391) 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#L407) 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(pattern[, options]); ``` ### [.braces](index.js#L434) 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` | `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 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']` * `[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 April 10, 2019 (longer bars are better): ```sh # .makeRe star micromatch x 1,724,735 ops/sec ±1.69% (87 runs sampled)) minimatch x 649,565 ops/sec ±1.93% (91 runs sampled) # .makeRe star; dot=true micromatch x 1,302,127 ops/sec ±1.43% (92 runs sampled) minimatch x 556,242 ops/sec ±0.71% (86 runs sampled) # .makeRe globstar micromatch x 1,393,992 ops/sec ±0.71% (89 runs sampled) minimatch x 1,112,801 ops/sec ±2.02% (91 runs sampled) # .makeRe globstars micromatch x 1,419,097 ops/sec ±0.34% (94 runs sampled) minimatch x 541,207 ops/sec ±1.66% (93 runs sampled) # .makeRe with leading star micromatch x 1,247,825 ops/sec ±0.97% (94 runs sampled) minimatch x 489,660 ops/sec ±0.63% (94 runs sampled) # .makeRe - braces micromatch x 206,301 ops/sec ±1.62% (81 runs sampled)) minimatch x 115,986 ops/sec ±0.59% (94 runs sampled) # .makeRe braces - range (expanded) micromatch x 27,782 ops/sec ±0.79% (88 runs sampled) minimatch x 4,683 ops/sec ±1.20% (92 runs sampled) # .makeRe braces - range (compiled) micromatch x 134,056 ops/sec ±2.73% (77 runs sampled)) minimatch x 977 ops/sec ±0.85% (91 runs sampled)d) # .makeRe braces - nested ranges (expanded) micromatch x 18,353 ops/sec ±0.95% (91 runs sampled) minimatch x 4,514 ops/sec ±1.04% (93 runs sampled) # .makeRe braces - nested ranges (compiled) micromatch x 38,916 ops/sec ±1.85% (82 runs sampled) minimatch x 980 ops/sec ±0.54% (93 runs sampled)d) # .makeRe braces - set (compiled) micromatch x 141,088 ops/sec ±1.70% (70 runs sampled)) minimatch x 43,385 ops/sec ±0.87% (93 runs sampled) # .makeRe braces - nested sets (compiled) micromatch x 87,272 ops/sec ±2.85% (71 runs sampled)) minimatch x 25,327 ops/sec ±1.59% (86 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** | | --- | --- | | 475 | [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 | [Tvrqvoise](https://github.com/Tvrqvoise) | | 2 | [tunnckoCore](https://github.com/tunnckoCore) | | 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) | | 1 | [simlu](https://github.com/simlu) | | 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 10, 2019._ # 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.js - jsonfile ================ Easily read/write JSON files. [![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) `options` (`object`, default `undefined`): Pass in any `fs.readFile` 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 var jsonfile = require('jsonfile') var file = '/tmp/data.json' jsonfile.readFile(file, function(err, obj) { console.dir(obj) }) ``` ### readFileSync(filename, [options]) `options` (`object`, default `undefined`): Pass in any `fs.readFileSync` 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 var jsonfile = require('jsonfile') var file = '/tmp/data.json' console.dir(jsonfile.readFileSync(file)) ``` ### writeFile(filename, obj, [options], callback) `options`: Pass in any `fs.writeFile` 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` and override `EOL` string. ```js var jsonfile = require('jsonfile') var file = '/tmp/data.json' var obj = {name: 'JP'} jsonfile.writeFile(file, obj, function (err) { console.error(err) }) ``` **formatting with spaces:** ```js var jsonfile = require('jsonfile') var file = '/tmp/data.json' var obj = {name: 'JP'} jsonfile.writeFile(file, obj, {spaces: 2}, function(err) { console.error(err) }) ``` **overriding EOL:** ```js var jsonfile = require('jsonfile') var file = '/tmp/data.json' var obj = {name: 'JP'} jsonfile.writeFile(file, obj, {spaces: 2, EOL: '\r\n'}, function(err) { console.error(err) }) ``` **appending to an existing JSON file:** You can use `fs.writeFile` option `{flag: 'a'}` to achieve this. ```js var jsonfile = require('jsonfile') var file = '/tmp/mayAlreadyExistedData.json' var obj = {name: 'JP'} jsonfile.writeFile(file, obj, {flag: 'a'}, function (err) { console.error(err) }) ``` ### writeFileSync(filename, obj, [options]) `options`: Pass in any `fs.writeFileSync` 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` and override `EOL` string. ```js var jsonfile = require('jsonfile') var file = '/tmp/data.json' var obj = {name: 'JP'} jsonfile.writeFileSync(file, obj) ``` **formatting with spaces:** ```js var jsonfile = require('jsonfile') var file = '/tmp/data.json' var obj = {name: 'JP'} jsonfile.writeFileSync(file, obj, {spaces: 2}) ``` **overriding EOL:** ```js var jsonfile = require('jsonfile') var file = '/tmp/data.json' var obj = {name: 'JP'} jsonfile.writeFileSync(file, obj, {spaces: 2, EOL: '\r\n'}) ``` **appending to an existing JSON file:** You can use `fs.writeFileSync` option `{flag: 'a'}` to achieve this. ```js var jsonfile = require('jsonfile') var file = '/tmp/mayAlreadyExistedData.json' var obj = {name: 'JP'} jsonfile.writeFileSync(file, obj, {flag: 'a'}) ``` License ------- (MIT License) Copyright 2012-2016, JP Richardson <jprichardson@gmail.com> # DOMException This package implements the [`DOMException`](https://heycam.github.io/webidl/#idl-DOMException) class, from web browsers. It exists in service of [jsdom](https://github.com/tmpvar/jsdom) and related packages. Example usage: ```js const DOMException = require("domexception"); const e1 = new DOMException("Something went wrong", "BadThingsError"); console.assert(e1.name === "BadThingsError"); console.assert(e1.code === 0); const e2 = new DOMException("Another exciting error message", "NoModificationAllowedError"); console.assert(e2.name === "NoModificationAllowedError"); console.assert(e2.code === 7); console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10); ``` ## APIs This package exposes two flavors of the `DOMException` interface depending on the imported module. ### `domexception` module This module default-exports the `DOMException` interface constructor. ### `domexception/webidl2js-wrapper` module This module exports the `DOMException` [interface wrapper API](https://github.com/jsdom/webidl2js#for-interfaces) generated by [webidl2js](https://github.com/jsdom/webidl2js). ## Ansi to Html [![](https://img.shields.io/travis/rburns/ansi-to-html.svg)](https://travis-ci.org/rburns/ansi-to-html/branches) [![](https://img.shields.io/npm/v/ansi-to-html.svg)](https://www.npmjs.com/package/ansi-to-html) ![](https://img.shields.io/npm/dm/ansi-to-html.svg) This was originally a port of the ansi to html converter from [bcat](https://github.com/rtomayko/bcat/blob/master/lib/bcat/ansi.rb) to JavaScript. It has since undergone quite a lot of modification. It has a few additions: * The API has been altered to accept options in the constructor, and input in `toHtml()`. * ANSI codes for setting the foreground or background color to default are handled * the 'erase in line' escape code (`\x1b[K`) is dropped from the output. ## Installation ```bash npm install ansi-to-html ``` ## Usage ```javascript var Convert = require('ansi-to-html'); var convert = new Convert(); console.log(convert.toHtml('\x1b[30mblack\x1b[37mwhite')); /* prints: <span style="color:#000">black<span style="color:#AAA">white</span></span> */ ``` ## Command line usage When using ansi-to-html from the command line the stream option is set to `true`. Other options can be provided. See `ansi-to-html -h` for more detail. ### Process a file ```bash ansi-to-html the_filename ``` ### From STDIN ```bash git log | ansi-to-html ``` ## Options Options can be be passed to the constructor to customize behaviour. **fg** `<CSS color values>`. The default foreground color used when reset color codes are encountered. **bg** `<CSS color values>`. The default background color used when reset color codes are encountered. **newline** `true` or `false`. Convert newline characters to `<br/>`. **escapeXML** `true` or `false`. Generate HTML/XML entities. **stream** `true` or `false`. Save style state across invocations of `toHtml()`. **colors** `Object`/`Array` (with values 0 - 255 containing CSS color values). Can override specific colors or the entire ANSI palette ### Default options ```json5 { fg: '#FFF', bg: '#000', newline: false, escapeXML: false, stream: false } ``` ## Development Once you have the git repository cloned, install the dependencies: ```bash cd ansi-to-html npm install ``` #### Lint ```bash npm run lint ``` #### Build ```bash npm run build ``` - Builds the `/src` files by running `babel`. - Saves the built files in `/lib` output directory. - Recommended to run `babel` in Watch mode - will re-build the project each time the files are changed. ```bash npm run build:watch ``` #### Test ```bash npm test ``` - Note: Runs the tests against the built files (in the `/lib` directory). - You also run the tests in watch mode (will rerun tests when files are changed). - Recommended to run the build in watch mode as well to re-build the project before the tests are run. ```bash npm run test:watch ``` # color-string [![Build Status](https://travis-ci.org/Qix-/color-string.svg?branch=master)](https://travis-ci.org/Qix-/color-string) > library for parsing and generating CSS color strings. ## Install With [npm](http://npmjs.org/): ```console $ npm install color-string ``` ## Usage ### Parsing ```js colorString.get('#FFF') // {model: 'rgb', value: [255, 255, 255, 1]} colorString.get('#FFFA') // {model: 'rgb', value: [255, 255, 255, 0.67]} colorString.get('#FFFFFFAA') // {model: 'rgb', value: [255, 255, 255, 0.67]} colorString.get('hsl(360, 100%, 50%)') // {model: 'hsl', value: [0, 100, 50, 1]} colorString.get('hwb(60, 3%, 60%)') // {model: 'hwb', value: [60, 3, 60, 1]} colorString.get.rgb('#FFF') // [255, 255, 255, 1] colorString.get.rgb('blue') // [0, 0, 255, 1] colorString.get.rgb('rgba(200, 60, 60, 0.3)') // [200, 60, 60, 0.3] colorString.get.rgb('rgb(200, 200, 200)') // [200, 200, 200, 1] colorString.get.hsl('hsl(360, 100%, 50%)') // [0, 100, 50, 1] colorString.get.hsl('hsla(360, 60%, 50%, 0.4)') // [0, 60, 50, 0.4] colorString.get.hwb('hwb(60, 3%, 60%)') // [60, 3, 60, 1] colorString.get.hwb('hwb(60, 3%, 60%, 0.6)') // [60, 3, 60, 0.6] colorString.get.rgb('invalid color string') // null ``` ### Generation ```js colorString.to.hex([255, 255, 255]) // "#FFFFFF" colorString.to.hex([0, 0, 255, 0.4]) // "#0000FF66" colorString.to.hex([0, 0, 255], 0.4) // "#0000FF66" colorString.to.rgb([255, 255, 255]) // "rgb(255, 255, 255)" colorString.to.rgb([0, 0, 255, 0.4]) // "rgba(0, 0, 255, 0.4)" colorString.to.rgb([0, 0, 255], 0.4) // "rgba(0, 0, 255, 0.4)" colorString.to.rgb.percent([0, 0, 255]) // "rgb(0%, 0%, 100%)" colorString.to.keyword([255, 255, 0]) // "yellow" colorString.to.hsl([360, 100, 100]) // "hsl(360, 100%, 100%)" colorString.to.hwb([50, 3, 15]) // "hwb(50, 3%, 15%)" // all functions also support swizzling colorString.to.rgb(0, [0, 255], 0.4) // "rgba(0, 0, 255, 0.4)" colorString.to.rgb([0, 0], [255], 0.4) // "rgba(0, 0, 255, 0.4)" colorString.to.rgb([0], 0, [255, 0.4]) // "rgba(0, 0, 255, 0.4)" ``` # 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). # diff-sequences Compare items in two sequences to find a **longest common subsequence**. The items not in common are the items to delete or insert in a **shortest edit script**. To maximize flexibility and minimize memory, you write **callback** functions as configuration: **Input** function `isCommon(aIndex, bIndex)` compares items at indexes in the sequences and returns a truthy/falsey value. This package might call your function more than once for some pairs of indexes. - Because your function encapsulates **comparison**, this package can compare items according to `===` operator, `Object.is` method, or other criterion. - Because your function encapsulates **sequences**, this package can find differences in arrays, strings, or other data. **Output** function `foundSubsequence(nCommon, aCommon, bCommon)` receives the number of adjacent items and starting indexes of each common subsequence. If sequences do not have common items, then this package does not call your function. If N is the sum of lengths of sequences and L is length of a longest common subsequence, then D = N – 2L is the number of **differences** in the corresponding shortest edit script. [_An O(ND) Difference Algorithm and Its Variations_](http://xmailserver.org/diff2.pdf) by Eugene W. Myers is fast when sequences have **few** differences. This package implements the **linear space** variation with optimizations so it is fast even when sequences have **many** differences. ## Usage To add this package as a dependency of a project, do either of the following: - `npm install diff-sequences` - `yarn add diff-sequences` To use `diff` as the name of the default export from this package, do either of the following: - `var diff = require('diff-sequences').default; // CommonJS modules` - `import diff from 'diff-sequences'; // ECMAScript modules` Call `diff` with the **lengths** of sequences and your **callback** functions: ```js const a = ['a', 'b', 'c', 'a', 'b', 'b', 'a']; const b = ['c', 'b', 'a', 'b', 'a', 'c']; function isCommon(aIndex, bIndex) { return a[aIndex] === b[bIndex]; } function foundSubsequence(nCommon, aCommon, bCommon) { // see examples } diff(a.length, b.length, isCommon, foundSubsequence); ``` ## Example of longest common subsequence Some sequences (for example, `a` and `b` in the example of usage) have more than one longest common subsequence. This package finds the following common items: | comparisons of common items | values | output arguments | | :------------------------------- | :--------- | --------------------------: | | `a[2] === b[0]` | `'c'` | `foundSubsequence(1, 2, 0)` | | `a[4] === b[1]` | `'b'` | `foundSubsequence(1, 4, 1)` | | `a[5] === b[3] && a[6] === b[4]` | `'b', 'a'` | `foundSubsequence(2, 5, 3)` | The “edit graph” analogy in the Myers paper shows the following common items: | comparisons of common items | values | | :------------------------------- | :--------- | | `a[2] === b[0]` | `'c'` | | `a[3] === b[2] && a[4] === b[3]` | `'a', 'b'` | | `a[6] === b[4]` | `'a'` | Various packages which implement the Myers algorithm will **always agree** on the **length** of a longest common subsequence, but might **sometimes disagree** on which **items** are in it. ## Example of callback functions to count common items ```js // Return length of longest common subsequence according to === operator. function countCommonItems(a, b) { let n = 0; function isCommon(aIndex, bIndex) { return a[aIndex] === b[bIndex]; } function foundSubsequence(nCommon) { n += nCommon; } diff(a.length, b.length, isCommon, foundSubsequence); return n; } const commonLength = countCommonItems( ['a', 'b', 'c', 'a', 'b', 'b', 'a'], ['c', 'b', 'a', 'b', 'a', 'c'], ); ``` | category of items | expression | value | | :----------------- | ------------------------: | ----: | | in common | `commonLength` | `4` | | to delete from `a` | `a.length - commonLength` | `3` | | to insert from `b` | `b.length - commonLength` | `2` | If the length difference `b.length - a.length` is: - negative: its absolute value is the minimum number of items to **delete** from `a` - positive: it is the minimum number of items to **insert** from `b` - zero: there is an **equal** number of items to delete from `a` and insert from `b` - non-zero: there is an equal number of **additional** items to delete from `a` and insert from `b` In this example, `6 - 7` is: - negative: `1` is the minimum number of items to **delete** from `a` - non-zero: `2` is the number of **additional** items to delete from `a` and insert from `b` ## Example of callback functions to find common items ```js // Return array of items in longest common subsequence according to Object.is method. const findCommonItems = (a, b) => { const array = []; diff( a.length, b.length, (aIndex, bIndex) => Object.is(a[aIndex], b[bIndex]), (nCommon, aCommon) => { for (; nCommon !== 0; nCommon -= 1, aCommon += 1) { array.push(a[aCommon]); } }, ); return array; }; const commonItems = findCommonItems( ['a', 'b', 'c', 'a', 'b', 'b', 'a'], ['c', 'b', 'a', 'b', 'a', 'c'], ); ``` | `i` | `commonItems[i]` | `aIndex` | | --: | :--------------- | -------: | | `0` | `'c'` | `2` | | `1` | `'b'` | `4` | | `2` | `'b'` | `5` | | `3` | `'a'` | `6` | ## Example of callback functions to diff index intervals Instead of slicing array-like objects, you can adjust indexes in your callback functions. ```js // Diff index intervals that are half open [start, end) like array slice method. const diffIndexIntervals = (a, aStart, aEnd, b, bStart, bEnd) => { // Validate: 0 <= aStart and aStart <= aEnd and aEnd <= a.length // Validate: 0 <= bStart and bStart <= bEnd and bEnd <= b.length diff( aEnd - aStart, bEnd - bStart, (aIndex, bIndex) => Object.is(a[aStart + aIndex], b[bStart + bIndex]), (nCommon, aCommon, bCommon) => { // aStart + aCommon, bStart + bCommon }, ); // After the last common subsequence, do any remaining work. }; ``` ## Example of callback functions to emulate diff command Linux or Unix has a `diff` command to compare files line by line. Its output is a **shortest edit script**: - **c**hange adjacent lines from the first file to lines from the second file - **d**elete lines from the first file - **a**ppend or insert lines from the second file ```js // Given zero-based half-open range [start, end) of array indexes, // return one-based closed range [start + 1, end] as string. const getRange = (start, end) => start + 1 === end ? `${start + 1}` : `${start + 1},${end}`; // Given index intervals of lines to delete or insert, or both, or neither, // push formatted diff lines onto array. const pushDelIns = (aLines, aIndex, aEnd, bLines, bIndex, bEnd, array) => { const deleteLines = aIndex !== aEnd; const insertLines = bIndex !== bEnd; const changeLines = deleteLines && insertLines; if (changeLines) { array.push(getRange(aIndex, aEnd) + 'c' + getRange(bIndex, bEnd)); } else if (deleteLines) { array.push(getRange(aIndex, aEnd) + 'd' + String(bIndex)); } else if (insertLines) { array.push(String(aIndex) + 'a' + getRange(bIndex, bEnd)); } else { return; } for (; aIndex !== aEnd; aIndex += 1) { array.push('< ' + aLines[aIndex]); // delete is less than } if (changeLines) { array.push('---'); } for (; bIndex !== bEnd; bIndex += 1) { array.push('> ' + bLines[bIndex]); // insert is greater than } }; // Given content of two files, return emulated output of diff utility. const findShortestEditScript = (a, b) => { const aLines = a.split('\n'); const bLines = b.split('\n'); const aLength = aLines.length; const bLength = bLines.length; const isCommon = (aIndex, bIndex) => aLines[aIndex] === bLines[bIndex]; let aIndex = 0; let bIndex = 0; const array = []; const foundSubsequence = (nCommon, aCommon, bCommon) => { pushDelIns(aLines, aIndex, aCommon, bLines, bIndex, bCommon, array); aIndex = aCommon + nCommon; // number of lines compared in a bIndex = bCommon + nCommon; // number of lines compared in b }; diff(aLength, bLength, isCommon, foundSubsequence); // After the last common subsequence, push remaining change lines. pushDelIns(aLines, aIndex, aLength, bLines, bIndex, bLength, array); return array.length === 0 ? '' : array.join('\n') + '\n'; }; ``` ## Example of callback functions to format diff lines Here is simplified code to format **changed and unchanged lines** in expected and received values after a test fails in Jest: ```js // Format diff with minus or plus for change lines and space for common lines. const formatDiffLines = (a, b) => { // Jest depends on pretty-format package to serialize objects as strings. // Unindented for comparison to avoid distracting differences: const aLinesUn = format(a, {indent: 0 /*, other options*/}).split('\n'); const bLinesUn = format(b, {indent: 0 /*, other options*/}).split('\n'); // Indented to display changed and unchanged lines: const aLinesIn = format(a, {indent: 2 /*, other options*/}).split('\n'); const bLinesIn = format(b, {indent: 2 /*, other options*/}).split('\n'); const aLength = aLinesIn.length; // Validate: aLinesUn.length === aLength const bLength = bLinesIn.length; // Validate: bLinesUn.length === bLength const isCommon = (aIndex, bIndex) => aLinesUn[aIndex] === bLinesUn[bIndex]; // Only because the GitHub Flavored Markdown doc collapses adjacent spaces, // this example code and the following table represent spaces as middle dots. let aIndex = 0; let bIndex = 0; const array = []; const foundSubsequence = (nCommon, aCommon, bCommon) => { for (; aIndex !== aCommon; aIndex += 1) { array.push('-·' + aLinesIn[aIndex]); // delete is minus } for (; bIndex !== bCommon; bIndex += 1) { array.push('+·' + bLinesIn[bIndex]); // insert is plus } for (; nCommon !== 0; nCommon -= 1, aIndex += 1, bIndex += 1) { // For common lines, received indentation seems more intuitive. array.push('··' + bLinesIn[bIndex]); // common is space } }; diff(aLength, bLength, isCommon, foundSubsequence); // After the last common subsequence, push remaining change lines. for (; aIndex !== aLength; aIndex += 1) { array.push('-·' + aLinesIn[aIndex]); } for (; bIndex !== bLength; bIndex += 1) { array.push('+·' + bLinesIn[bIndex]); } return array; }; const expected = { searching: '', sorting: { ascending: true, fieldKey: 'what', }, }; const received = { searching: '', sorting: [ { descending: false, fieldKey: 'what', }, ], }; const diffLines = formatDiffLines(expected, received); ``` If N is the sum of lengths of sequences and L is length of a longest common subsequence, then N – L is length of an array of diff lines. In this example, N is 7 + 9, L is 5, and N – L is 11. | `i` | `diffLines[i]` | `aIndex` | `bIndex` | | ---: | :--------------------------------- | -------: | -------: | | `0` | `'··Object {'` | `0` | `0` | | `1` | `'····"searching": "",'` | `1` | `1` | | `2` | `'-···"sorting": Object {'` | `2` | | | `3` | `'-·····"ascending": true,'` | `3` | | | `4` | `'+·····"sorting": Array ['` | | `2` | | `5` | `'+·······Object {'` | | `3` | | `6` | `'+·········"descending": false,'` | | `4` | | `7` | `'··········"fieldKey": "what",'` | `4` | `5` | | `8` | `'········},'` | `5` | `6` | | `9` | `'+·····],'` | | `7` | | `10` | `'··}'` | `6` | `8` | ## Example of callback functions to find diff items Here is simplified code to find changed and unchanged substrings **within adjacent changed lines** in expected and received values after a test fails in Jest: ```js // Return diff items for strings (compatible with diff-match-patch package). const findDiffItems = (a, b) => { const isCommon = (aIndex, bIndex) => a[aIndex] === b[bIndex]; let aIndex = 0; let bIndex = 0; const array = []; const foundSubsequence = (nCommon, aCommon, bCommon) => { if (aIndex !== aCommon) { array.push([-1, a.slice(aIndex, aCommon)]); // delete is -1 } if (bIndex !== bCommon) { array.push([1, b.slice(bIndex, bCommon)]); // insert is 1 } aIndex = aCommon + nCommon; // number of characters compared in a bIndex = bCommon + nCommon; // number of characters compared in b array.push([0, a.slice(aCommon, aIndex)]); // common is 0 }; diff(a.length, b.length, isCommon, foundSubsequence); // After the last common subsequence, push remaining change items. if (aIndex !== a.length) { array.push([-1, a.slice(aIndex)]); } if (bIndex !== b.length) { array.push([1, b.slice(bIndex)]); } return array; }; const expectedDeleted = ['"sorting": Object {', '"ascending": true,'].join( '\n', ); const receivedInserted = [ '"sorting": Array [', 'Object {', '"descending": false,', ].join('\n'); const diffItems = findDiffItems(expectedDeleted, receivedInserted); ``` | `i` | `diffItems[i][0]` | `diffItems[i][1]` | | --: | ----------------: | :---------------- | | `0` | `0` | `'"sorting": '` | | `1` | `1` | `'Array [\n'` | | `2` | `0` | `'Object {\n"'` | | `3` | `-1` | `'a'` | | `4` | `1` | `'de'` | | `5` | `0` | `'scending": '` | | `6` | `-1` | `'tru'` | | `7` | `1` | `'fals'` | | `8` | `0` | `'e,'` | The length difference `b.length - a.length` is equal to the sum of `diffItems[i][0]` values times `diffItems[i][1]` lengths. In this example, the difference `48 - 38` is equal to the sum `10`. | category of diff item | `[0]` | `[1]` lengths | subtotal | | :-------------------- | ----: | -----------------: | -------: | | in common | `0` | `11 + 10 + 11 + 2` | `0` | | to delete from `a` | `–1` | `1 + 3` | `-4` | | to insert from `b` | `1` | `8 + 2 + 4` | `14` | Instead of formatting the changed substrings with escape codes for colors in the `foundSubsequence` function to save memory, this example spends memory to **gain flexibility** before formatting, so a separate heuristic algorithm might modify the generic array of diff items to show changes more clearly: | `i` | `diffItems[i][0]` | `diffItems[i][1]` | | --: | ----------------: | :---------------- | | `6` | `-1` | `'true'` | | `7` | `1` | `'false'` | | `8` | `0` | `','` | For expected and received strings of serialized data, the result of finding changed **lines**, and then finding changed **substrings** within adjacent changed lines (as in the preceding two examples) sometimes displays the changes in a more intuitive way than the result of finding changed substrings, and then splitting them into changed and unchanged lines. # <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 # 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.8.3 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. # 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._ JavaScript Numbers are represented as [IEEE 754 double-precision floats](http://steve.hollasch.net/cgindex/coding/ieeefloat.html). Unfortunately, this means they lose integer precision for values beyond +/- 2^^53. For projects that need to accurately handle 64-bit ints, such as [node-thrift](https://github.com/wadey/node-thrift), a performant, Number-like class is needed. Int64 is that class. Int64 instances look and feel much like JS-native Numbers. By way of example ... ```js // First, let's illustrate the problem ... > (0x123456789).toString(16) '123456789' // <- what we expect. > (0x123456789abcdef0).toString(16) '123456789abcdf00' // <- Ugh! JS doesn't do big ints. :( // So let's create a couple Int64s using the above values ... // Require, of course > Int64 = require('node-int64') // x's value is what we expect (the decimal value of 0x123456789) > x = new Int64(0x123456789) [Int64 value:4886718345 octets:00 00 00 01 23 45 67 89] // y's value is Infinity because it's outside the range of integer // precision. But that's okay - it's still useful because it's internal // representation (octets) is what we passed in > y = new Int64('123456789abcdef0') [Int64 value:Infinity octets:12 34 56 78 9a bc de f0] // Let's do some math. Int64's behave like Numbers. (Sorry, Int64 isn't // for doing 64-bit integer arithmetic (yet) - it's just for carrying // around int64 values > x + 1 4886718346 > y + 1 Infinity // Int64 string operations ... > 'value: ' + x 'value: 4886718345' > 'value: ' + y 'value: Infinity' > x.toString(2) '100100011010001010110011110001001' > y.toString(2) 'Infinity' // Use JS's isFinite() method to see if the Int64 value is in the // integer-precise range of JS values > isFinite(x) true > isFinite(y) false // Get an octet string representation. (Yay, y is what we put in!) > x.toOctetString() '0000000123456789' > y.toOctetString() '123456789abcdef0' // Finally, some other ways to create Int64s ... // Pass hi/lo words > new Int64(0x12345678, 0x9abcdef0) [Int64 value:Infinity octets:12 34 56 78 9a bc de f0] // Pass a Buffer > new Int64(new Buffer([0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0])) [Int64 value:Infinity octets:12 34 56 78 9a bc de f0] // Pass a Buffer and offset > new Int64(new Buffer([0,0,0,0,0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0]), 4) [Int64 value:Infinity octets:12 34 56 78 9a bc de f0] // Pull out into a buffer > new Int64(new Buffer([0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0])).toBuffer() <Buffer 12 34 56 78 9a bc de f0> // Or copy into an existing one (at an offset) > var buf = new Buffer(1024); > new Int64(new Buffer([0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0])).copy(buf, 512); ``` # 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). # 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:pass@example.com: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/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:alpha@example.com,bravo@example.com?subject=SUBSCRIBE&body=Sign%20me%20up!"); //returns: //{ // scheme : "mailto", // to : ["alpha@example.com", "bravo@example.com"], // subject : "SUBSCRIBE", // body : "Sign me up!" //} URI.serialize({ scheme : "mailto", to : ["alpha@example.com"], subject : "REMOVE", body : "Please remove me", headers : { cc : "charlie@example.com" } }) === "mailto:alpha@example.com?cc=charlie@example.com&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/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. # stylehacks > Detect/remove browser hacks from CSS files. ## Install With [npm](https://npmjs.org/package/stylehacks) do: ``` npm install stylehacks --save ``` ## Example In its default mode, stylehacks will remove hacks from your CSS file, based on the browsers that you wish to support. ### Input ```css h1 { _color: white; color: rgba(255, 255, 255, 0.5); } ``` ### Output ```css h1 { color: rgba(255, 255, 255, 0.5); } ``` ## API ### `stylehacks.detect(node)` Type: `function` Returns: `boolean` This method will take any PostCSS *node*, run applicable plugins depending on its type, then will return a boolean depending on whether it found any of the supported hacks. For example, if the `decl` node found below is passed to the `detect` function, it will return `true`. But if the `rule` node is passed, it will return `false` instead. ```css h1 { _color: red } ``` ### `stylehacks.process(css, [options]).then(function(result) {})` #### options ##### lint Type: `boolean` Default: `false` If lint mode is enabled, stylehacks will not remove hacks from the CSS; instead, it will add warnings to `Result#messages`. ### `postcss([ stylehacks(opts) ])` stylehacks can also be consumed as a PostCSS plugin. See the [documentation](https://github.com/postcss/postcss#usage) for examples for your environment. ## Related stylehacks works well with your existing PostCSS setup: * [stylelint] - Comprehensive & modern CSS linter, to ensure that your code style rules are respected. ## Contributing Pull requests are welcome. If you add functionality, then please add unit tests to cover it. ## License MIT © [Ben Briggs](http://beneb.info) [stylelint]: https://github.com/stylelint/stylelint # 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. # 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._ # 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 Technical Report #51](https://github.com/mathiasbynens/unicode-tr51). 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-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._ # 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`/`es2019` 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` ## Security Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. [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 # 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. **english** | [русский](https://github.com/svg/svgo/blob/master/README.ru.md) - - - <img src="https://svg.github.io/svgo-logo.svg" width="200" height="200" alt="logo"/> ## SVGO [![NPM version](https://badge.fury.io/js/svgo.svg)](https://npmjs.org/package/svgo) [![Build Status](https://secure.travis-ci.org/svg/svgo.svg)](https://travis-ci.org/svg/svgo) [![Coverage Status](https://img.shields.io/coveralls/svg/svgo.svg)](https://coveralls.io/r/svg/svgo?branch=master) **SVG O**ptimizer is a Nodejs-based tool for optimizing SVG vector graphics files. ![](https://mc.yandex.ru/watch/18431326) ## Why? SVG files, especially those exported from various editors, usually contain a lot of redundant and useless information. This can include editor metadata, comments, hidden elements, default or non-optimal values and other stuff that can be safely removed or converted without affecting the SVG rendering result. ## What it can do SVGO has a plugin-based architecture, so almost every optimization is a separate plugin. Today we have: | Plugin | Description | Default | | ------ | ----------- | ------- | | [cleanupAttrs](https://github.com/svg/svgo/blob/master/plugins/cleanupAttrs.js) | cleanup attributes from newlines, trailing, and repeating spaces | `enabled` | | [inlineStyles](https://github.com/svg/svgo/blob/master/plugins/inlineStyles.js) | move and merge styles from `<style>` elements to element `style` attributes | `enabled` | | [removeDoctype](https://github.com/svg/svgo/blob/master/plugins/removeDoctype.js) | remove doctype declaration | `enabled` | | [removeXMLProcInst](https://github.com/svg/svgo/blob/master/plugins/removeXMLProcInst.js) | remove XML processing instructions | `enabled` | | [removeComments](https://github.com/svg/svgo/blob/master/plugins/removeComments.js) | remove comments | `enabled` | | [removeMetadata](https://github.com/svg/svgo/blob/master/plugins/removeMetadata.js) | remove `<metadata>` | `enabled` | | [removeTitle](https://github.com/svg/svgo/blob/master/plugins/removeTitle.js) | remove `<title>` | `enabled` | | [removeDesc](https://github.com/svg/svgo/blob/master/plugins/removeDesc.js) | remove `<desc>` | `enabled` | | [removeUselessDefs](https://github.com/svg/svgo/blob/master/plugins/removeUselessDefs.js) | remove elements of `<defs>` without `id` | `enabled` | | [removeXMLNS](https://github.com/svg/svgo/blob/master/plugins/removeXMLNS.js) | removes `xmlns` attribute (for inline svg) | `disabled` | | [removeEditorsNSData](https://github.com/svg/svgo/blob/master/plugins/removeEditorsNSData.js) | remove editors namespaces, elements, and attributes | `enabled` | | [removeEmptyAttrs](https://github.com/svg/svgo/blob/master/plugins/removeEmptyAttrs.js) | remove empty attributes | `enabled` | | [removeHiddenElems](https://github.com/svg/svgo/blob/master/plugins/removeHiddenElems.js) | remove hidden elements | `enabled` | | [removeEmptyText](https://github.com/svg/svgo/blob/master/plugins/removeEmptyText.js) | remove empty Text elements | `enabled` | | [removeEmptyContainers](https://github.com/svg/svgo/blob/master/plugins/removeEmptyContainers.js) | remove empty Container elements | `enabled` | | [removeViewBox](https://github.com/svg/svgo/blob/master/plugins/removeViewBox.js) | remove `viewBox` attribute when possible | `enabled` | | [cleanupEnableBackground](https://github.com/svg/svgo/blob/master/plugins/cleanupEnableBackground.js) | remove or cleanup `enable-background` attribute when possible | `enabled` | | [minifyStyles](https://github.com/svg/svgo/blob/master/plugins/minifyStyles.js) | minify `<style>` elements content with [CSSO](https://github.com/css/csso) | `enabled` | | [convertStyleToAttrs](https://github.com/svg/svgo/blob/master/plugins/convertStyleToAttrs.js) | convert styles into attributes | `enabled` | | [convertColors](https://github.com/svg/svgo/blob/master/plugins/convertColors.js) | convert colors (from `rgb()` to `#rrggbb`, from `#rrggbb` to `#rgb`) | `enabled` | | [convertPathData](https://github.com/svg/svgo/blob/master/plugins/convertPathData.js) | convert Path data to relative or absolute (whichever is shorter), convert one segment to another, trim useless delimiters, smart rounding, and much more | `enabled` | | [convertTransform](https://github.com/svg/svgo/blob/master/plugins/convertTransform.js) | collapse multiple transforms into one, convert matrices to the short aliases, and much more | `enabled` | | [removeUnknownsAndDefaults](https://github.com/svg/svgo/blob/master/plugins/removeUnknownsAndDefaults.js) | remove unknown elements content and attributes, remove attrs with default values | `enabled` | | [removeNonInheritableGroupAttrs](https://github.com/svg/svgo/blob/master/plugins/removeNonInheritableGroupAttrs.js) | remove non-inheritable group's "presentation" attributes | `enabled` | | [removeUselessStrokeAndFill](https://github.com/svg/svgo/blob/master/plugins/removeUselessStrokeAndFill.js) | remove useless `stroke` and `fill` attrs | `enabled` | | [removeUnusedNS](https://github.com/svg/svgo/blob/master/plugins/removeUnusedNS.js) | remove unused namespaces declaration | `enabled` | | [prefixIds](https://github.com/svg/svgo/blob/master/plugins/prefixIds.js) | prefix IDs and classes with the SVG filename or an arbitrary string | `disabled` | | [cleanupIDs](https://github.com/svg/svgo/blob/master/plugins/cleanupIDs.js) | remove unused and minify used IDs | `enabled` | | [cleanupNumericValues](https://github.com/svg/svgo/blob/master/plugins/cleanupNumericValues.js) | round numeric values to the fixed precision, remove default `px` units | `enabled` | | [cleanupListOfValues](https://github.com/svg/svgo/blob/master/plugins/cleanupListOfValues.js) | round numeric values in attributes that take a list of numbers (like `viewBox` or `enable-background`) | `disabled` | | [moveElemsAttrsToGroup](https://github.com/svg/svgo/blob/master/plugins/moveElemsAttrsToGroup.js) | move elements' attributes to their enclosing group | `enabled` | | [moveGroupAttrsToElems](https://github.com/svg/svgo/blob/master/plugins/moveGroupAttrsToElems.js) | move some group attributes to the contained elements | `enabled` | | [collapseGroups](https://github.com/svg/svgo/blob/master/plugins/collapseGroups.js) | collapse useless groups | `enabled` | | [removeRasterImages](https://github.com/svg/svgo/blob/master/plugins/removeRasterImages.js) | remove raster images | `disabled` | | [mergePaths](https://github.com/svg/svgo/blob/master/plugins/mergePaths.js) | merge multiple Paths into one | `enabled` | | [convertShapeToPath](https://github.com/svg/svgo/blob/master/plugins/convertShapeToPath.js) | convert some basic shapes to `<path>` | `enabled` | | [convertEllipseToCircle](https://github.com/svg/svgo/blob/master/plugins/convertEllipseToCircle.js) | convert non-eccentric `<ellipse>` to `<circle>` | `enabled` | | [sortAttrs](https://github.com/svg/svgo/blob/master/plugins/sortAttrs.js) | sort element attributes for epic readability | `disabled` | | [sortDefsChildren](https://github.com/svg/svgo/blob/master/plugins/sortDefsChildren.js) | sort children of `<defs>` in order to improve compression | `enabled` | | [removeDimensions](https://github.com/svg/svgo/blob/master/plugins/removeDimensions.js) | remove `width`/`height` and add `viewBox` if it's missing (opposite to removeViewBox, disable it first) | `disabled` | | [removeAttrs](https://github.com/svg/svgo/blob/master/plugins/removeAttrs.js) | remove attributes by pattern | `disabled` | | [removeAttributesBySelector](https://github.com/svg/svgo/blob/master/plugins/removeAttributesBySelector.js) | removes attributes of elements that match a css selector | `disabled` | | [removeElementsByAttr](https://github.com/svg/svgo/blob/master/plugins/removeElementsByAttr.js) | remove arbitrary elements by ID or className | `disabled` | | [addClassesToSVGElement](https://github.com/svg/svgo/blob/master/plugins/addClassesToSVGElement.js) | add classnames to an outer `<svg>` element | `disabled` | | [addAttributesToSVGElement](https://github.com/svg/svgo/blob/master/plugins/addAttributesToSVGElement.js) | adds attributes to an outer `<svg>` element | `disabled` | | [removeOffCanvasPaths](https://github.com/svg/svgo/blob/master/plugins/removeOffCanvasPaths.js) | removes elements that are drawn outside of the viewbox | `disabled` | | [removeStyleElement](https://github.com/svg/svgo/blob/master/plugins/removeStyleElement.js) | remove `<style>` elements | `disabled` | | [removeScriptElement](https://github.com/svg/svgo/blob/master/plugins/removeScriptElement.js) | remove `<script>` elements | `disabled` | | [reusePaths](https://github.com/svg/svgo/blob/master/plugins/reusePaths.js) | Find duplicated <path> elements and replace them with <use> links | `disabled` | Want to know how it works and how to write your own plugin? [Of course you want to](https://github.com/svg/svgo/blob/master/docs/how-it-works/en.md). ([동작방법](https://github.com/svg/svgo/blob/master/docs/how-it-works/ko.md)) ## Installation ```sh $ [sudo] npm install -g svgo ``` ## Usage ### <abbr title="Command Line Interface">CLI</abbr> ``` Usage: svgo [OPTIONS] [ARGS] Options: -h, --help : Help -v, --version : Version -i INPUT, --input=INPUT : Input file, "-" for STDIN -s STRING, --string=STRING : Input SVG data string -f FOLDER, --folder=FOLDER : Input folder, optimize and rewrite all *.svg files -o OUTPUT, --output=OUTPUT : Output file or folder (by default the same as the input), "-" for STDOUT -p PRECISION, --precision=PRECISION : Set number of digits in the fractional part, overrides plugins params --config=CONFIG : Config file or JSON string to extend or replace default --disable=PLUGIN : Disable plugin by name, "--disable=PLUGIN1,PLUGIN2" for multiple plugins --enable=PLUGIN : Enable plugin by name, "--enable=PLUGIN3,PLUGIN4" for multiple plugins --datauri=DATAURI : Output as Data URI string (base64, URI encoded or unencoded) --multipass : Pass over SVGs multiple times to ensure all optimizations are applied --pretty : Make SVG pretty printed --indent=INDENT : Indent number when pretty printing SVGs -r, --recursive : Use with '-f'. Optimizes *.svg files in folders recursively. -q, --quiet : Only output error messages, not regular status messages --show-plugins : Show available plugins and exit Arguments: INPUT : Alias to --input ``` * with files: ```sh $ svgo test.svg ``` or: ```sh $ svgo *.svg ``` ```sh $ svgo test.svg -o test.min.svg ``` ```sh $ svgo test.svg other.svg third.svg ``` ```sh $ svgo test.svg other.svg third.svg -o test.min.svg -o other.min.svg -o third.min.svg ``` * with STDIN / STDOUT: ```sh $ cat test.svg | svgo -i - -o - > test.min.svg ``` * with folder ```sh $ svgo -f ../path/to/folder/with/svg/files ``` or: ```sh $ svgo -f ../path/to/folder/with/svg/files -o ../path/to/folder/with/svg/output ``` ```sh $ svgo *.svg -o ../path/to/folder/with/svg/output ``` * with strings: ```sh $ svgo -s '<svg version="1.1">test</svg>' -o test.min.svg ``` or even with Data URI base64: ```sh $ svgo -s 'data:image/svg+xml;base64,...' -o test.min.svg ``` * with SVGZ: from `.svgz` to `.svg`: ```sh $ gunzip -c test.svgz | svgo -i - -o test.min.svg ``` from `.svg` to `.svgz`: ```sh $ svgo test.svg -o - | gzip -cfq9 > test.svgz ``` ### Other Ways to Use SVGO * as a web app – [SVGOMG](https://jakearchibald.github.io/svgomg/) * as a Nodejs module – [examples](https://github.com/svg/svgo/tree/master/examples) * as a Grunt task – [grunt-svgmin](https://github.com/sindresorhus/grunt-svgmin) * as a Gulp task – [gulp-svgmin](https://github.com/ben-eb/gulp-svgmin) * as a Mimosa module – [mimosa-minify-svg](https://github.com/dbashford/mimosa-minify-svg) * as an OSX Folder Action – [svgo-osx-folder-action](https://github.com/svg/svgo-osx-folder-action) * as a webpack loader – [image-webpack-loader](https://github.com/tcoopman/image-webpack-loader) * as a Telegram Bot – [svgo_bot](https://github.com/maksugr/svgo_bot) * as a PostCSS plugin – [postcss-svgo](https://github.com/ben-eb/postcss-svgo) * as an Inkscape plugin – [inkscape-svgo](https://github.com/konsumer/inkscape-svgo) * as a Sketch plugin - [svgo-compressor](https://github.com/BohemianCoding/svgo-compressor) * as macOS app - [Image Shrinker](https://image-shrinker.com) * as a Rollup plugin - [rollup-plugin-svgo](https://github.com/porsager/rollup-plugin-svgo) ## Backers | [<img src="https://sheetjs.com/sketch128.png" width="80">](https://sheetjs.com/) | [<img src="https://rawgithub.com/fontello/fontello/master/fontello-image.svg" width="80">](http://fontello.com/) | |:-:|:-:| | [SheetJS LLC](https://sheetjs.com/) | [Fontello](http://fontello.com/) | ## Donations - PayPal: https://www.paypal.me/deepsweet ## License and Copyright This software is released under the terms of the [MIT license](https://github.com/svg/svgo/blob/master/LICENSE). Logo by [Yegor Bolshakov](http://xizzzy.ru/). ## istanbul-lib-instrument [![Build Status](https://travis-ci.org/istanbuljs/istanbul-lib-instrument.svg?branch=master)](https://travis-ci.org/istanbuljs/istanbul-lib-instrument) Istanbul instrumenter library. Version 1.1.x now implements instrumentation using `Babel`. The implementation is inspired by prior art by @dtinth as demonstrated in the `__coverage__` babel plugin. It provides 2 "modes" of instrumentation. - The old API that is mostly unchanged (except for incompatibilities noted) and performs the instrumentation using babel as a library. - A `programVisitor` function for the Babel AST that can be used by a Babel plugin to emit instrumentation for ES6 code directly without any source map processing. This is the preferred path for babel users. The Babel plugin is called `babel-plugin-istanbul`. Incompatibilities and changes to instrumentation behavior can be found in [v0-changes.md](v0-changes.md). # 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._ #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 # 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) [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;lauri@rooden.ee&gt; [The MIT License](http://lauri.rooden.ee/mit-license.txt) # 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.3.2. 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 `Indentifier` 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, 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. # 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. # 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._ # 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. The `&` character before methods is required because they are not static methods but instance methods. ``` 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("Func1", &[ClassName]::Func1), InstanceMethod("Func2", &[ClassName]::Func2), InstanceAccessor("Value", &[ClassName]::ValueGetter), StaticMethod("MethodName", &[ClassName]::StaticMethod), 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. # 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._ # 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._ # 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._ # 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 --save 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', …] var ignoredDirectories = require('ignore-by-default').directories() ``` # duplexer3 [![Build Status](https://travis-ci.org/floatdrop/duplexer3.svg?branch=master)](https://travis-ci.org/floatdrop/duplexer3) [![Coverage Status](https://coveralls.io/repos/floatdrop/duplexer3/badge.svg?branch=master&service=github)](https://coveralls.io/github/floatdrop/duplexer3?branch=master) Like [duplexer2](https://github.com/deoxxa/duplexer2) but using Streams3 without readable-stream dependency ```javascript var stream = require("stream"); var duplexer3 = require("duplexer3"); var writable = new stream.Writable({objectMode: true}), readable = new stream.Readable({objectMode: true}); writable._write = function _write(input, encoding, done) { if (readable.push(input)) { return done(); } else { readable.once("drain", done); } }; readable._read = function _read(n) { // no-op }; // simulate the readable thing closing after a bit writable.once("finish", function() { setTimeout(function() { readable.push(null); }, 500); }); var duplex = duplexer3(writable, readable); duplex.on("data", function(e) { console.log("got data", JSON.stringify(e)); }); duplex.on("finish", function() { console.log("got finish event"); }); duplex.on("end", function() { console.log("got end event"); }); duplex.write("oh, hi there", function() { console.log("finished writing"); }); duplex.end(function() { console.log("finished ending"); }); ``` ``` got data "oh, hi there" finished writing got finish event finished ending got end event ``` ## Overview This is a reimplementation of [duplexer](https://www.npmjs.com/package/duplexer) using the Streams3 API which is standard in Node as of v4. Everything largely works the same. ## Installation [Available via `npm`](https://docs.npmjs.com/cli/install): ``` $ npm i duplexer3 ``` ## API ### duplexer3 Creates a new `DuplexWrapper` object, which is the actual class that implements most of the fun stuff. All that fun stuff is hidden. DON'T LOOK. ```javascript duplexer3([options], writable, readable) ``` ```javascript const duplex = duplexer3(new stream.Writable(), new stream.Readable()); ``` Arguments * __options__ - an object specifying the regular `stream.Duplex` options, as well as the properties described below. * __writable__ - a writable stream * __readable__ - a readable stream Options * __bubbleErrors__ - a boolean value that specifies whether to bubble errors from the underlying readable/writable streams. Default is `true`. ## License 3-clause BSD. [A copy](./LICENSE) is included with the source. ## Contact * GitHub ([deoxxa](http://github.com/deoxxa)) * Twitter ([@deoxxa](http://twitter.com/deoxxa)) * Email ([deoxxa@fknsrs.biz](mailto:deoxxa@fknsrs.biz)) # 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 # `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 ``` # :rocket: fast-glob > Is a faster [`node-glob`](https://github.com/isaacs/node-glob) alternative. ## :bulb: Highlights * :rocket: Fast by using Streams and Promises. Used [readdir-enhanced](https://github.com/BigstickCarpet/readdir-enhanced) and [micromatch](https://github.com/jonschlinkert/micromatch). * :beginner: User-friendly, since it supports multiple and negated patterns (`['*', '!*.md']`). * :vertical_traffic_light: Rational, because it doesn't read excluded directories (`!**/node_modules/**`). * :gear: Universal, because it supports Synchronous, Promise and Stream API. * :money_with_wings: Economy, because it provides `fs.Stats` for matched path if you wanted. ## Donate If you want to thank me, or promote your Issue. [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://paypal.me/mrmlnc) > Sorry, but I have work and support for packages requires some time after work. I will be glad of your support and PR's. ## Install ``` $ npm install --save fast-glob ``` ## Usage #### Asynchronous ```js const fg = require('fast-glob'); fg(['src/**/*.js', '!src/**/*.spec.js']).then((entries) => console.log(entries)); fg.async(['src/**/*.js', '!src/**/*.spec.js']).then((entries) => console.log(entries)); ``` #### Synchronous ```js const fg = require('fast-glob'); const entries = fg.sync(['src/**/*.js', '!src/**/*.spec.js']); console.log(entries); ``` #### Stream ```js const fg = require('fast-glob'); const stream = fg.stream(['src/**/*.js', '!src/**/*.spec.js']); const entries = []; stream.on('data', (entry) => entries.push(entry)); stream.once('error', console.log); stream.once('end', () => console.log(entries)); ``` ## API ### fg(patterns, [options]) ### fg.async(patterns, [options]) Returns a `Promise` with an array of matching [entries](#entry). ### fg.sync(patterns, [options]) Returns an array of matching [entries](#entry). ### fg.stream(patterns, [options]) Returns a [`ReadableStream`](https://nodejs.org/api/stream.html#stream_readable_streams) when the `data` event will be emitted with [`Entry`](#entry). #### patterns * Type: `string|string[]` This package does not respect the order of patterns. First, all the negative patterns are applied, and only then the positive patterns. #### options * Type: `Object` See [options](#options-1) section for more detailed information. ### fg.generateTasks(patterns, [options]) Return a set of tasks based on provided patterns. All tasks satisfy the `Task` interface: ```ts interface Task { /** * Parent directory for all patterns inside this task. */ base: string; /** * Dynamic or static patterns are in this task. */ dynamic: boolean; /** * All patterns. */ patterns: string[]; /** * Only positive patterns. */ positive: string[]; /** * Only negative patterns without ! symbol. */ negative: string[]; } ``` ## Entry The entry which can be a `string` if the [`stats`](#stats) option is disabled, otherwise `fs.Stats` with two additional `path` and `depth` properties. ## Options #### cwd * Type: `string` * Default: `process.cwd()` The current working directory in which to search. #### deep * Type: `number|boolean` * Default: `true` The deep option can be set to `true` to traverse the entire directory structure, or it can be set to a *number* to only traverse that many levels deep. For example, you have the following tree: ``` test └── one └── two └── index.js ``` > :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` option. ```js fg('test/**', { onlyFiles: false, deep: 0 }); // -> ['test/one'] fg('test/**', { onlyFiles: false, deep: 1 }); // -> ['test/one', 'test/one/two'] fg('**', { onlyFiles: false, cwd: 'test', deep: 0 }); // -> ['one'] fg('**', { onlyFiles: false, cwd: 'test', deep: 1 }); // -> ['one', 'one/two'] ``` #### ignore * Type: `string[]` * Default: `[]` An array of glob patterns to exclude matches. #### dot * Type: `boolean` * Default: `false` Allow patterns to match filenames starting with a period (files & directories), even if the pattern does not explicitly have a period in that spot. #### stats * Type: `boolean` * Default: `false` Return `fs.Stats` with two additional `path` and `depth` properties instead of a `string`. #### onlyFiles * Type: `boolean` * Default: `true` Return only files. #### onlyDirectories * Type: `boolean` * Default: `false` Return only directories. #### followSymlinkedDirectories * Type: `boolean` * Default: `true` Follow symlinked directories when expanding `**` patterns. #### unique * Type: `boolean` * Default: `true` Prevent duplicate results. #### markDirectories * Type: `boolean` * Default: `false` Add a `/` character to directory entries. #### absolute * Type: `boolean` * Default: `false` Return absolute paths for matched entries. > :book: Note that you need to use this option if you want to use absolute negative patterns like `${__dirname}/*.md`. #### nobrace * Type: `boolean` * Default: `false` Disable expansion of brace patterns (`{a,b}`, `{1..3}`). #### brace * Type: `boolean` * Default: `true` The [`nobrace`](#nobrace) option without double-negation. This option has a higher priority then `nobrace`. #### noglobstar * Type: `boolean` * Default: `false` Disable matching with globstars (`**`). #### globstar * Type: `boolean` * Default: `true` The [`noglobstar`](#noglobstar) option without double-negation. This option has a higher priority then `noglobstar`. #### noext * Type: `boolean` * Default: `false` Disable extglob support (patterns like `+(a|b)`), so that extglobs are regarded as literal characters. #### extension * Type: `boolean` * Default: `true` The [`noext`](#noext) option without double-negation. This option has a higher priority then `noext`. #### nocase * Type: `boolean` * Default: `false` Disable a [case-sensitive](https://en.wikipedia.org/wiki/Case_sensitivity) mode for matching files. ##### Examples * File System: `test/file.md`, `test/File.md` * Case-sensitive for `test/file.*` pattern (`false`): `test/file.md` * Case-insensitive for `test/file.*` pattern (`true`): `test/file.md`, `test/File.md` #### case * Type: `boolean` * Default: `true` The [`nocase`](#nocase) option without double-negation. This option has a higher priority then `nocase`. #### matchBase * Type: `boolean` * Default: `false` Allow glob patterns without slashes to match a file path based on its basename. For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. #### transform * Type: `Function` * Default: `null` Allows you to transform a path or `fs.Stats` object before sending to the array. ```js const fg = require('fast-glob'); const entries1 = fg.sync(['**/*.scss']); const entries2 = fg.sync(['**/*.scss'], { transform: (entry) => '_' + entry }); console.log(entries1); // ['a.scss', 'b.scss'] console.log(entries2); // ['_a.scss', '_b.scss'] ``` If you are using **TypeScript**, you probably want to specify your own type of the returned array. ```ts import * as fg from 'fast-glob'; interface IMyOwnEntry { path: string; } const entries: IMyOwnEntry[] = fg.sync<IMyOwnEntry>(['*.md'], { transform: (entry) => typeof entry === 'string' ? { path: entry } : { path: entry.path } // Will throw compilation error for non-IMyOwnEntry types (boolean, for example) }); ``` ## How to exclude directory from reading? You can use a negative pattern like this: `!**/node_modules` or `!**/node_modules/**`. Also you can use `ignore` option. Just look at the example below. ``` 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.txt'] fg.sync(['**/*.md'], { ignore: '**/second/**' }); // ['first/file.txt'] ``` > :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 UNC paths as patterns (due to syntax), but you can use them as `cwd` directory. ```ts fg.sync('*', { cwd: '\\\\?\\C:\\Python27' /* or //?/C:/Python27 */ }); fg.sync('Python27/*', { cwd: '\\\\?\\C:\\' /* or //?/C:/ */ }); ``` ## Compatible with `node-glob`? Not fully, because `fast-glob` does not implement all options of `node-glob`. See table below. | node-glob | fast-glob | | :----------: | :-------: | | `cwd` | [`cwd`](#cwd) | | `root` | – | | `dot` | [`dot`](#dot) | | `nomount` | – | | `mark` | [`markDirectories`](#markdirectories) | | `nosort` | – | | `nounique` | [`unique`](#unique) | | `nobrace` | [`nobrace`](#nobrace) or [`brace`](#brace) | | `noglobstar` | [`noglobstar`](#noglobstar) or [`globstar`](#globstar) | | `noext` | [`noext`](#noext) or [`extension`](#extension) | | `nocase` | [`nocase`](#nocase) or [`case`](#case) | | `matchBase` | [`matchbase`](#matchbase) | | `nodir` | [`onlyFiles`](#onlyfiles) | | `ignore` | [`ignore`](#ignore) | | `follow` | [`followSymlinkedDirectories`](#followsymlinkeddirectories) | | `realpath` | – | | `absolute` | [`absolute`](#absolute) | ## Benchmarks **Tech specs:** Server: [Vultr Bare Metal](https://www.vultr.com/pricing/baremetal) * Processor: E3-1270v6 (8 CPU) * RAM: 32GB * Disk: SSD You can see results [here](https://gist.github.com/mrmlnc/f06246b197f53c356895fa35355a367c) for latest release. ## Related * [readdir-enhanced](https://github.com/BigstickCarpet/readdir-enhanced) – Fast functional replacement for `fs.readdir()`. * [globby](https://github.com/sindresorhus/globby) – User-friendly glob matching. * [node-glob](https://github.com/isaacs/node-glob) – «Standard» glob functionality for Node.js * [bash-glob](https://github.com/micromatch/bash-glob) – Bash-powered globbing for node.js. * [glob-stream](https://github.com/gulpjs/glob-stream) – A Readable Stream interface over node-glob that used in the [gulpjs](https://github.com/gulpjs/gulp). * [tiny-glob](https://github.com/terkelg/tiny-glob) – Tiny and extremely fast library to match files and folders using glob patterns. ## Changelog See the [Releases section of our GitHub project](https://github.com/mrmlnc/fast-glob/releases) for changelogs for each release version. ## License This software is released under the terms of the MIT license. # 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 # 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._ # 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._ # 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). # pn [![NPM][NPM1]][NPM2] [![Build Status][1]][2] The `pn` library gives you the Promise-using node standard library you've always dreamed of. Think "Promised Node" when saying it. Just about every node standard library method that takes a callback will now return a `Promise` iff no callback is supplied. But existing code that passes callbacks will still work fine --- and fast: No unnecessary `Promise`s are created if you supply a callback. The wrappers are generated automatically by a script, with a table to handle exceptions and odd cases. See below for more details. ## Installation ``` npm install pn ``` ## Usage ``` var fs = require('pn/fs'); fs.writeFile('foo', 'bar', 'utf-8').then(function() { console.log('done'); }); // But you can use callbacks, too -- existing code won't break. fs.writeFile('foo', 'bat', 'utf-8', function(err) { console.log('yay'); }); ``` This library uses node native promises (ie `global.Promise`) by default, and thus works with node >= 0.11. You can use [`core-js`](https://www.npmjs.org/package/core-js) or [`es6-shim`](https://www.npmjs.org/package/es6-shim) to add ES6 Promises to earlier versions of node, for example: ``` require('es6-shim'); var fs = require('pn/fs'); ``` Just be sure that `es6-shim` is loaded before the `pn` package in that case. You might also want to look into packages like [`prfun`](https://www.npmjs.org/package/prfun) which add some helpers to make working with native promises much more fun. In particular, the `Promise#done` method is very useful when debugging, at least until v8's native Promise debugging capabilities are completed. ## Custom Promise types You can also specify a custom `Promise` type to use, as follows: ``` var MyPromise = require('prfun'); // Use prfun's Promises, for example. require('pn/_promise')(MyPromise); // This only needs to be done once. ``` ## Exceptions and odd cases The wrappers are automatically generated by `scripts/generate.js`; there is a table in that file which specifies all the odd cases. In general: if the node API has a callback which takes multiple value arguments, the `Promise` returned will be an object with named fields corresponding to the different values. If the node API takes a callback *and* returns a value, `pn` will return the original value with a nonenumerable field named `promise` corresponding to the callback. Combining these two cases: ``` var child_process = require('pn/child_process'); var cp = child_process.execFile('true'); console.log('pid', cp.pid); cp.promise.then(function(result) { console.log('stdout: ', result.stdout); console.log('stderr: ', result.stderr); }); ``` * `child_process`: The `exec` and `execFile` methods promise a object with fields named `stdout` and `stderr`. They return a `ChildProcess` object with a nonenumerable field named `promise` corresponding to the callback. * `crypto`: The `randomBytes` and `pseudoRandomBytes` methods are now always asynchronous, returning a `Promise` if no callback is supplied. Use the new `randomBytesSync` and `pseudoRandomBytesSync` methods if you want synchronous computation. *This is backwards incompatible with existing node code.* * `dns`: The `lookupService` method promises an object with fields named `hostname` and `service`. * `fs`: The `exists` method doesn't pass an error to its callback. The promisied version will never reject. The `write` method promises an object with fields named `written` and `data`. The `read` method promises an object with fields named `read` and `data`. * `http`, `https`: The `request` and `get` methods return a `ClientRequest` object with a nonenumerable field named `promise`, which will resolve to an `IncomingMessage` object. * `process`: You can defer computation to the next tick with `require('pn/process').nextTick().then(function(){...})` * `tls`: The `connect` and `createServer` return objects with a nonenumerable field named `promise`. There are a few object methods which are not promisified by this package: * `domain`: `Domain#bind`, `Domain#intercept` * `http`,`https`: `ClientRequest#setTimeout`, `IncomingMessage#setTimeout`, `Server#setTimeout`, `ServerResponse#setTimeout`, `Server#listen`, `Server#close` * `net`: `Server#listen`, `Server#close`, `Server#getConnections`, `Socket#write`, `Socket#setTimeout` * `readline`: `Interface#question` * `stream`: `Writable#write`, `Writable#end` * `dgram`: `Socket#send`, `Socket#bind`. ## Related packages Here are some other packages with similar aims: * [`promised-node`](https://www.npmjs.org/package/promised-node) * [`then-fs`](https://www.npmjs.org/package/then-fs) * [`final-fs`](https://www.npmjs.org/package/final-fs) ## License Copyright (c) 2014-2018 C. Scott Ananian 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. [NPM1]: https://nodei.co/npm/pn.png [NPM2]: https://nodei.co/npm/pn/ [1]: https://travis-ci.org/cscott/node-pn.svg [2]: https://travis-ci.org/cscott/node-pn # 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/ # 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). 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> 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 }); ``` # 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 `mime@1.x` 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 <!-- eslint-disable no-unused-vars --> ```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. <!-- eslint-disable no-undef --> ```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. <!-- eslint-disable no-undef --> ```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. <!-- eslint-disable no-undef --> ```js mime.extension('application/octet-stream') // 'bin' ``` ### mime.charset(type) Lookup the implied default charset of a content-type. <!-- eslint-disable no-undef --> ```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 ## 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 (olalonde@gmail.com) - James Talmage (james@talmage.io) - [Ruben Verborgh](https://ruben.verborgh.org/) ## License [https://github.com/follow-redirects/follow-redirects/blob/master/LICENSE](MIT License) # 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._ # alphanum-sort [![Build Status](https://travis-ci.org/TrySound/alphanum-sort.svg?branch=master)](https://travis-ci.org/TrySound/alphanum-sort) > Alphanumeric sorting algorithm ## Install With [npm](https://npmjs.org/package/alphanum-sort) do: ``` npm i alphanum-sort -S ``` ## Example ```js var sort = require('alphanum-sort'); var result = sort(['item20', 'item19', 'item1', 'item10', 'item2']); // ['item1', 'item2', 'item10', 'item19', 'item20'] ``` ## API ### alphanumSort(array, options) #### options ##### insensitive Type: `Boolean` Default: `false` Compares items case insensitively ##### sign Type: `Boolean` Default: `false` Allows `+` and `-` characters before numbers ## License MIT © [Bogdan Chadkin](https://github.com/trysound) # Parse `data:` URLs This package helps you parse `data:` URLs [according to the WHATWG Fetch Standard](https://fetch.spec.whatwg.org/#data-urls): ```js const parseDataURL = require("data-urls"); const textExample = parseDataURL("data:,Hello%2C%20World!"); console.log(textExample.mimeType.toString()); // "text/plain;charset=US-ASCII" console.log(textExample.body.toString()); // "Hello, World!" const htmlExample = dataURL("data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E"); console.log(htmlExample.mimeType.toString()); // "text/html" console.log(htmlExample.body.toString()); // <h1>Hello, World!</h1> const pngExample = parseDataURL("data:image/png;base64,iVBORw0KGgoAAA" + "ANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4" + "//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU" + "5ErkJggg=="); console.log(pngExample.mimeType.toString()); // "image/png" console.log(pngExample.body); // <Buffer 89 50 4e 47 0d ... > ``` ## API This package's main module's default export is a function that accepts a string and returns a `{ mimeType, body }` object, or `null` if the result cannot be parsed as a `data:` URL. - The `mimeType` property is an instance of [whatwg-mimetype](https://www.npmjs.com/package/whatwg-mimetype)'s `MIMEType` class. - The `body` property is a Node.js [`Buffer`](https://nodejs.org/docs/latest/api/buffer.html) instance. As shown in the examples above, both of these have useful `toString()` methods for manipulating them as string values. However… ### A word of caution on string decoding Because Node.js's `Buffer.prototype.toString()` assumes a UTF-8 encoding, simply doing `dataURL.body.toString()` may not work correctly if the `data:` URL's contents were not originally written in UTF-8. This includes if the encoding is "US-ASCII", [aka windows-1252](https://encoding.spec.whatwg.org/#names-and-labels), which is notable for being the default in many cases. A more complete decoding example would use the [whatwg-encoding](https://www.npmjs.com/package/whatwg-encoding) package as follows: ```js const parseDataURL = require("data-urls"); const { labelToName, decode } = require("whatwg-encoding"); const dataURL = parseDataURL(arbitraryString); const encodingName = labelToName(dataURL.mimeType.parameters.get("charset")); const bodyDecoded = decode(dataURL.body, encodingName); ``` For example, given an `arbitraryString` of `data:,Hello!`, this will produce a `bodyDecoded` of `"Hello!"`, as expected. But given an `arbitraryString` of `"data:,Héllo!"`, this will correctly produce a `bodyDecoded` of `"Héllo!"`, whereas just doing `dataURL.body.toString()` will give back `"Héllo!"`. In summary, only use `dataURL.body.toString()` when you are very certain your data is inside the ASCII range (i.e. code points within the range U+0000 to U+007F). ### Advanced functionality: parsing from a URL record If you are using the [whatwg-url](https://github.com/jsdom/whatwg-url) package, you may already have a "URL record" object on hand, as produced by that package's `parseURL` export. In that case, you can use this package's `fromURLRecord` export to save a bit of work: ```js const { parseURL } = require("whatwg-url"); const dataURLFromURLRecord = require("data-urls").fromURLRecord; const urlRecord = parseURL("data:,Hello%2C%20World!"); const dataURL = dataURLFromURLRecord(urlRecord); ``` In practice, we expect this functionality only to be used by consumers like [jsdom](https://www.npmjs.com/package/jsdom), which are using these packages at a very low level. # 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). # 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. # 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._ # hsla-regex [![Build Status](https://secure.travis-ci.org/regexps/hsla-regex.png?branch=master)](https://travis-ci.org/regexps/hsla-regex) Regex for matching HSLA colors. ## Installation ```bash npm install --save hsla-regex ``` ## Usage ```javascript var hslaRegex = require('hsla-regex'); hslaRegex({ exact: true }).test('hsla(123, 45%, 67%, .8)'); // => true hslaRegex({ exact: true }).test('foo bar'); // => false hslaRegex({ exact: true }).exec('hsla(1, 1.111%, 1.1111%, .8)'); // => [ // 'hsla(1, 1.111%, 1.1111%, .8)', // '1', // '1.111%', // '1.1111%', // '.8' // index: 0, // input: 'hsla(1, 1.111%, 1.1111%, .8)' // ] 'hsla(123, 45%, 67%, .8) cats and dogs'.match(hslaRegex()); // = ['hsla(123, 45%, 67%, .8)'] ``` ## License MIT ## 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. Create new Pull Request Crafted with <3 by John Otander ([@4lpine](https://twitter.com/4lpine)). *** > This package was initially generated with [yeoman](http://yeoman.io) and the [p generator](https://github.com/johnotander/generator-p.git). # posthtml-parser [![npm version](https://badge.fury.io/js/posthtml-parser.svg)](http://badge.fury.io/js/posthtml-parser) [![Build Status](https://travis-ci.org/posthtml/posthtml-parser.svg?branch=master)](https://travis-ci.org/posthtml/posthtml-parser?branch=master) [![Coverage Status](https://coveralls.io/repos/posthtml/posthtml-parser/badge.svg?branch=master)](https://coveralls.io/r/posthtml/posthtml-parser?branch=master) Parse HTML/XML to [PostHTML AST](https://github.com/posthtml/posthtml-parser#posthtml-ast-format). More about [PostHTML](https://github.com/posthtml/posthtml#readme) ## Install [NPM](http://npmjs.com) install ``` $ npm install posthtml-parser ``` ## Usage #### Input HTML ```html <a class="animals" href="#"> <span class="animals__cat" style="background: url(cat.png)">Cat</span> </a> ``` ```js const parser = require('posthtml-parser') const fs = require('fs') const html = fs.readFileSync('path/to/input.html').toString() console.log(parser(html)) // Logs a PostHTML AST ``` #### input HTML ```html <a class="animals" href="#"> <span class="animals__cat" style="background: url(cat.png)">Cat</span> </a> ``` #### Result PostHTMLTree ```js [{ tag: 'a', attrs: { class: 'animals', href: '#' }, content: [ '\n ', { tag: 'span', attrs: { class: 'animals__cat', style: 'background: url(cat.png)' }, content: ['Cat'] }, '\n' ] }] ``` ## PostHTML AST Format Any parser being used with PostHTML should return a standard PostHTML [Abstract Syntax Tree](https://www.wikiwand.com/en/Abstract_syntax_tree) (AST). Fortunately, this is a very easy format to produce and understand. The AST is an array that can contain strings and objects. Any strings represent plain text content to be written to the output. Any objects represent HTML tags. Tag objects generally look something like this: ```js { tag: 'div', attrs: { class: 'foo' }, content: ['hello world!'] } ``` Tag objects can contain three keys. The `tag` key takes the name of the tag as the value. This can include custom tags. The optional `attrs` key takes an object with key/value pairs representing the attributes of the html tag. A boolean attribute has an empty string as its value. Finally, the optional `content` key takes an array as its value, which is a PostHTML AST. In this manner, the AST is a tree that should be walked recursively. ## Options ### `directives` Type: `Array` Default: `[{name: '!doctype', start: '<', end: '>'}]` Description: *Adds processing of custom directives. Note: The property ```name``` in custom directives can be ```String``` or ```RegExp``` type* ### `xmlMode` Type: `Boolean` Default: `false` Description: *Indicates whether special tags (`<script>` and `<style>`) should get special treatment and if "empty" tags (eg. `<br>`) can have children. If false, the content of special tags will be text only. For feeds and other XML content (documents that don't consist of HTML), set this to true.* ### `decodeEntities` Type: `Boolean` Default: `false` Description: *If set to true, entities within the document will be decoded.* ### `lowerCaseTags` Type: `Boolean` Default: `false` Description: *If set to true, all tags will be lowercased. If `xmlMode` is disabled.* ### `lowerCaseAttributeNames` Type: `Boolean` Default: `false` Description: *If set to true, all attribute names will be lowercased. This has noticeable impact on speed.* ### `recognizeCDATA` Type: `Boolean` Default: `false` Description: *If set to true, CDATA sections will be recognized as text even if the `xmlMode` option is not enabled. NOTE: If `xmlMode` is set to `true` then CDATA sections will always be recognized as text.* ### `recognizeSelfClosing` Type: `Boolean` Default: `false` Description: *If set to true, self-closing tags will trigger the `onclosetag` event even if `xmlMode` is not set to `true`. NOTE: If `xmlMode` is set to `true` then self-closing tags will always be recognized.* ## License [MIT](LICENSE) 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. DeAsync.js ======= [![NPM version](http://img.shields.io/npm/v/deasync.svg)](https://www.npmjs.org/package/deasync) DeAsync turns async function into sync, implemented with a blocking mechanism by calling Node.js event loop at JavaScript layer. The core of deasync is writen in C++. ## Motivation Suppose you maintain a library that exposes a function <code>getData</code>. Your users call it to get actual data: <code>var myData = getData();</code> Under the hood data is saved in a file so you implemented <code>getData</code> using Node.js built-in <code>fs.readFileSync</code>. It's obvious both <code>getData</code> and <code>fs.readFileSync</code> are sync functions. One day you were told to switch the underlying data source to a repo such as MongoDB which can only be accessed asynchronously. You were also told to avoid pissing off your users, <code>getData</code> API cannot be changed to return merely a promise or demand a callback parameter. How do you meet both requirements? You may tempted to use [node-fibers](https://github.com/laverdet/node-fibers) or a module derived from it, but node fibers can only wrap async function call into a sync function inside a fiber. In the case above you cannot assume all callers are inside fibers. On the other hand, if you start a fiber in `getData` then `getData` itself will still return immediately without waiting for the async call result. For similar reason ES6 generators introduced in Node v0.11 won't work either. What really needed is a way to block subsequent JavaScript from running without blocking entire thread by yielding to allow other events in the event loop to be handled. Ideally the blockage is removed as soon as the result of async function is available. A less ideal but often acceptable alternative is a `sleep` function which you can use to implement the blockage like ```while(!done) sleep(100);```. It is less ideal because sleep duration has to be guessed. It is important the `sleep` function not only shouldn't block entire thread, but also shouldn't incur busy wait that pegs the CPU to 100%. </small> DeAsync supports both alternatives. ## Usages * Generic wrapper of async function with conventional API signature `function(p1,...pn,function cb(error,result){})`. Returns `result` and throws `error` as exception if not null: ```javascript var deasync = require('deasync'); var cp = require('child_process'); var exec = deasync(cp.exec); // output result of ls -la try{ console.log(exec('ls -la')); } catch(err){ console.log(err); } // done is printed last, as supposed, with cp.exec wrapped in deasync; first without. console.log('done'); ``` * For async function with unconventional API, for instance `function asyncFunction(p1,function cb(res){})`, use `loopWhile(predicateFunc)` where `predicateFunc` is a function that returns boolean loop condition ```javascript var done = false; var data; asyncFunction(p1,function cb(res){ data = res; done = true; }); require('deasync').loopWhile(function(){return !done;}); // data is now populated ``` * Sleep (a wrapper of setTimeout) ```javascript function SyncFunction(){ var ret; setTimeout(function(){ ret = "hello"; },3000); while(ret === undefined) { require('deasync').sleep(100); } // returns hello with sleep; undefined without return ret; } ``` ## Installation Except on a few [ platforms + Node version combinations](https://github.com/abbr/deasync-bin) where binary distribution is included, DeAsync uses node-gyp to compile C++ source code so you may need the compilers listed in [node-gyp](https://github.com/TooTallNate/node-gyp). You may also need to [update npm's bundled node-gyp](https://github.com/TooTallNate/node-gyp/wiki/Updating-npm's-bundled-node-gyp). To install, run ```npm install deasync``` ## Recommendation Unlike other (a)sync js packages that mostly have only syntactic impact, DeAsync also changes code execution sequence. As such, it is intended to solve niche cases like the above one. If all you are facing is syntatic problem such as callback hell, using a less drastic package implemented in pure js is recommended. ## Support Pull requests and issue reporting are welcome. For issues to be considered by maintainer 1. they must be reproducible 2. there must be evidence the issue is related to DeAsync To that end, the issue should contain platform information, error message relevant to DeAsync, and preferably code snippet. If code snippet is supplied, it must be self-contained, i.e. independent from your runtime environment or other modules not explictly specified via `require` in the code snippet. ## License The MIT License (MIT) Copyright (c) 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. # html-escaper [![Build Status](https://travis-ci.org/WebReflection/html-escaper.svg?branch=master)](https://travis-ci.org/WebReflection/html-escaper) [![Coverage Status](https://coveralls.io/repos/github/WebReflection/html-escaper/badge.svg?branch=master)](https://coveralls.io/github/WebReflection/html-escaper?branch=master) A simple module to escape/unescape common problematic entities. ### How This package is available in npm so `npm install html-escaper` is all you need to do, using eventually the global flag too. Once the module is present ```js var html = require('html-escaper'); // two basic methods html.escape('string'); html.unescape('escaped string'); ``` ### Why there is basically one rule only: do not **ever** replace one char after another if you are transforming a string into another. ```js // WARNING: THIS IS WRONG // if you are that kind of dev that does this function escape(s) { return s.replace(/&/g, "&amp;") .replace(/</g, "&lt;") .replace(/>/g, "&gt;") .replace(/'/g, "&#39;") .replace(/"/g, "&quot;"); } // you might be the same dev that does this too function unescape(s) { return s.replace(/&amp;/g, "&") .replace(/&lt;/g, "<") .replace(/&gt;/g, ">") .replace(/&#39;/g, "'") .replace(/&quot;/g, '"'); } // guess what we have here ? unescape('&amp;lt;'); // now guess this XSS too ... unescape('&amp;lt;script&amp;gt;alert("yo")&amp;lt;/script&amp;gt;'); ``` The last example will produce `<script>alert("yo")</script>` instead of the expected `&lt;script&gt;alert("yo")&lt;/script&gt;`. Nothing like this could possibly happen if we grab all chars at once and either ways. It's just a fortunate case that after swapping `&` with `&amp;` no other replace will be affected, but it's not portable and universally a bad practice. Grab all chars at once, no excuses! **more details** As somebody might think it's an `unescape` issue only, it's not. Being an anti-pattern with side effects works both ways. As example, changing the order of the replacement in escaping would produce the unexpected: ```js function escape(s) { return s.replace(/</g, "&lt;") .replace(/>/g, "&gt;") .replace(/'/g, "&#39;") .replace(/"/g, "&quot;") .replace(/&/g, "&amp;"); } escape('<'); // &amp;lt; instead of &lt; ``` If we do not want to code with the fear that the order wasn't perfect or that our order in either escaping or unescaping is different from the order another method or function used, if we understand the issue and we agree it's potentially a disaster prone approach, if we add the fact in this case creating 4 RegExp objects each time and invoking 4 times `.replace` trough the `String.prototype` is also potentially slower than creating one function only holding one object, or holding the function too, we should agree there is not absolutely any valid reason to keep proposing a char-by-char implementation. We have proofs this approach can fail already so ... why should we risk? Just avoid and grab all chars at once or simply use this tiny utility. ### Backtick Internt explorer < 9 has [some backtick issue](https://html5sec.org/#102) For compatibility sake with common server-side HTML entities encoders and decoders, and in order to have the most reliable I/O, this little utility will NOT fix this IE < 9 problem. It is also important to note that if we create valid HTML and we set attributes at runtime through this utility, backticks in strings cannot possibly affect attribute behaviors. ```js var img = new Image(); img.src = html.escape( 'x` `<script>alert(1)</script>"` `' ); // it won't cause problems even in IE < 9 ``` **However**, if you use `innerHTML` and you target IE < 9 then [this **might** be a problem](https://github.com/nette/nette/issues/1496). Accordingly, if you need more chars and/or backticks to be escaped and unescaped, feel free to use alternatives like [lodash](https://github.com/lodash/lodash) or [he](https://www.npmjs.com/package/he) Here a bit more of [my POV](https://github.com/WebReflection/html-escaper/commit/52d554fc6e8583b6ffdd357967cf71962fc07cf6#commitcomment-10625122) and why I haven't implemented same thing alternatives did. Good news: those are alternatives ;-) # 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. #boolbase This very simple module provides two basic functions, one that always returns true (`trueFunc`) and one that always returns false (`falseFunc`). ###WTF? By having only a single instance of these functions around, it's possible to do some nice optimizations. Eg. [`CSSselect`](https://github.com/fb55/CSSselect) uses these functions to determine whether a selector won't match any elements. If that's the case, the DOM doesn't even have to be touched. ###And why is this a separate module? I'm trying to modularize `CSSselect` and most modules depend on these functions. IMHO, having a separate module is the easiest solution to this problem. 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) # acorn-globals Detect global variables in JavaScript using acorn [Get supported acorn-globals with the Tidelift Subscription](https://tidelift.com/subscription/pkg/npm-acorn_globals?utm_source=npm-acorn-globals&utm_medium=referral&utm_campaign=readme) [![Build Status](https://img.shields.io/travis/ForbesLindesay/acorn-globals/master.svg)](https://travis-ci.org/ForbesLindesay/acorn-globals) [![Dependency Status](https://img.shields.io/david/ForbesLindesay/acorn-globals.svg)](https://david-dm.org/ForbesLindesay/acorn-globals) [![NPM version](https://img.shields.io/npm/v/acorn-globals.svg)](https://www.npmjs.org/package/acorn-globals) ## Installation npm install acorn-globals ## Usage detect.js ```js var fs = require('fs'); var detect = require('acorn-globals'); var src = fs.readFileSync(__dirname + '/input.js', 'utf8'); var scope = detect(src); console.dir(scope); ``` input.js ```js var x = 5; var y = 3, z = 2; w.foo(); w = 2; RAWR=444; RAWR.foo(); BLARG=3; foo(function () { var BAR = 3; process.nextTick(function (ZZZZZZZZZZZZ) { console.log('beep boop'); var xyz = 4; x += 10; x.zzzzzz; ZZZ=6; }); function doom () { } ZZZ.foo(); }); console.log(xyz); ``` output: ``` $ node example/detect.js [ { name: 'BLARG', nodes: [ [Object] ] }, { name: 'RAWR', nodes: [ [Object], [Object] ] }, { name: 'ZZZ', nodes: [ [Object], [Object] ] }, { name: 'console', nodes: [ [Object], [Object] ] }, { name: 'foo', nodes: [ [Object] ] }, { name: 'process', nodes: [ [Object] ] }, { name: 'w', nodes: [ [Object], [Object] ] }, { name: 'xyz', nodes: [ [Object] ] } ] ``` ## 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 # 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._ [![CircleCI](https://circleci.com/gh/amasad/sane.svg?style=svg)](https://circleci.com/gh/amasad/sane) sane ---- I've been driven to insanity by node filesystem watcher wrappers. Sane aims to be fast, small, and reliable file system watcher. It does that by: * By default stays away from fs polling because it's very slow and cpu intensive * Uses `fs.watch` by default and sensibly works around the various issues * Maintains a consistent API across different platforms * Where `fs.watch` is not reliable you have the choice of using the following alternatives: * [the facebook watchman library](https://facebook.github.io/watchman/) * [the watchexec library](https://github.com/watchexec/watchexec) * polling ## Install ``` $ npm install sane ``` ## How to choose a mode Don't worry too much about choosing the correct mode upfront because sane maintains the same API across all modes and will be easy to switch. * If you're only supporting Linux and OS X, `watchman` would be the most reliable mode * If you're using node > v0.10.0 use the default mode * If you're running OS X and you're watching a lot of directories and you're running into https://github.com/joyent/node/issues/5463, use `watchman` * If you're in an environment where native file system events aren't available (like Vagrant), you should use polling * Otherwise, the default mode should work well for you ## API ### sane(dir, options) Watches a directory and all its descendant directories for changes, deletions, and additions on files and directories. ```js var watcher = sane('path/to/dir', {glob: ['**/*.js', '**/*.css']}); watcher.on('ready', function () { console.log('ready') }); watcher.on('change', function (filepath, root, stat) { console.log('file changed', filepath); }); watcher.on('add', function (filepath, root, stat) { console.log('file added', filepath); }); watcher.on('delete', function (filepath, root) { console.log('file deleted', filepath); }); // close watcher.close(); ``` options: * `glob`: a single string glob pattern or an array of them. * `poll`: puts the watcher in polling mode. Under the hood that means `fs.watchFile`. * `watchman`: makes the watcher use [watchman](https://facebook.github.io/watchman/). * `watchmanPath`: sets a custom path for `watchman` binary. * `watchexec`: makes the watcher use [watchexec](https://github.com/watchexec/watchexec). * `dot`: enables watching files/directories that start with a dot. * `ignored`: a glob, regex, function, or array of any combination. For the glob pattern documentation, see [micromatch](https://github.com/micromatch/micromatch). If you choose to use `watchman` you'll have to [install watchman yourself](https://facebook.github.io/watchman/docs/install.html)). If you choose to use `watchexec` you'll have to [install watchexec yourself](https://github.com/watchexec/watchexec)). For the ignored options, see [anymatch](https://github.com/es128/anymatch). ### sane.NodeWatcher(dir, options) The default watcher class. Uses `fs.watch` under the hood, and takes the same options as `sane(dir, options)`. ### sane.WatchmanWatcher(dir, options) The watchman watcher class. Takes the same options as `sane(dir, options)`. ### sane.Watchexec(dir, options) The watchexec watcher class. Takes the same options as `sane(dir, options)`. ### sane.PollWatcher(dir, options) The polling watcher class. Takes the same options as `sane(dir, options)` with the addition of: * interval: indicates how often the files should be polled. (passed to fs.watchFile) ### sane.{Node|Watchman|Watchexec|Poll}Watcher#close Stops watching. ### sane.{Node|Watchman|Watchexec|Poll}Watcher events Emits the following events: All events are passed the file/dir path relative to the root directory * `ready` when the program is ready to detect events in the directory * `change` when a file changes * `add` when a file or directory has been added * `delete` when a file or directory has been deleted ## CLI This module includes a simple command line interface, which you can install with `npm install sane -g`. ``` Usage: sane <command> [...directory] [--glob=<filePattern>] [--poll] [--watchman] [--watchman-path=<watchmanBinaryPath>] [--dot] [--wait=<seconds>] OPTIONS: --glob=<filePattern> A single string glob pattern or an array of them. --ignored=<filePattern> A glob, regex, function, or array of any combination. --poll, -p Use polling mode. --watchman, -w Use watchman (if available). --watchman-path=<watchmanBinaryPath> Sets a custom path for watchman binary (if using this mode). --dot, -d Enables watching files/directories that start with a dot. --wait=<seconds> Duration, in seconds, that watching will be disabled after running <command>. Setting this option will throttle calls to <command> for the specified duration. --quiet, -q Disables sane's console output --changes-only, -o Runs <command> only when a change occur. Skips running <command> at startup ``` It will watch the given `directory` and run the given <command> every time a file changes. ### CLI example usage - `sane 'echo "A command ran"'` - `sane 'echo "A command ran"' --glob='**/*.css'` - `sane 'echo "A command ran"' site/assets/css --glob='**/*.css'` - `sane 'echo "A command ran"' --glob='**/*.css' --ignored='**/ignore.css'` - `sane 'echo "A command ran"' --wait=3` - `sane 'echo "A command ran"' -p` ## License MIT ## Credits The CLI was originally based on the [watch CLI](https://github.com/mikeal/watch). Watch is licensed under the Apache License Version 2.0. # <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 # 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) # core-js [![Sponsors on Open Collective](https://opencollective.com/core-js/sponsors/badge.svg)](#raising-funds) [![Backers on Open Collective](https://opencollective.com/core-js/backers/badge.svg)](#raising-funds) [![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) ## Raising funds `core-js` isn't backed by a company, so the future of this project depends on you. Become a sponsor or a backer [**on Open Collective**](https://opencollective.com/core-js) or [**on Patreon**](https://www.patreon.com/zloirock) if you are interested in `core-js`. --- <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> --- <a href="https://opencollective.com/core-js#backers" target="_blank"><img src="https://opencollective.com/core-js/backers.svg?width=890"></a> --- **It's documentation for obsolete `core-js@2`. If you looking documentation for actual `core-js` version, please, check [this branch](https://github.com/zloirock/core-js/tree/master).** Modular standard library for JavaScript. Includes polyfills for [ECMAScript 5](#ecmascript-5), [ECMAScript 6](#ecmascript-6): [promises](#ecmascript-6-promise), [symbols](#ecmascript-6-symbol), [collections](#ecmascript-6-collections), iterators, [typed arrays](#ecmascript-6-typed-arrays), [ECMAScript 7+ proposals](#ecmascript-7-proposals), [setImmediate](#setimmediate), etc. Some additional features such as [dictionaries](#dict) or [extended partial application](#partial-application). You can require only needed features or use it without global namespace pollution. [*Example*](http://goo.gl/a2xexl): ```js Array.from(new Set([1, 2, 3, 2, 1])); // => [1, 2, 3] '*'.repeat(10); // => '**********' Promise.resolve(32).then(x => console.log(x)); // => 32 setImmediate(x => console.log(x), 42); // => 42 ``` [*Without global namespace pollution*](http://goo.gl/paOHb0): ```js var core = require('core-js/library'); // With a modular system, otherwise use global `core` core.Array.from(new core.Set([1, 2, 3, 2, 1])); // => [1, 2, 3] core.String.repeat('*', 10); // => '**********' core.Promise.resolve(32).then(x => console.log(x)); // => 32 core.setImmediate(x => console.log(x), 42); // => 42 ``` ### Index - [Usage](#usage) - [Basic](#basic) - [CommonJS](#commonjs) - [Custom build](#custom-build-from-the-command-line) - [Supported engines](#supported-engines) - [Features](#features) - [ECMAScript 5](#ecmascript-5) - [ECMAScript 6](#ecmascript-6) - [ECMAScript 6: Object](#ecmascript-6-object) - [ECMAScript 6: Function](#ecmascript-6-function) - [ECMAScript 6: Array](#ecmascript-6-array) - [ECMAScript 6: String](#ecmascript-6-string) - [ECMAScript 6: RegExp](#ecmascript-6-regexp) - [ECMAScript 6: Number](#ecmascript-6-number) - [ECMAScript 6: Math](#ecmascript-6-math) - [ECMAScript 6: Date](#ecmascript-6-date) - [ECMAScript 6: Promise](#ecmascript-6-promise) - [ECMAScript 6: Symbol](#ecmascript-6-symbol) - [ECMAScript 6: Collections](#ecmascript-6-collections) - [ECMAScript 6: Typed Arrays](#ecmascript-6-typed-arrays) - [ECMAScript 6: Reflect](#ecmascript-6-reflect) - [ECMAScript 7+ proposals](#ecmascript-7-proposals) - [stage 4 proposals](#stage-4-proposals) - [stage 3 proposals](#stage-3-proposals) - [stage 2 proposals](#stage-2-proposals) - [stage 1 proposals](#stage-1-proposals) - [stage 0 proposals](#stage-0-proposals) - [pre-stage 0 proposals](#pre-stage-0-proposals) - [Web standards](#web-standards) - [setTimeout / setInterval](#settimeout--setinterval) - [setImmediate](#setimmediate) - [iterable DOM collections](#iterable-dom-collections) - [Non-standard](#non-standard) - [Object](#object) - [Dict](#dict) - [partial application](#partial-application) - [Number Iterator](#number-iterator) - [escaping strings](#escaping-strings) - [delay](#delay) - [helpers for iterators](#helpers-for-iterators) - [Missing polyfills](#missing-polyfills) - [Changelog](./CHANGELOG.md) ## Usage ### Basic ``` npm i core-js bower install core.js ``` ```js // Default require('core-js'); // Without global namespace pollution var core = require('core-js/library'); // Shim only require('core-js/shim'); ``` If you need complete build for browser, use builds from `core-js/client` path: * [default](https://raw.githack.com/zloirock/core-js/v2.6.11/client/core.min.js): Includes all features, standard and non-standard. * [as a library](https://raw.githack.com/zloirock/core-js/v2.6.11/client/library.min.js): Like "default", but does not pollute the global namespace (see [2nd example at the top](#core-js)). * [shim only](https://raw.githack.com/zloirock/core-js/v2.6.11/client/shim.min.js): Only includes the standard methods. Warning: if you use `core-js` with the extension of native objects, require all needed `core-js` modules at the beginning of entry point of your application, otherwise, conflicts may occur. ### CommonJS You can require only needed modules. ```js require('core-js/fn/set'); require('core-js/fn/array/from'); require('core-js/fn/array/find-index'); Array.from(new Set([1, 2, 3, 2, 1])); // => [1, 2, 3] [1, 2, NaN, 3, 4].findIndex(isNaN); // => 2 // or, w/o global namespace pollution: var Set = require('core-js/library/fn/set'); var from = require('core-js/library/fn/array/from'); var findIndex = require('core-js/library/fn/array/find-index'); from(new Set([1, 2, 3, 2, 1])); // => [1, 2, 3] findIndex([1, 2, NaN, 3, 4], isNaN); // => 2 ``` Available entry points for methods / constructors, as above examples, and namespaces: for example, `core-js/es6/array` (`core-js/library/es6/array`) contains all [ES6 `Array` features](#ecmascript-6-array), `core-js/es6` (`core-js/library/es6`) contains all ES6 features. ##### Caveats when using CommonJS API: * `modules` path is internal API, does not inject all required dependencies and can be changed in minor or patch releases. Use it only for a custom build and / or if you know what are you doing. * `core-js` is extremely modular and uses a lot of very tiny modules, because of that for usage in browsers bundle up `core-js` instead of usage loader for each file, otherwise, you will have hundreds of requests. #### CommonJS and prototype methods without global namespace pollution In the `library` version, we can't pollute prototypes of native constructors. Because of that, prototype methods transformed to static methods like in examples above. `babel` `runtime` transformer also can't transform them. But with transpilers we can use one more trick - [bind operator and virtual methods](https://github.com/zenparsing/es-function-bind). Special for that, available `/virtual/` entry points. Example: ```js import fill from 'core-js/library/fn/array/virtual/fill'; import findIndex from 'core-js/library/fn/array/virtual/find-index'; Array(10)::fill(0).map((a, b) => b * b)::findIndex(it => it && !(it % 8)); // => 4 // or import {fill, findIndex} from 'core-js/library/fn/array/virtual'; Array(10)::fill(0).map((a, b) => b * b)::findIndex(it => it && !(it % 8)); // => 4 ``` ### Custom build (from the command-line) ``` npm i core-js && cd node_modules/core-js && npm i npm run grunt build:core.dict,es6 -- --blacklist=es6.promise,es6.math --library=on --path=custom uglify ``` Where `core.dict` and `es6` are modules (namespaces) names, which will be added to the build, `es6.promise` and `es6.math` are modules (namespaces) names, which will be excluded from the build, `--library=on` is flag for build without global namespace pollution and `custom` is target file name. Available namespaces: for example, `es6.array` contains [ES6 `Array` features](#ecmascript-6-array), `es6` contains all modules whose names start with `es6`. ### Custom build (from external scripts) [`core-js-builder`](https://www.npmjs.com/package/core-js-builder) package exports a function that takes the same parameters as the `build` target from the previous section. This will conditionally include or exclude certain parts of `core-js`: ```js require('core-js-builder')({ modules: ['es6', 'core.dict'], // modules / namespaces blacklist: ['es6.reflect'], // blacklist of modules / namespaces, by default - empty list library: false, // flag for build without global namespace pollution, by default - false umd: true // use UMD wrapper for export `core` object, by default - true }).then(code => { // ... }).catch(error => { // ... }); ``` ## Supported engines **Tested in:** - Chrome 26+ - Firefox 4+ - Safari 5+ - Opera 12+ - Internet Explorer 6+ (sure, IE8- with ES3 limitations) - Edge - Android Browser 2.3+ - iOS Safari 5.1+ - PhantomJS 1.9 / 2.1 - NodeJS 0.8+ ...and it doesn't mean `core-js` will not work in other engines, they just have not been tested. ## Features: [*CommonJS entry points:*](#commonjs) ``` core-js(/library) <- all features core-js(/library)/shim <- only polyfills ``` ### ECMAScript 5 All features moved to the [`es6` namespace](#ecmascript-6), here just a list of features: ```js Object .create(proto | null, descriptors?) -> object .getPrototypeOf(object) -> proto | null .defineProperty(target, key, desc) -> target, cap for ie8- .defineProperties(target, descriptors) -> target, cap for ie8- .getOwnPropertyDescriptor(object, key) -> desc .getOwnPropertyNames(object) -> array .keys(object) -> array .seal(object) -> object, cap for ie8- .freeze(object) -> object, cap for ie8- .preventExtensions(object) -> object, cap for ie8- .isSealed(object) -> bool, cap for ie8- .isFrozen(object) -> bool, cap for ie8- .isExtensible(object) -> bool, cap for ie8- Array .isArray(var) -> bool #slice(start?, end?) -> array, fix for ie7- #join(string = ',') -> string, fix for ie7- #indexOf(var, from?) -> int #lastIndexOf(var, from?) -> int #every(fn(val, index, @), that) -> bool #some(fn(val, index, @), that) -> bool #forEach(fn(val, index, @), that) -> void #map(fn(val, index, @), that) -> array #filter(fn(val, index, @), that) -> array #reduce(fn(memo, val, index, @), memo?) -> var #reduceRight(fn(memo, val, index, @), memo?) -> var #sort(fn?) -> @, fixes for some engines Function #bind(object, ...args) -> boundFn(...args) String #split(separator, limit) -> array #trim() -> str RegExp #toString() -> str Number #toFixed(digits) -> string #toPrecision(precision) -> string parseInt(str, radix) -> int parseFloat(str) -> num Date .now() -> int #toISOString() -> string #toJSON() -> string ``` [*CommonJS entry points:*](#commonjs) ``` core-js(/library)/es5 ``` ### ECMAScript 6 [*CommonJS entry points:*](#commonjs) ``` core-js(/library)/es6 ``` #### ECMAScript 6: Object Modules [`es6.object.assign`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.object.assign.js), [`es6.object.is`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.object.is.js), [`es6.object.set-prototype-of`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.object.set-prototype-of.js) and [`es6.object.to-string`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.object.to-string.js). In ES6 most `Object` static methods should work with primitives. Modules [`es6.object.freeze`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.object.freeze.js), [`es6.object.seal`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.object.seal.js), [`es6.object.prevent-extensions`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.object.prevent-extensions.js), [`es6.object.is-frozen`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.object.is-frozen.js), [`es6.object.is-sealed`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.object.is-sealed.js), [`es6.object.is-extensible`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.object.is-extensible.js), [`es6.object.get-own-property-descriptor`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.object.get-own-property-descriptor.js), [`es6.object.get-prototype-of`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.object.get-prototype-of.js), [`es6.object.keys`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.object.keys.js) and [`es6.object.get-own-property-names`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.object.get-own-property-names.js). Just ES5 features: [`es6.object.create`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.object.create.js), [`es6.object.define-property`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.object.define-property.js) and [`es6.object.define-properties`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.object.es6.object.define-properties.js). ```js Object .assign(target, ...src) -> target .is(a, b) -> bool .setPrototypeOf(target, proto | null) -> target (required __proto__ - IE11+) .create(object | null, descriptors?) -> object .getPrototypeOf(var) -> object | null .defineProperty(object, key, desc) -> target .defineProperties(object, descriptors) -> target .getOwnPropertyDescriptor(var, key) -> desc | undefined .keys(var) -> array .getOwnPropertyNames(var) -> array .freeze(var) -> var .seal(var) -> var .preventExtensions(var) -> var .isFrozen(var) -> bool .isSealed(var) -> bool .isExtensible(var) -> bool #toString() -> string, ES6 fix: @@toStringTag support ``` [*CommonJS entry points:*](#commonjs) ``` core-js(/library)/es6/object core-js(/library)/fn/object/assign core-js(/library)/fn/object/is core-js(/library)/fn/object/set-prototype-of core-js(/library)/fn/object/get-prototype-of core-js(/library)/fn/object/create core-js(/library)/fn/object/define-property core-js(/library)/fn/object/define-properties core-js(/library)/fn/object/get-own-property-descriptor core-js(/library)/fn/object/keys core-js(/library)/fn/object/get-own-property-names core-js(/library)/fn/object/freeze core-js(/library)/fn/object/seal core-js(/library)/fn/object/prevent-extensions core-js(/library)/fn/object/is-frozen core-js(/library)/fn/object/is-sealed core-js(/library)/fn/object/is-extensible core-js/fn/object/to-string ``` [*Examples*](http://goo.gl/ywdwPz): ```js var foo = {q: 1, w: 2} , bar = {e: 3, r: 4} , baz = {t: 5, y: 6}; Object.assign(foo, bar, baz); // => foo = {q: 1, w: 2, e: 3, r: 4, t: 5, y: 6} Object.is(NaN, NaN); // => true Object.is(0, -0); // => false Object.is(42, 42); // => true Object.is(42, '42'); // => false function Parent(){} function Child(){} Object.setPrototypeOf(Child.prototype, Parent.prototype); new Child instanceof Child; // => true new Child instanceof Parent; // => true var O = {}; O[Symbol.toStringTag] = 'Foo'; '' + O; // => '[object Foo]' Object.keys('qwe'); // => ['0', '1', '2'] Object.getPrototypeOf('qwe') === String.prototype; // => true ``` #### ECMAScript 6: Function Modules [`es6.function.name`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.function.name.js), [`es6.function.has-instance`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.function.has-instance.js). Just ES5: [`es6.function.bind`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.function.bind.js). ```js Function #bind(object, ...args) -> boundFn(...args) #name -> string (IE9+) #@@hasInstance(var) -> bool ``` [*CommonJS entry points:*](#commonjs) ``` core-js/es6/function core-js/fn/function/name core-js/fn/function/has-instance core-js/fn/function/bind core-js/fn/function/virtual/bind ``` [*Example*](http://goo.gl/zqu3Wp): ```js (function foo(){}).name // => 'foo' console.log.bind(console, 42)(43); // => 42 43 ``` #### ECMAScript 6: Array Modules [`es6.array.from`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.array.from.js), [`es6.array.of`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.array.of.js), [`es6.array.copy-within`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.array.copy-within.js), [`es6.array.fill`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.array.fill.js), [`es6.array.find`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.array.find.js), [`es6.array.find-index`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.array.find-index.js), [`es6.array.iterator`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.array.iterator.js). ES5 features with fixes: [`es6.array.is-array`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.array.is-array.js), [`es6.array.slice`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.array.slice.js), [`es6.array.join`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.array.join.js), [`es6.array.index-of`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.array.index-of.js), [`es6.array.last-index-of`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.array.last-index-of.js), [`es6.array.every`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.array.every.js), [`es6.array.some`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.array.some.js), [`es6.array.for-each`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.array.for-each.js), [`es6.array.map`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.array.map.js), [`es6.array.filter`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.array.filter.js), [`es6.array.reduce`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.array.reduce.js), [`es6.array.reduce-right`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.array.reduce-right.js), [`es6.array.sort`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.array.sort.js). ```js Array .from(iterable | array-like, mapFn(val, index)?, that) -> array .of(...args) -> array .isArray(var) -> bool #copyWithin(target = 0, start = 0, end = @length) -> @ #fill(val, start = 0, end = @length) -> @ #find(fn(val, index, @), that) -> val #findIndex(fn(val, index, @), that) -> index | -1 #values() -> iterator #keys() -> iterator #entries() -> iterator #join(string = ',') -> string, fix for ie7- #slice(start?, end?) -> array, fix for ie7- #indexOf(var, from?) -> index | -1 #lastIndexOf(var, from?) -> index | -1 #every(fn(val, index, @), that) -> bool #some(fn(val, index, @), that) -> bool #forEach(fn(val, index, @), that) -> void #map(fn(val, index, @), that) -> array #filter(fn(val, index, @), that) -> array #reduce(fn(memo, val, index, @), memo?) -> var #reduceRight(fn(memo, val, index, @), memo?) -> var #sort(fn?) -> @, invalid arguments fix #@@iterator() -> iterator (values) #@@unscopables -> object (cap) Arguments #@@iterator() -> iterator (values, available only in core-js methods) ``` [*CommonJS entry points:*](#commonjs) ``` core-js(/library)/es6/array core-js(/library)/fn/array/from core-js(/library)/fn/array/of core-js(/library)/fn/array/is-array core-js(/library)/fn/array/iterator core-js(/library)/fn/array/copy-within core-js(/library)/fn/array/fill core-js(/library)/fn/array/find core-js(/library)/fn/array/find-index core-js(/library)/fn/array/values core-js(/library)/fn/array/keys core-js(/library)/fn/array/entries core-js(/library)/fn/array/slice core-js(/library)/fn/array/join core-js(/library)/fn/array/index-of core-js(/library)/fn/array/last-index-of core-js(/library)/fn/array/every core-js(/library)/fn/array/some core-js(/library)/fn/array/for-each core-js(/library)/fn/array/map core-js(/library)/fn/array/filter core-js(/library)/fn/array/reduce core-js(/library)/fn/array/reduce-right core-js(/library)/fn/array/sort core-js(/library)/fn/array/virtual/iterator core-js(/library)/fn/array/virtual/copy-within core-js(/library)/fn/array/virtual/fill core-js(/library)/fn/array/virtual/find core-js(/library)/fn/array/virtual/find-index core-js(/library)/fn/array/virtual/values core-js(/library)/fn/array/virtual/keys core-js(/library)/fn/array/virtual/entries core-js(/library)/fn/array/virtual/slice core-js(/library)/fn/array/virtual/join core-js(/library)/fn/array/virtual/index-of core-js(/library)/fn/array/virtual/last-index-of core-js(/library)/fn/array/virtual/every core-js(/library)/fn/array/virtual/some core-js(/library)/fn/array/virtual/for-each core-js(/library)/fn/array/virtual/map core-js(/library)/fn/array/virtual/filter core-js(/library)/fn/array/virtual/reduce core-js(/library)/fn/array/virtual/reduce-right core-js(/library)/fn/array/virtual/sort ``` [*Examples*](http://goo.gl/oaUFUf): ```js Array.from(new Set([1, 2, 3, 2, 1])); // => [1, 2, 3] Array.from({0: 1, 1: 2, 2: 3, length: 3}); // => [1, 2, 3] Array.from('123', Number); // => [1, 2, 3] Array.from('123', function(it){ return it * it; }); // => [1, 4, 9] Array.of(1); // => [1] Array.of(1, 2, 3); // => [1, 2, 3] var array = ['a', 'b', 'c']; for(var val of array)console.log(val); // => 'a', 'b', 'c' for(var val of array.values())console.log(val); // => 'a', 'b', 'c' for(var key of array.keys())console.log(key); // => 0, 1, 2 for(var [key, val] of array.entries()){ console.log(key); // => 0, 1, 2 console.log(val); // => 'a', 'b', 'c' } function isOdd(val){ return val % 2; } [4, 8, 15, 16, 23, 42].find(isOdd); // => 15 [4, 8, 15, 16, 23, 42].findIndex(isOdd); // => 2 [4, 8, 15, 16, 23, 42].find(isNaN); // => undefined [4, 8, 15, 16, 23, 42].findIndex(isNaN); // => -1 Array(5).fill(42); // => [42, 42, 42, 42, 42] [1, 2, 3, 4, 5].copyWithin(0, 3); // => [4, 5, 3, 4, 5] ``` #### ECMAScript 6: String Modules [`es6.string.from-code-point`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.string.from-code-point.js), [`es6.string.raw`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.string.raw.js), [`es6.string.iterator`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.string.iterator.js), [`es6.string.code-point-at`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.string.code-point-at.js), [`es6.string.ends-with`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.string.ends-with.js), [`es6.string.includes`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.string.includes.js), [`es6.string.repeat`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.string.repeat.js), [`es6.string.starts-with`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.string.starts-with.js) and [`es6.string.trim`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.string.trim.js). Annex B HTML methods. Ugly, but it's also the part of the spec. Modules [`es6.string.anchor`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.string.anchor.js), [`es6.string.big`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.string.big.js), [`es6.string.blink`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.string.blink.js), [`es6.string.bold`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.string.bold.js), [`es6.string.fixed`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.string.fixed.js), [`es6.string.fontcolor`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.string.fontcolor.js), [`es6.string.fontsize`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.string.fontsize.js), [`es6.string.italics`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.string.italics.js), [`es6.string.link`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.string.link.js), [`es6.string.small`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.string.small.js), [`es6.string.strike`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.string.strike.js), [`es6.string.sub`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.string.sub.js) and [`es6.string.sup`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.string.sup.js). ```js String .fromCodePoint(...codePoints) -> str .raw({raw}, ...substitutions) -> str #includes(str, from?) -> bool #startsWith(str, from?) -> bool #endsWith(str, from?) -> bool #repeat(num) -> str #codePointAt(pos) -> uint #trim() -> str, ES6 fix #anchor(name) -> str #big() -> str #blink() -> str #bold() -> str #fixed() -> str #fontcolor(color) -> str #fontsize(size) -> str #italics() -> str #link(url) -> str #small() -> str #strike() -> str #sub() -> str #sup() -> str #@@iterator() -> iterator (code points) ``` [*CommonJS entry points:*](#commonjs) ``` core-js(/library)/es6/string core-js(/library)/fn/string/from-code-point core-js(/library)/fn/string/raw core-js(/library)/fn/string/includes core-js(/library)/fn/string/starts-with core-js(/library)/fn/string/ends-with core-js(/library)/fn/string/repeat core-js(/library)/fn/string/code-point-at core-js(/library)/fn/string/trim core-js(/library)/fn/string/anchor core-js(/library)/fn/string/big core-js(/library)/fn/string/blink core-js(/library)/fn/string/bold core-js(/library)/fn/string/fixed core-js(/library)/fn/string/fontcolor core-js(/library)/fn/string/fontsize core-js(/library)/fn/string/italics core-js(/library)/fn/string/link core-js(/library)/fn/string/small core-js(/library)/fn/string/strike core-js(/library)/fn/string/sub core-js(/library)/fn/string/sup core-js(/library)/fn/string/iterator core-js(/library)/fn/string/virtual/includes core-js(/library)/fn/string/virtual/starts-with core-js(/library)/fn/string/virtual/ends-with core-js(/library)/fn/string/virtual/repeat core-js(/library)/fn/string/virtual/code-point-at core-js(/library)/fn/string/virtual/trim core-js(/library)/fn/string/virtual/anchor core-js(/library)/fn/string/virtual/big core-js(/library)/fn/string/virtual/blink core-js(/library)/fn/string/virtual/bold core-js(/library)/fn/string/virtual/fixed core-js(/library)/fn/string/virtual/fontcolor core-js(/library)/fn/string/virtual/fontsize core-js(/library)/fn/string/virtual/italics core-js(/library)/fn/string/virtual/link core-js(/library)/fn/string/virtual/small core-js(/library)/fn/string/virtual/strike core-js(/library)/fn/string/virtual/sub core-js(/library)/fn/string/virtual/sup core-js(/library)/fn/string/virtual/iterator ``` [*Examples*](http://goo.gl/3UaQ93): ```js for(var val of 'a𠮷b'){ console.log(val); // => 'a', '𠮷', 'b' } 'foobarbaz'.includes('bar'); // => true 'foobarbaz'.includes('bar', 4); // => false 'foobarbaz'.startsWith('foo'); // => true 'foobarbaz'.startsWith('bar', 3); // => true 'foobarbaz'.endsWith('baz'); // => true 'foobarbaz'.endsWith('bar', 6); // => true 'string'.repeat(3); // => 'stringstringstring' '𠮷'.codePointAt(0); // => 134071 String.fromCodePoint(97, 134071, 98); // => 'a𠮷b' var name = 'Bob'; String.raw`Hi\n${name}!`; // => 'Hi\\nBob!' (ES6 template string syntax) String.raw({raw: 'test'}, 0, 1, 2); // => 't0e1s2t' 'foo'.bold(); // => '<b>foo</b>' 'bar'.anchor('a"b'); // => '<a name="a&quot;b">bar</a>' 'baz'.link('http://example.com'); // => '<a href="http://example.com">baz</a>' ``` #### ECMAScript 6: RegExp Modules [`es6.regexp.constructor`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.regexp.constructor.js) and [`es6.regexp.flags`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.regexp.flags.js). Support well-known [symbols](#ecmascript-6-symbol) `@@match`, `@@replace`, `@@search` and `@@split`, modules [`es6.regexp.match`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.regexp.match.js), [`es6.regexp.replace`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.regexp.replace.js), [`es6.regexp.search`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.regexp.search.js) and [`es6.regexp.split`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.regexp.split.js). ``` [new] RegExp(pattern, flags?) -> regexp, ES6 fix: can alter flags (IE9+) #flags -> str (IE9+) #toString() -> str, ES6 fixes #@@match(str) -> array | null #@@replace(str, replacer) -> string #@@search(str) -> index #@@split(str, limit) -> array String #match(tpl) -> var, ES6 fix for support @@match #replace(tpl, replacer) -> var, ES6 fix for support @@replace #search(tpl) -> var, ES6 fix for support @@search #split(tpl, limit) -> var, ES6 fix for support @@split, some fixes for old engines ``` [*CommonJS entry points:*](#commonjs) ``` core-js/es6/regexp core-js/fn/regexp/constructor core-js(/library)/fn/regexp/flags core-js/fn/regexp/to-string core-js/fn/regexp/match core-js/fn/regexp/replace core-js/fn/regexp/search core-js/fn/regexp/split ``` [*Examples*](http://goo.gl/PiJxBD): ```js RegExp(/./g, 'm'); // => /./m /foo/.flags; // => '' /foo/gim.flags; // => 'gim' 'foo'.match({[Symbol.match]: _ => 1}); // => 1 'foo'.replace({[Symbol.replace]: _ => 2}); // => 2 'foo'.search({[Symbol.search]: _ => 3}); // => 3 'foo'.split({[Symbol.split]: _ => 4}); // => 4 RegExp.prototype.toString.call({source: 'foo', flags: 'bar'}); // => '/foo/bar' ``` #### ECMAScript 6: Number Module [`es6.number.constructor`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.number.constructor.js). `Number` constructor support binary and octal literals, [*example*](http://goo.gl/jRd6b3): ```js Number('0b1010101'); // => 85 Number('0o7654321'); // => 2054353 ``` Modules [`es6.number.epsilon`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.number.epsilon.js), [`es6.number.is-finite`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.number.is-finite.js), [`es6.number.is-integer`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.number.is-integer.js), [`es6.number.is-nan`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.number.is-nan.js), [`es6.number.is-safe-integer`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.number.is-safe-integer.js), [`es6.number.max-safe-integer`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.number.max-safe-integer.js), [`es6.number.min-safe-integer`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.number.min-safe-integer.js), [`es6.number.parse-float`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.number.parse-float.js), [`es6.number.parse-int`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.number.parse-int.js), [`es6.number.to-fixed`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.number.to-fixed.js), [`es6.number.to-precision`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.number.to-precision.js), [`es6.parse-int`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.parse-int.js), [`es6.parse-float`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.parse-float.js). ```js [new] Number(var) -> number | number object .isFinite(num) -> bool .isNaN(num) -> bool .isInteger(num) -> bool .isSafeInteger(num) -> bool .parseFloat(str) -> num .parseInt(str) -> int .EPSILON -> num .MAX_SAFE_INTEGER -> int .MIN_SAFE_INTEGER -> int #toFixed(digits) -> string, fixes #toPrecision(precision) -> string, fixes parseFloat(str) -> num, fixes parseInt(str) -> int, fixes ``` [*CommonJS entry points:*](#commonjs) ``` core-js(/library)/es6/number core-js/es6/number/constructor core-js(/library)/fn/number/is-finite core-js(/library)/fn/number/is-nan core-js(/library)/fn/number/is-integer core-js(/library)/fn/number/is-safe-integer core-js(/library)/fn/number/parse-float core-js(/library)/fn/number/parse-int core-js(/library)/fn/number/epsilon core-js(/library)/fn/number/max-safe-integer core-js(/library)/fn/number/min-safe-integer core-js(/library)/fn/number/to-fixed core-js(/library)/fn/number/to-precision core-js(/library)/fn/parse-float core-js(/library)/fn/parse-int ``` #### ECMAScript 6: Math Modules [`es6.math.acosh`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.math.acosh.js), [`es6.math.asinh`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.math.asinh.js), [`es6.math.atanh`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.math.atanh.js), [`es6.math.cbrt`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.math.cbrt.js), [`es6.math.clz32`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.math.clz32.js), [`es6.math.cosh`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.math.cosh.js), [`es6.math.expm1`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.math.expm1.js), [`es6.math.fround`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.math.fround.js), [`es6.math.hypot`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.math.hypot.js), [`es6.math.imul`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.math.imul.js), [`es6.math.log10`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.math.log10.js), [`es6.math.log1p`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.math.log1p.js), [`es6.math.log2`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.math.log2.js), [`es6.math.sign`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.math.sign.js), [`es6.math.sinh`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.math.sinh.js), [`es6.math.tanh`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.math.tanh.js), [`es6.math.trunc`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.math.trunc.js). ```js Math .acosh(num) -> num .asinh(num) -> num .atanh(num) -> num .cbrt(num) -> num .clz32(num) -> uint .cosh(num) -> num .expm1(num) -> num .fround(num) -> num .hypot(...args) -> num .imul(num, num) -> int .log1p(num) -> num .log10(num) -> num .log2(num) -> num .sign(num) -> 1 | -1 | 0 | -0 | NaN .sinh(num) -> num .tanh(num) -> num .trunc(num) -> num ``` [*CommonJS entry points:*](#commonjs) ``` core-js(/library)/es6/math core-js(/library)/fn/math/acosh core-js(/library)/fn/math/asinh core-js(/library)/fn/math/atanh core-js(/library)/fn/math/cbrt core-js(/library)/fn/math/clz32 core-js(/library)/fn/math/cosh core-js(/library)/fn/math/expm1 core-js(/library)/fn/math/fround core-js(/library)/fn/math/hypot core-js(/library)/fn/math/imul core-js(/library)/fn/math/log1p core-js(/library)/fn/math/log10 core-js(/library)/fn/math/log2 core-js(/library)/fn/math/sign core-js(/library)/fn/math/sinh core-js(/library)/fn/math/tanh core-js(/library)/fn/math/trunc ``` #### ECMAScript 6: Date Modules [`es6.date.to-string`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.date.to-string.js), ES5 features with fixes: [`es6.date.now`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.date.now.js), [`es6.date.to-iso-string`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.date.to-iso-string.js), [`es6.date.to-json`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.date.to-json.js) and [`es6.date.to-primitive`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.date.to-primitive.js). ```js Date .now() -> int #toISOString() -> string #toJSON() -> string #toString() -> string #@@toPrimitive(hint) -> primitive ``` [*CommonJS entry points:*](#commonjs) ``` core-js/es6/date core-js/fn/date/to-string core-js(/library)/fn/date/now core-js(/library)/fn/date/to-iso-string core-js(/library)/fn/date/to-json core-js(/library)/fn/date/to-primitive ``` [*Example*](http://goo.gl/haeHLR): ```js new Date(NaN).toString(); // => 'Invalid Date' ``` #### ECMAScript 6: Promise Module [`es6.promise`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.promise.js). ```js new Promise(executor(resolve(var), reject(var))) -> promise #then(resolved(var), rejected(var)) -> promise #catch(rejected(var)) -> promise .resolve(promise | var) -> promise .reject(var) -> promise .all(iterable) -> promise .race(iterable) -> promise ``` [*CommonJS entry points:*](#commonjs) ``` core-js(/library)/es6/promise core-js(/library)/fn/promise ``` Basic [*example*](http://goo.gl/vGrtUC): ```js function sleepRandom(time){ return new Promise(function(resolve, reject){ setTimeout(resolve, time * 1e3, 0 | Math.random() * 1e3); }); } console.log('Run'); // => Run sleepRandom(5).then(function(result){ console.log(result); // => 869, after 5 sec. return sleepRandom(10); }).then(function(result){ console.log(result); // => 202, after 10 sec. }).then(function(){ console.log('immediately after'); // => immediately after throw Error('Irror!'); }).then(function(){ console.log('will not be displayed'); }).catch(x => console.log(x)); // => => Error: Irror! ``` `Promise.resolve` and `Promise.reject` [*example*](http://goo.gl/vr8TN3): ```js Promise.resolve(42).then(x => console.log(x)); // => 42 Promise.reject(42).catch(x => console.log(x)); // => 42 Promise.resolve($.getJSON('/data.json')); // => ES6 promise ``` `Promise.all` [*example*](http://goo.gl/RdoDBZ): ```js Promise.all([ 'foo', sleepRandom(5), sleepRandom(15), sleepRandom(10) // after 15 sec: ]).then(x => console.log(x)); // => ['foo', 956, 85, 382] ``` `Promise.race` [*example*](http://goo.gl/L8ovkJ): ```js function timeLimit(promise, time){ return Promise.race([promise, new Promise(function(resolve, reject){ setTimeout(reject, time * 1e3, Error('Await > ' + time + ' sec')); })]); } timeLimit(sleepRandom(5), 10).then(x => console.log(x)); // => 853, after 5 sec. timeLimit(sleepRandom(15), 10).catch(x => console.log(x)); // Error: Await > 10 sec ``` ECMAScript 7 [async functions](https://tc39.github.io/ecmascript-asyncawait) [example](http://goo.gl/wnQS4j): ```js var delay = time => new Promise(resolve => setTimeout(resolve, time)) async function sleepRandom(time){ await delay(time * 1e3); return 0 | Math.random() * 1e3; }; async function sleepError(time, msg){ await delay(time * 1e3); throw Error(msg); }; (async () => { try { console.log('Run'); // => Run console.log(await sleepRandom(5)); // => 936, after 5 sec. var [a, b, c] = await Promise.all([ sleepRandom(5), sleepRandom(15), sleepRandom(10) ]); console.log(a, b, c); // => 210 445 71, after 15 sec. await sleepError(5, 'Irror!'); console.log('Will not be displayed'); } catch(e){ console.log(e); // => Error: 'Irror!', after 5 sec. } })(); ``` ##### Unhandled rejection tracking In Node.js, like in native implementation, available events [`unhandledRejection`](https://nodejs.org/api/process.html#process_event_unhandledrejection) and [`rejectionHandled`](https://nodejs.org/api/process.html#process_event_rejectionhandled): ```js process.on('unhandledRejection', (reason, promise) => console.log('unhandled', reason, promise)); process.on('rejectionHandled', (promise) => console.log('handled', promise)); var p = Promise.reject(42); // unhandled 42 [object Promise] setTimeout(() => p.catch(_ => _), 1e3); // handled [object Promise] ``` In a browser on rejection, by default, you will see notify in the console, or you can add a custom handler and a handler on handling unhandled, [*example*](http://goo.gl/Wozskl): ```js window.onunhandledrejection = e => console.log('unhandled', e.reason, e.promise); window.onrejectionhandled = e => console.log('handled', e.reason, e.promise); var p = Promise.reject(42); // unhandled 42 [object Promise] setTimeout(() => p.catch(_ => _), 1e3); // handled 42 [object Promise] ``` #### ECMAScript 6: Symbol Module [`es6.symbol`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.symbol.js). ```js Symbol(description?) -> symbol .hasInstance -> @@hasInstance .isConcatSpreadable -> @@isConcatSpreadable .iterator -> @@iterator .match -> @@match .replace -> @@replace .search -> @@search .species -> @@species .split -> @@split .toPrimitive -> @@toPrimitive .toStringTag -> @@toStringTag .unscopables -> @@unscopables .for(key) -> symbol .keyFor(symbol) -> key .useSimple() -> void .useSetter() -> void Object .getOwnPropertySymbols(object) -> array ``` Also wrapped some methods for correct work with `Symbol` polyfill. ```js Object .create(proto | null, descriptors?) -> object .defineProperty(target, key, desc) -> target .defineProperties(target, descriptors) -> target .getOwnPropertyDescriptor(var, key) -> desc | undefined .getOwnPropertyNames(var) -> array #propertyIsEnumerable(key) -> bool JSON .stringify(target, replacer?, space?) -> string | undefined ``` [*CommonJS entry points:*](#commonjs) ``` core-js(/library)/es6/symbol core-js(/library)/fn/symbol core-js(/library)/fn/symbol/has-instance core-js(/library)/fn/symbol/is-concat-spreadable core-js(/library)/fn/symbol/iterator core-js(/library)/fn/symbol/match core-js(/library)/fn/symbol/replace core-js(/library)/fn/symbol/search core-js(/library)/fn/symbol/species core-js(/library)/fn/symbol/split core-js(/library)/fn/symbol/to-primitive core-js(/library)/fn/symbol/to-string-tag core-js(/library)/fn/symbol/unscopables core-js(/library)/fn/symbol/for core-js(/library)/fn/symbol/key-for ``` [*Basic example*](http://goo.gl/BbvWFc): ```js var Person = (function(){ var NAME = Symbol('name'); function Person(name){ this[NAME] = name; } Person.prototype.getName = function(){ return this[NAME]; }; return Person; })(); var person = new Person('Vasya'); console.log(person.getName()); // => 'Vasya' console.log(person['name']); // => undefined console.log(person[Symbol('name')]); // => undefined, symbols are uniq for(var key in person)console.log(key); // => only 'getName', symbols are not enumerable ``` `Symbol.for` & `Symbol.keyFor` [*example*](http://goo.gl/0pdJjX): ```js var symbol = Symbol.for('key'); symbol === Symbol.for('key'); // true Symbol.keyFor(symbol); // 'key' ``` [*Example*](http://goo.gl/mKVOQJ) with methods for getting own object keys: ```js var O = {a: 1}; Object.defineProperty(O, 'b', {value: 2}); O[Symbol('c')] = 3; Object.keys(O); // => ['a'] Object.getOwnPropertyNames(O); // => ['a', 'b'] Object.getOwnPropertySymbols(O); // => [Symbol(c)] Reflect.ownKeys(O); // => ['a', 'b', Symbol(c)] ``` ##### Caveats when using `Symbol` polyfill: * We can't add new primitive type, `Symbol` returns object. * `Symbol.for` and `Symbol.keyFor` can't be shimmed cross-realm. * By default, to hide the keys, `Symbol` polyfill defines setter in `Object.prototype`. For this reason, uncontrolled creation of symbols can cause memory leak and the `in` operator is not working correctly with `Symbol` polyfill: `Symbol() in {} // => true`. You can disable defining setters in `Object.prototype`. [Example](http://goo.gl/N5UD7J): ```js Symbol.useSimple(); var s1 = Symbol('s1') , o1 = {}; o1[s1] = true; for(var key in o1)console.log(key); // => 'Symbol(s1)_t.qamkg9f3q', w/o native Symbol Symbol.useSetter(); var s2 = Symbol('s2') , o2 = {}; o2[s2] = true; for(var key in o2)console.log(key); // nothing ``` * Currently, `core-js` not adds setters to `Object.prototype` for well-known symbols for correct work something like `Symbol.iterator in foo`. It can cause problems with their enumerability. * Some problems possible with environment exotic objects (for example, IE `localStorage`). #### ECMAScript 6: Collections `core-js` uses native collections in most case, just fixes methods / constructor, if it's required, and in old environment uses fast polyfill (O(1) lookup). #### Map Module [`es6.map`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.map.js). ```js new Map(iterable (entries) ?) -> map #clear() -> void #delete(key) -> bool #forEach(fn(val, key, @), that) -> void #get(key) -> val #has(key) -> bool #set(key, val) -> @ #size -> uint #values() -> iterator #keys() -> iterator #entries() -> iterator #@@iterator() -> iterator (entries) ``` [*CommonJS entry points:*](#commonjs) ``` core-js(/library)/es6/map core-js(/library)/fn/map ``` [*Examples*](http://goo.gl/GWR7NI): ```js var a = [1]; var map = new Map([['a', 1], [42, 2]]); map.set(a, 3).set(true, 4); console.log(map.size); // => 4 console.log(map.has(a)); // => true console.log(map.has([1])); // => false console.log(map.get(a)); // => 3 map.forEach(function(val, key){ console.log(val); // => 1, 2, 3, 4 console.log(key); // => 'a', 42, [1], true }); map.delete(a); console.log(map.size); // => 3 console.log(map.get(a)); // => undefined console.log(Array.from(map)); // => [['a', 1], [42, 2], [true, 4]] var map = new Map([['a', 1], ['b', 2], ['c', 3]]); for(var [key, val] of map){ console.log(key); // => 'a', 'b', 'c' console.log(val); // => 1, 2, 3 } for(var val of map.values())console.log(val); // => 1, 2, 3 for(var key of map.keys())console.log(key); // => 'a', 'b', 'c' for(var [key, val] of map.entries()){ console.log(key); // => 'a', 'b', 'c' console.log(val); // => 1, 2, 3 } ``` #### Set Module [`es6.set`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.set.js). ```js new Set(iterable?) -> set #add(key) -> @ #clear() -> void #delete(key) -> bool #forEach(fn(el, el, @), that) -> void #has(key) -> bool #size -> uint #values() -> iterator #keys() -> iterator #entries() -> iterator #@@iterator() -> iterator (values) ``` [*CommonJS entry points:*](#commonjs) ``` core-js(/library)/es6/set core-js(/library)/fn/set ``` [*Examples*](http://goo.gl/bmhLwg): ```js var set = new Set(['a', 'b', 'a', 'c']); set.add('d').add('b').add('e'); console.log(set.size); // => 5 console.log(set.has('b')); // => true set.forEach(function(it){ console.log(it); // => 'a', 'b', 'c', 'd', 'e' }); set.delete('b'); console.log(set.size); // => 4 console.log(set.has('b')); // => false console.log(Array.from(set)); // => ['a', 'c', 'd', 'e'] var set = new Set([1, 2, 3, 2, 1]); for(var val of set)console.log(val); // => 1, 2, 3 for(var val of set.values())console.log(val); // => 1, 2, 3 for(var key of set.keys())console.log(key); // => 1, 2, 3 for(var [key, val] of set.entries()){ console.log(key); // => 1, 2, 3 console.log(val); // => 1, 2, 3 } ``` #### WeakMap Module [`es6.weak-map`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.weak-map.js). ```js new WeakMap(iterable (entries) ?) -> weakmap #delete(key) -> bool #get(key) -> val #has(key) -> bool #set(key, val) -> @ ``` [*CommonJS entry points:*](#commonjs) ``` core-js(/library)/es6/weak-map core-js(/library)/fn/weak-map ``` [*Examples*](http://goo.gl/SILXyw): ```js var a = [1] , b = [2] , c = [3]; var wmap = new WeakMap([[a, 1], [b, 2]]); wmap.set(c, 3).set(b, 4); console.log(wmap.has(a)); // => true console.log(wmap.has([1])); // => false console.log(wmap.get(a)); // => 1 wmap.delete(a); console.log(wmap.get(a)); // => undefined // Private properties store: var Person = (function(){ var names = new WeakMap; function Person(name){ names.set(this, name); } Person.prototype.getName = function(){ return names.get(this); }; return Person; })(); var person = new Person('Vasya'); console.log(person.getName()); // => 'Vasya' for(var key in person)console.log(key); // => only 'getName' ``` #### WeakSet Module [`es6.weak-set`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.weak-set.js). ```js new WeakSet(iterable?) -> weakset #add(key) -> @ #delete(key) -> bool #has(key) -> bool ``` [*CommonJS entry points:*](#commonjs) ``` core-js(/library)/es6/weak-set core-js(/library)/fn/weak-set ``` [*Examples*](http://goo.gl/TdFbEx): ```js var a = [1] , b = [2] , c = [3]; var wset = new WeakSet([a, b, a]); wset.add(c).add(b).add(c); console.log(wset.has(b)); // => true console.log(wset.has([2])); // => false wset.delete(b); console.log(wset.has(b)); // => false ``` ##### Caveats when using collections polyfill: * Weak-collections polyfill stores values as hidden properties of keys. It works correct and not leak in most cases. However, it is desirable to store a collection longer than its keys. #### ECMAScript 6: Typed Arrays Implementations and fixes `ArrayBuffer`, `DataView`, typed arrays constructors, static and prototype methods. Typed Arrays work only in environments with support descriptors (IE9+), `ArrayBuffer` and `DataView` should work anywhere. Modules [`es6.typed.array-buffer`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.typed.array-buffer.js), [`es6.typed.data-view`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.typed.data-view.js), [`es6.typed.int8-array`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.typed.int8-array.js), [`es6.typed.uint8-array`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.typed.uint8-array.js), [`es6.typed.uint8-clamped-array`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.typed.uint8-clamped-array.js), [`es6.typed.int16-array`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.typed.int16-array.js), [`es6.typed.uint16-array`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.typed.uint16-array.js), [`es6.typed.int32-array`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.typed.int32-array.js), [`es6.typed.uint32-array`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.typed.uint32-array.js), [`es6.typed.float32-array`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.typed.float32-array.js) and [`es6.typed.float64-array`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.typed.float64-array.js). ```js new ArrayBuffer(length) -> buffer .isView(var) -> bool #slice(start = 0, end = @length) -> buffer #byteLength -> uint new DataView(buffer, byteOffset = 0, byteLength = buffer.byteLength - byteOffset) -> view #getInt8(offset) -> int8 #getUint8(offset) -> uint8 #getInt16(offset, littleEndian = false) -> int16 #getUint16(offset, littleEndian = false) -> uint16 #getInt32(offset, littleEndian = false) -> int32 #getUint32(offset, littleEndian = false) -> uint32 #getFloat32(offset, littleEndian = false) -> float32 #getFloat64(offset, littleEndian = false) -> float64 #setInt8(offset, value) -> void #setUint8(offset, value) -> void #setInt16(offset, value, littleEndian = false) -> void #setUint16(offset, value, littleEndian = false) -> void #setInt32(offset, value, littleEndian = false) -> void #setUint32(offset, value, littleEndian = false) -> void #setFloat32(offset, value, littleEndian = false) -> void #setFloat64(offset, value, littleEndian = false) -> void #buffer -> buffer #byteLength -> uint #byteOffset -> uint { Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array } new %TypedArray%(length) -> typed new %TypedArray%(typed) -> typed new %TypedArray%(arrayLike) -> typed new %TypedArray%(iterable) -> typed new %TypedArray%(buffer, byteOffset = 0, length = (buffer.byteLength - byteOffset) / @BYTES_PER_ELEMENT) -> typed .BYTES_PER_ELEMENT -> uint .from(arrayLike | iterable, mapFn(val, index)?, that) -> typed .of(...args) -> typed #BYTES_PER_ELEMENT -> uint #copyWithin(target = 0, start = 0, end = @length) -> @ #every(fn(val, index, @), that) -> bool #fill(val, start = 0, end = @length) -> @ #filter(fn(val, index, @), that) -> typed #find(fn(val, index, @), that) -> val #findIndex(fn(val, index, @), that) -> index #forEach(fn(val, index, @), that) -> void #indexOf(var, from?) -> int #join(string = ',') -> string #lastIndexOf(var, from?) -> int #map(fn(val, index, @), that) -> typed #reduce(fn(memo, val, index, @), memo?) -> var #reduceRight(fn(memo, val, index, @), memo?) -> var #reverse() -> @ #set(arrayLike, offset = 0) -> void #slice(start = 0, end = @length) -> typed #some(fn(val, index, @), that) -> bool #sort(fn(a, b)?) -> @ #subarray(start = 0, end = @length) -> typed #toString() -> string #toLocaleString() -> string #values() -> iterator #keys() -> iterator #entries() -> iterator #@@iterator() -> iterator (values) #buffer -> buffer #byteLength -> uint #byteOffset -> uint #length -> uint ``` [*CommonJS entry points:*](#commonjs) ``` core-js(/library)/es6/typed core-js(/library)/fn/typed core-js(/library)/fn/typed/array-buffer core-js(/library)/fn/typed/data-view core-js(/library)/fn/typed/int8-array core-js(/library)/fn/typed/uint8-array core-js(/library)/fn/typed/uint8-clamped-array core-js(/library)/fn/typed/int16-array core-js(/library)/fn/typed/uint16-array core-js(/library)/fn/typed/int32-array core-js(/library)/fn/typed/uint32-array core-js(/library)/fn/typed/float32-array core-js(/library)/fn/typed/float64-array ``` [*Examples*](http://goo.gl/yla75z): ```js new Int32Array(4); // => [0, 0, 0, 0] new Uint8ClampedArray([1, 2, 3, 666]); // => [1, 2, 3, 255] new Float32Array(new Set([1, 2, 3, 2, 1])); // => [1, 2, 3] var buffer = new ArrayBuffer(8); var view = new DataView(buffer); view.setFloat64(0, 123.456, true); new Uint8Array(buffer.slice(4)); // => [47, 221, 94, 64] Int8Array.of(1, 1.5, 5.7, 745); // => [1, 1, 5, -23] Uint8Array.from([1, 1.5, 5.7, 745]); // => [1, 1, 5, 233] var typed = new Uint8Array([1, 2, 3]); var a = typed.slice(1); // => [2, 3] typed.buffer === a.buffer; // => false var b = typed.subarray(1); // => [2, 3] typed.buffer === b.buffer; // => true typed.filter(it => it % 2); // => [1, 3] typed.map(it => it * 1.5); // => [1, 3, 4] for(var val of typed)console.log(val); // => 1, 2, 3 for(var val of typed.values())console.log(val); // => 1, 2, 3 for(var key of typed.keys())console.log(key); // => 0, 1, 2 for(var [key, val] of typed.entries()){ console.log(key); // => 0, 1, 2 console.log(val); // => 1, 2, 3 } ``` ##### Caveats when using typed arrays: * Typed Arrays polyfills works completely how should work by the spec, but because of internal use getter / setters on each instance, is slow and consumes significant memory. However, typed arrays polyfills required mainly for IE9 (and for `Uint8ClampedArray` in IE10 and early IE11), all modern engines have native typed arrays and requires only constructors fixes and methods. * The current version hasn't special entry points for methods, they can be added only with constructors. It can be added in the future. * In the `library` version we can't pollute native prototypes, so prototype methods available as constructors static. #### ECMAScript 6: Reflect Modules [`es6.reflect.apply`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.reflect.apply.js), [`es6.reflect.construct`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.reflect.construct.js), [`es6.reflect.define-property`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.reflect.define-property.js), [`es6.reflect.delete-property`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.reflect.delete-property.js), [`es6.reflect.enumerate`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.reflect.enumerate.js), [`es6.reflect.get`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.reflect.get.js), [`es6.reflect.get-own-property-descriptor`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.reflect.get-own-property-descriptor.js), [`es6.reflect.get-prototype-of`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.reflect.get-prototype-of.js), [`es6.reflect.has`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.reflect.has.js), [`es6.reflect.is-extensible`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.reflect.is-extensible.js), [`es6.reflect.own-keys`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.reflect.own-keys.js), [`es6.reflect.prevent-extensions`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.reflect.prevent-extensions.js), [`es6.reflect.set`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.reflect.set.js), [`es6.reflect.set-prototype-of`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es6.reflect.set-prototype-of.js). ```js Reflect .apply(target, thisArgument, argumentsList) -> var .construct(target, argumentsList, newTarget?) -> object .defineProperty(target, propertyKey, attributes) -> bool .deleteProperty(target, propertyKey) -> bool .enumerate(target) -> iterator (removed from the spec and will be removed from core-js@3) .get(target, propertyKey, receiver?) -> var .getOwnPropertyDescriptor(target, propertyKey) -> desc .getPrototypeOf(target) -> object | null .has(target, propertyKey) -> bool .isExtensible(target) -> bool .ownKeys(target) -> array .preventExtensions(target) -> bool .set(target, propertyKey, V, receiver?) -> bool .setPrototypeOf(target, proto) -> bool (required __proto__ - IE11+) ``` [*CommonJS entry points:*](#commonjs) ``` core-js(/library)/es6/reflect core-js(/library)/fn/reflect core-js(/library)/fn/reflect/apply core-js(/library)/fn/reflect/construct core-js(/library)/fn/reflect/define-property core-js(/library)/fn/reflect/delete-property core-js(/library)/fn/reflect/enumerate (deprecated and will be removed from the next major release) core-js(/library)/fn/reflect/get core-js(/library)/fn/reflect/get-own-property-descriptor core-js(/library)/fn/reflect/get-prototype-of core-js(/library)/fn/reflect/has core-js(/library)/fn/reflect/is-extensible core-js(/library)/fn/reflect/own-keys core-js(/library)/fn/reflect/prevent-extensions core-js(/library)/fn/reflect/set core-js(/library)/fn/reflect/set-prototype-of ``` [*Examples*](http://goo.gl/gVT0cH): ```js var O = {a: 1}; Object.defineProperty(O, 'b', {value: 2}); O[Symbol('c')] = 3; Reflect.ownKeys(O); // => ['a', 'b', Symbol(c)] function C(a, b){ this.c = a + b; } var instance = Reflect.construct(C, [20, 22]); instance.c; // => 42 ``` ### ECMAScript 7+ proposals [The TC39 process.](https://tc39.github.io/process-document/) [*CommonJS entry points:*](#commonjs) ``` core-js(/library)/es7 core-js(/library)/es7/array core-js(/library)/es7/global core-js(/library)/es7/string core-js(/library)/es7/map core-js(/library)/es7/set core-js(/library)/es7/error core-js(/library)/es7/math core-js(/library)/es7/system core-js(/library)/es7/symbol core-js(/library)/es7/reflect core-js(/library)/es7/observable ``` `core-js/stage/4` entry point contains only stage 4 proposals, `core-js/stage/3` - stage 3 and stage 4, etc. #### Stage 4 proposals [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/stage/4 ``` * `{Array, %TypedArray%}#includes` [proposal](https://github.com/tc39/Array.prototype.includes) - module [`es7.array.includes`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.array.includes.js), `%TypedArray%` version in modules from [this section](#ecmascript-6-typed-arrays). ```js Array #includes(var, from?) -> bool { Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array } #includes(var, from?) -> bool ``` [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/fn/array/includes ``` [*Examples*](http://goo.gl/2Gq4ma): ```js [1, 2, 3].includes(2); // => true [1, 2, 3].includes(4); // => false [1, 2, 3].includes(2, 2); // => false [NaN].indexOf(NaN); // => -1 [NaN].includes(NaN); // => true Array(1).indexOf(undefined); // => -1 Array(1).includes(undefined); // => true ``` * `Object.values`, `Object.entries` [proposal](https://github.com/tc39/proposal-object-values-entries) - modules [`es7.object.values`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.object.values.js), [`es7.object.entries`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.object.entries.js) ```js Object .values(object) -> array .entries(object) -> array ``` [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/fn/object/values core-js(/library)/fn/object/entries ``` [*Examples*](http://goo.gl/6kuGOn): ```js Object.values({a: 1, b: 2, c: 3}); // => [1, 2, 3] Object.entries({a: 1, b: 2, c: 3}); // => [['a', 1], ['b', 2], ['c', 3]] for(let [key, value] of Object.entries({a: 1, b: 2, c: 3})){ console.log(key); // => 'a', 'b', 'c' console.log(value); // => 1, 2, 3 } ``` * `Object.getOwnPropertyDescriptors` [proposal](https://github.com/tc39/proposal-object-getownpropertydescriptors) - module [`es7.object.get-own-property-descriptors`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.object.get-own-property-descriptors.js) ```js Object .getOwnPropertyDescriptors(object) -> object ``` [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/fn/object/get-own-property-descriptors ``` *Examples*: ```js // Shallow object cloning with prototype and descriptors: var copy = Object.create(Object.getPrototypeOf(O), Object.getOwnPropertyDescriptors(O)); // Mixin: Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); ``` * `String#padStart`, `String#padEnd` [proposal](https://github.com/tc39/proposal-string-pad-start-end) - modules [`es7.string.pad-start`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.string.pad-start.js), [`es7.string.pad-end`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.string.pad-end.js) ```js String #padStart(length, fillStr = ' ') -> string #padEnd(length, fillStr = ' ') -> string ``` [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/fn/string/pad-start core-js(/library)/fn/string/pad-end core-js(/library)/fn/string/virtual/pad-start core-js(/library)/fn/string/virtual/pad-end ``` [*Examples*](http://goo.gl/hK5ccv): ```js 'hello'.padStart(10); // => ' hello' 'hello'.padStart(10, '1234'); // => '12341hello' 'hello'.padEnd(10); // => 'hello ' 'hello'.padEnd(10, '1234'); // => 'hello12341' ``` * `Object#__(define|lookup)[GS]etter__`, [annex B ES2017](https://github.com/tc39/ecma262/pull/381), but we haven't special namespace for that - modules [`es7.object.define-setter`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.object.define-setter.js), [`es7.object.define-getter`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.object.define-getter.js), [`es7.object.lookup-setter`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.object.lookup-setter.js) and [`es7.object.lookup-getter`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.object.lookup-getter.js). ```js Object #__defineSetter__(key, fn) -> void #__defineGetter__(key, fn) -> void #__lookupSetter__(key) -> fn | void #__lookupGetter__(key) -> fn | void ``` [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/fn/object/define-getter core-js(/library)/fn/object/define-setter core-js(/library)/fn/object/lookup-getter core-js(/library)/fn/object/lookup-setter ``` #### Stage 3 proposals [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/stage/3 ``` * `global` [proposal](https://github.com/tc39/proposal-global) - modules [`es7.global`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.global.js) and [`es7.system.global`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.system.global.js) (obsolete) ```js global -> object System .global -> object (obsolete) ``` [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/fn/global core-js(/library)/fn/system/global (obsolete) ``` [*Examples*](http://goo.gl/gEqMl7): ```js global.Array === Array; // => true ``` * `Promise#finally` [proposal](https://github.com/tc39/proposal-promise-finally) - module [`es7.promise.finally`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.promise.finally.js) ```js Promise #finally(onFinally()) -> promise ``` [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/fn/promise/finally ``` [*Examples*](https://goo.gl/AhyBbJ): ```js Promise.resolve(42).finally(() => console.log('You will see it anyway')); Promise.reject(42).finally(() => console.log('You will see it anyway')); #### Stage 2 proposals [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/stage/2 ``` * `String#trimLeft`, `String#trimRight` / `String#trimStart`, `String#trimEnd` [proposal](https://github.com/sebmarkbage/ecmascript-string-left-right-trim) - modules [`es7.string.trim-left`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.string.trim-right.js), [`es7.string.trim-right`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.string.trim-right.js) ```js String #trimLeft() -> string #trimRight() -> string #trimStart() -> string #trimEnd() -> string ``` [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/fn/string/trim-start core-js(/library)/fn/string/trim-end core-js(/library)/fn/string/trim-left core-js(/library)/fn/string/trim-right core-js(/library)/fn/string/virtual/trim-start core-js(/library)/fn/string/virtual/trim-end core-js(/library)/fn/string/virtual/trim-left core-js(/library)/fn/string/virtual/trim-right ``` [*Examples*](http://goo.gl/Er5lMJ): ```js ' hello '.trimLeft(); // => 'hello ' ' hello '.trimRight(); // => ' hello' ``` ``` * `Symbol.asyncIterator` for [async iteration proposal](https://github.com/tc39/proposal-async-iteration) - module [`es7.symbol.async-iterator`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.symbol.async-iterator.js) ```js Symbol .asyncIterator -> @@asyncIterator ``` [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/fn/symbol/async-iterator ``` #### Stage 1 proposals [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/stage/1 ``` * `Promise.try` [proposal](https://github.com/tc39/proposal-promise-try) - module [`es7.promise.try`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.promise.try.js) ```js Promise .try(function()) -> promise ``` [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/fn/promise/try ``` [*Examples*](https://goo.gl/k5GGRo): ```js Promise.try(() => 42).then(it => console.log(`Promise, resolved as ${it}`)); Promise.try(() => { throw 42; }).catch(it => console.log(`Promise, rejected as ${it}`)); ``` * `Array#flatten` and `Array#flatMap` [proposal](https://tc39.github.io/proposal-flatMap) - modules [`es7.array.flatten`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.array.flatten.js) and [`es7.array.flat-map`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.array.flat-map.js) ```js Array #flatten(depthArg = 1) -> array #flatMap(fn(val, key, @), that) -> array ``` [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/fn/array/flatten core-js(/library)/fn/array/flat-map core-js(/library)/fn/array/virtual/flatten core-js(/library)/fn/array/virtual/flat-map ``` [*Examples*](https://goo.gl/jTXsZi): ```js [1, [2, 3], [4, 5]].flatten(); // => [1, 2, 3, 4, 5] [1, [2, [3, [4]]], 5].flatten(); // => [1, 2, [3, [4]], 5] [1, [2, [3, [4]]], 5].flatten(3); // => [1, 2, 3, 4, 5] [{a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6}].flatMap(it => [it.a, it.b]); // => [1, 2, 3, 4, 5, 6] ``` * `.of` and `.from` methods on collection constructors [proposal](https://github.com/tc39/proposal-setmap-offrom) - modules [`es7.set.of`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.set.of.js), [`es7.set.from`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.set.from.js), [`es7.map.of`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.map.of.js), [`es7.map.from`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.map.from.js), [`es7.weak-set.of`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.weak-set.of.js), [`es7.weak-set.from`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.weak-set.from.js), [`es7.weak-map.of`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.weak-map.of.js), [`es7.weak-map.from`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.weak-map.from.js) ```js Set .of(...args) -> set .from(iterable, mapFn(val, index)?, that?) -> set Map .of(...args) -> map .from(iterable, mapFn(val, index)?, that?) -> map WeakSet .of(...args) -> weakset .from(iterable, mapFn(val, index)?, that?) -> weakset WeakMap .of(...args) -> weakmap .from(iterable, mapFn(val, index)?, that?) -> weakmap ``` [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/fn/set/of core-js(/library)/fn/set/from core-js(/library)/fn/map/of core-js(/library)/fn/map/from core-js(/library)/fn/weak-set/of core-js(/library)/fn/weak-set/from core-js(/library)/fn/weak-map/of core-js(/library)/fn/weak-map/from ``` [*Examples*](https://goo.gl/mSC7eU): ```js Set.of(1, 2, 3, 2, 1); // => Set {1, 2, 3} Map.from([[1, 2], [3, 4]], ([key, val]) => [key ** 2, val ** 2]); // => Map {1: 4, 9: 16} ``` * `String#matchAll` [proposal](https://github.com/tc39/String.prototype.matchAll) - module [`es7.string.match-all`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.string.match-all.js) ```js String #matchAll(regexp) -> iterator ``` [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/fn/string/match-all core-js(/library)/fn/string/virtual/match-all ``` [*Examples*](http://goo.gl/6kp9EB): ```js for(let [_, d, D] of '1111a2b3cccc'.matchAll(/(\d)(\D)/)){ console.log(d, D); // => 1 a, 2 b, 3 c } ``` * `Observable` [proposal](https://github.com/zenparsing/es-observable) - modules [`es7.observable`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.observable.js) and [`es7.symbol.observable`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.symbol.observable.js) ```js new Observable(fn) -> observable #subscribe(observer) -> subscription #forEach(fn) -> promise #@@observable() -> @ .of(...items) -> observable .from(observable | iterable) -> observable .@@species -> @ Symbol .observable -> @@observable ``` [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/fn/observable core-js(/library)/fn/symbol/observable ``` [*Examples*](http://goo.gl/1LDywi): ```js new Observable(observer => { observer.next('hello'); observer.next('world'); observer.complete(); }).forEach(it => console.log(it)) .then(_ => console.log('!')); ``` * `Math.{clamp, DEG_PER_RAD, degrees, fscale, rad-per-deg, radians, scale}` [proposal](https://github.com/rwaldron/proposal-math-extensions) - modules [`es7.math.clamp`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.math.clamp.js), [`es7.math.DEG_PER_RAD`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.math.DEG_PER_RAD.js), [`es7.math.degrees`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.math.degrees.js), [`es7.math.fscale`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.math.fscale.js), [`es7.math.RAD_PER_DEG`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.math.RAD_PER_DEG.js), [`es7.math.radians`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.math.radians.js) and [`es7.math.scale`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.math.scale.js) ```js Math .DEG_PER_RAD -> number .RAD_PER_DEG -> number .clamp(x, lower, upper) -> number .degrees(radians) -> number .fscale(x, inLow, inHigh, outLow, outHigh) -> number .radians(degrees) -> number .scale(x, inLow, inHigh, outLow, outHigh) -> number ``` [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/fn/math/clamp core-js(/library)/fn/math/deg-per-rad core-js(/library)/fn/math/degrees core-js(/library)/fn/math/fscale core-js(/library)/fn/math/rad-per-deg core-js(/library)/fn/math/radians core-js(/library)/fn/math/scale ``` * `Math.signbit` [proposal](http://jfbastien.github.io/papers/Math.signbit.html) - module [`es7.math.signbit`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.math.signbit.js) ```js Math .signbit(x) -> bool ``` [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/fn/math/signbit ``` [*Examples*](http://es6.zloirock.ru/): ```js Math.signbit(NaN); // => NaN Math.signbit(1); // => true Math.signbit(-1); // => false Math.signbit(0); // => true Math.signbit(-0); // => false ``` #### Stage 0 proposals [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/stage/0 ``` * `String#at` [proposal](https://github.com/mathiasbynens/String.prototype.at) - module [`es7.string.at`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.string.at.js) ```js String #at(index) -> string ``` [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/fn/string/at core-js(/library)/fn/string/virtual/at ``` [*Examples*](http://goo.gl/XluXI8): ```js 'a𠮷b'.at(1); // => '𠮷' 'a𠮷b'.at(1).length; // => 2 ``` * `Map#toJSON`, `Set#toJSON` [proposal](https://github.com/DavidBruant/Map-Set.prototype.toJSON) - modules [`es7.map.to-json`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.map.to-json.js), [`es7.set.to-json`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.set.to-json.js) (rejected and will be removed from `core-js@3`) ```js Map #toJSON() -> array (rejected and will be removed from core-js@3) Set #toJSON() -> array (rejected and will be removed from core-js@3) ``` [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/fn/map core-js(/library)/fn/set ``` * `Error.isError` [proposal](https://github.com/ljharb/proposal-is-error) - module [`es7.error.is-error`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.error.is-error.js) (withdrawn and will be removed from `core-js@3`) ```js Error .isError(it) -> bool (withdrawn and will be removed from core-js@3) ``` [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/fn/error/is-error ``` * `Math.{iaddh, isubh, imulh, umulh}` [proposal](https://gist.github.com/BrendanEich/4294d5c212a6d2254703) - modules [`es7.math.iaddh`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.math.iaddh.js), [`es7.math.isubh`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.math.isubh.js), [`es7.math.imulh`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.math.imulh.js) and [`es7.math.umulh`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.math.umulh.js) ```js Math .iaddh(lo0, hi0, lo1, hi1) -> int32 .isubh(lo0, hi0, lo1, hi1) -> int32 .imulh(a, b) -> int32 .umulh(a, b) -> uint32 ``` [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/fn/math/iaddh core-js(/library)/fn/math/isubh core-js(/library)/fn/math/imulh core-js(/library)/fn/math/umulh ``` * `global.asap`, [TC39 discussion](https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-09/sept-25.md#510-globalasap-for-enqueuing-a-microtask), module [`es7.asap`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.asap.js) ```js asap(fn) -> void ``` [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/fn/asap ``` [*Examples*](http://goo.gl/tx3SRK): ```js asap(() => console.log('called as microtask')); ``` #### Pre-stage 0 proposals [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/stage/pre ``` * `Reflect` metadata [proposal](https://github.com/jonathandturner/decorators/blob/master/specs/metadata.md) - modules [`es7.reflect.define-metadata`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.reflect.define-metadata.js), [`es7.reflect.delete-metadata`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.reflect.delete-metadata.js), [`es7.reflect.get-metadata`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.reflect.get-metadata.js), [`es7.reflect.get-metadata-keys`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.reflect.get-metadata-keys.js), [`es7.reflect.get-own-metadata`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.reflect.get-own-metadata.js), [`es7.reflect.get-own-metadata-keys`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.reflect.get-own-metadata-keys.js), [`es7.reflect.has-metadata`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.reflect.has-metadata.js), [`es7.reflect.has-own-metadata`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.reflect.has-own-metadata.js) and [`es7.reflect.metadata`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/es7.reflect.metadata.js). ```js Reflect .defineMetadata(metadataKey, metadataValue, target, propertyKey?) -> void .getMetadata(metadataKey, target, propertyKey?) -> var .getOwnMetadata(metadataKey, target, propertyKey?) -> var .hasMetadata(metadataKey, target, propertyKey?) -> bool .hasOwnMetadata(metadataKey, target, propertyKey?) -> bool .deleteMetadata(metadataKey, target, propertyKey?) -> bool .getMetadataKeys(target, propertyKey?) -> array .getOwnMetadataKeys(target, propertyKey?) -> array .metadata(metadataKey, metadataValue) -> decorator(target, targetKey?) -> void ``` [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/fn/reflect/define-metadata core-js(/library)/fn/reflect/delete-metadata core-js(/library)/fn/reflect/get-metadata core-js(/library)/fn/reflect/get-metadata-keys core-js(/library)/fn/reflect/get-own-metadata core-js(/library)/fn/reflect/get-own-metadata-keys core-js(/library)/fn/reflect/has-metadata core-js(/library)/fn/reflect/has-own-metadata core-js(/library)/fn/reflect/metadata ``` [*Examples*](http://goo.gl/KCo3PS): ```js var O = {}; Reflect.defineMetadata('foo', 'bar', O); Reflect.ownKeys(O); // => [] Reflect.getOwnMetadataKeys(O); // => ['foo'] Reflect.getOwnMetadata('foo', O); // => 'bar' ``` ### Web standards [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/web ``` #### setTimeout / setInterval Module [`web.timers`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/web.timers.js). Additional arguments fix for IE9-. ```js setTimeout(fn(...args), time, ...args) -> id setInterval(fn(...args), time, ...args) -> id ``` [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/web/timers core-js(/library)/fn/set-timeout core-js(/library)/fn/set-interval ``` ```js // Before: setTimeout(log.bind(null, 42), 1000); // After: setTimeout(log, 1000, 42); ``` #### setImmediate Module [`web.immediate`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/web.immediate.js). [`setImmediate` proposal](https://developer.mozilla.org/en-US/docs/Web/API/Window.setImmediate) polyfill. ```js setImmediate(fn(...args), ...args) -> id clearImmediate(id) -> void ``` [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/web/immediate core-js(/library)/fn/set-immediate core-js(/library)/fn/clear-immediate ``` [*Examples*](http://goo.gl/6nXGrx): ```js setImmediate(function(arg1, arg2){ console.log(arg1, arg2); // => Message will be displayed with minimum delay }, 'Message will be displayed', 'with minimum delay'); clearImmediate(setImmediate(function(){ console.log('Message will not be displayed'); })); ``` #### Iterable DOM collections Some DOM collections should have [iterable interface](https://heycam.github.io/webidl/#idl-iterable) or should be [inherited from `Array`](https://heycam.github.io/webidl/#LegacyArrayClass). That mean they should have `keys`, `values`, `entries` and `@@iterator` methods for iteration. So add them. Module [`web.dom.iterable`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/web.dom.iterable.js): ```js { CSSRuleList, CSSStyleDeclaration, CSSValueList, ClientRectList, DOMRectList, DOMStringList, DOMTokenList, DataTransferItemList, FileList, HTMLAllCollection, HTMLCollection, HTMLFormElement, HTMLSelectElement, MediaList, MimeTypeArray, NamedNodeMap, NodeList, PaintRequestList, Plugin, PluginArray, SVGLengthList, SVGNumberList, SVGPathSegList, SVGPointList, SVGStringList, SVGTransformList, SourceBufferList, StyleSheetList, TextTrackCueList, TextTrackList, TouchList } #@@iterator() -> iterator (values) { DOMTokenList, NodeList } #values() -> iterator #keys() -> iterator #entries() -> iterator ``` [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/web/dom-collections core-js(/library)/fn/dom-collections/iterator ``` [*Examples*](http://goo.gl/lfXVFl): ```js for(var {id} of document.querySelectorAll('*')){ if(id)console.log(id); } for(var [index, {id}] of document.querySelectorAll('*').entries()){ if(id)console.log(index, id); } ``` ### Non-standard [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/core ``` #### Object Modules [`core.object.is-object`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/core.object.is-object.js), [`core.object.classof`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/core.object.classof.js), [`core.object.define`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/core.object.define.js), [`core.object.make`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/core.object.make.js). ```js Object .isObject(var) -> bool .classof(var) -> string .define(target, mixin) -> target .make(proto | null, mixin?) -> object ``` [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/core/object core-js(/library)/fn/object/is-object core-js(/library)/fn/object/define core-js(/library)/fn/object/make ``` Object classify [*examples*](http://goo.gl/YZQmGo): ```js Object.isObject({}); // => true Object.isObject(isNaN); // => true Object.isObject(null); // => false var classof = Object.classof; classof(null); // => 'Null' classof(undefined); // => 'Undefined' classof(1); // => 'Number' classof(true); // => 'Boolean' classof('string'); // => 'String' classof(Symbol()); // => 'Symbol' classof(new Number(1)); // => 'Number' classof(new Boolean(true)); // => 'Boolean' classof(new String('string')); // => 'String' var fn = function(){} , list = (function(){return arguments})(1, 2, 3); classof({}); // => 'Object' classof(fn); // => 'Function' classof([]); // => 'Array' classof(list); // => 'Arguments' classof(/./); // => 'RegExp' classof(new TypeError); // => 'Error' classof(new Set); // => 'Set' classof(new Map); // => 'Map' classof(new WeakSet); // => 'WeakSet' classof(new WeakMap); // => 'WeakMap' classof(new Promise(fn)); // => 'Promise' classof([].values()); // => 'Array Iterator' classof(new Set().values()); // => 'Set Iterator' classof(new Map().values()); // => 'Map Iterator' classof(Math); // => 'Math' classof(JSON); // => 'JSON' function Example(){} Example.prototype[Symbol.toStringTag] = 'Example'; classof(new Example); // => 'Example' ``` `Object.define` and `Object.make` [*examples*](http://goo.gl/rtpD5Z): ```js // Before: Object.defineProperty(target, 'c', { enumerable: true, configurable: true, get: function(){ return this.a + this.b; } }); // After: Object.define(target, { get c(){ return this.a + this.b; } }); // Shallow object cloning with prototype and descriptors: var copy = Object.make(Object.getPrototypeOf(src), src); // Simple inheritance: function Vector2D(x, y){ this.x = x; this.y = y; } Object.define(Vector2D.prototype, { get xy(){ return Math.hypot(this.x, this.y); } }); function Vector3D(x, y, z){ Vector2D.apply(this, arguments); this.z = z; } Vector3D.prototype = Object.make(Vector2D.prototype, { constructor: Vector3D, get xyz(){ return Math.hypot(this.x, this.y, this.z); } }); var vector = new Vector3D(9, 12, 20); console.log(vector.xy); // => 15 console.log(vector.xyz); // => 25 vector.y++; console.log(vector.xy); // => 15.811388300841896 console.log(vector.xyz); // => 25.495097567963924 ``` #### Dict Module [`core.dict`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/core.dict.js). Based on [TC39 discuss](https://github.com/rwaldron/tc39-notes/blob/master/es6/2012-11/nov-29.md#collection-apis-review) / [strawman](http://wiki.ecmascript.org/doku.php?id=harmony:modules_standard#dictionaries). ```js [new] Dict(iterable (entries) | object ?) -> dict .isDict(var) -> bool .values(object) -> iterator .keys(object) -> iterator .entries(object) -> iterator (entries) .has(object, key) -> bool .get(object, key) -> val .set(object, key, value) -> object .forEach(object, fn(val, key, @), that) -> void .map(object, fn(val, key, @), that) -> new @ .mapPairs(object, fn(val, key, @), that) -> new @ .filter(object, fn(val, key, @), that) -> new @ .some(object, fn(val, key, @), that) -> bool .every(object, fn(val, key, @), that) -> bool .find(object, fn(val, key, @), that) -> val .findKey(object, fn(val, key, @), that) -> key .keyOf(object, var) -> key .includes(object, var) -> bool .reduce(object, fn(memo, val, key, @), memo?) -> var ``` [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/core/dict core-js(/library)/fn/dict ``` `Dict` create object without prototype from iterable or simple object. [*Examples*](http://goo.gl/pnp8Vr): ```js var map = new Map([['a', 1], ['b', 2], ['c', 3]]); Dict(); // => {__proto__: null} Dict({a: 1, b: 2, c: 3}); // => {__proto__: null, a: 1, b: 2, c: 3} Dict(map); // => {__proto__: null, a: 1, b: 2, c: 3} Dict([1, 2, 3].entries()); // => {__proto__: null, 0: 1, 1: 2, 2: 3} var dict = Dict({a: 42}); dict instanceof Object; // => false dict.a; // => 42 dict.toString; // => undefined 'a' in dict; // => true 'hasOwnProperty' in dict; // => false Dict.isDict({}); // => false Dict.isDict(Dict()); // => true ``` `Dict.keys`, `Dict.values` and `Dict.entries` returns iterators for objects. [*Examples*](http://goo.gl/xAvECH): ```js var dict = {a: 1, b: 2, c: 3}; for(var key of Dict.keys(dict))console.log(key); // => 'a', 'b', 'c' for(var val of Dict.values(dict))console.log(val); // => 1, 2, 3 for(var [key, val] of Dict.entries(dict)){ console.log(key); // => 'a', 'b', 'c' console.log(val); // => 1, 2, 3 } new Map(Dict.entries(dict)); // => Map {a: 1, b: 2, c: 3} ``` Basic dict operations for objects with prototype [*examples*](http://goo.gl/B28UnG): ```js 'q' in {q: 1}; // => true 'toString' in {}; // => true Dict.has({q: 1}, 'q'); // => true Dict.has({}, 'toString'); // => false ({q: 1})['q']; // => 1 ({}).toString; // => function toString(){ [native code] } Dict.get({q: 1}, 'q'); // => 1 Dict.get({}, 'toString'); // => undefined var O = {}; O['q'] = 1; O['q']; // => 1 O['__proto__'] = {w: 2}; O['__proto__']; // => {w: 2} O['w']; // => 2 var O = {}; Dict.set(O, 'q', 1); O['q']; // => 1 Dict.set(O, '__proto__', {w: 2}); O['__proto__']; // => {w: 2} O['w']; // => undefined ``` Other methods of `Dict` module are static equivalents of `Array.prototype` methods for dictionaries. [*Examples*](http://goo.gl/xFi1RH): ```js var dict = {a: 1, b: 2, c: 3}; Dict.forEach(dict, console.log, console); // => 1, 'a', {a: 1, b: 2, c: 3} // => 2, 'b', {a: 1, b: 2, c: 3} // => 3, 'c', {a: 1, b: 2, c: 3} Dict.map(dict, function(it){ return it * it; }); // => {a: 1, b: 4, c: 9} Dict.mapPairs(dict, function(val, key){ if(key != 'b')return [key + key, val * val]; }); // => {aa: 1, cc: 9} Dict.filter(dict, function(it){ return it % 2; }); // => {a: 1, c: 3} Dict.some(dict, function(it){ return it === 2; }); // => true Dict.every(dict, function(it){ return it === 2; }); // => false Dict.find(dict, function(it){ return it > 2; }); // => 3 Dict.find(dict, function(it){ return it > 4; }); // => undefined Dict.findKey(dict, function(it){ return it > 2; }); // => 'c' Dict.findKey(dict, function(it){ return it > 4; }); // => undefined Dict.keyOf(dict, 2); // => 'b' Dict.keyOf(dict, 4); // => undefined Dict.includes(dict, 2); // => true Dict.includes(dict, 4); // => false Dict.reduce(dict, function(memo, it){ return memo + it; }); // => 6 Dict.reduce(dict, function(memo, it){ return memo + it; }, ''); // => '123' ``` #### Partial application Module [`core.function.part`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/core.function.part.js). ```js Function #part(...args | _) -> fn(...args) ``` [*CommonJS entry points:*](#commonjs) ```js core-js/core/function core-js(/library)/fn/function/part core-js(/library)/fn/function/virtual/part core-js(/library)/fn/_ ``` `Function#part` partial apply function without `this` binding. Uses global variable `_` (`core._` for builds without global namespace pollution) as placeholder and not conflict with `Underscore` / `LoDash`. [*Examples*](http://goo.gl/p9ZJ8K): ```js var fn1 = log.part(1, 2); fn1(3, 4); // => 1, 2, 3, 4 var fn2 = log.part(_, 2, _, 4); fn2(1, 3); // => 1, 2, 3, 4 var fn3 = log.part(1, _, _, 4); fn3(2, 3); // => 1, 2, 3, 4 fn2(1, 3, 5); // => 1, 2, 3, 4, 5 fn2(1); // => 1, 2, undefined, 4 ``` #### Number Iterator Module [`core.number.iterator`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/core.number.iterator.js). ```js Number #@@iterator() -> iterator ``` [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/core/number core-js(/library)/fn/number/iterator core-js(/library)/fn/number/virtual/iterator ``` [*Examples*](http://goo.gl/o45pCN): ```js for(var i of 3)console.log(i); // => 0, 1, 2 [...10]; // => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Array.from(10, Math.random); // => [0.9817775336559862, 0.02720663254149258, ...] Array.from(10, function(it){ return this + it * it; }, .42); // => [0.42, 1.42, 4.42, 9.42, 16.42, 25.42, 36.42, 49.42, 64.42, 81.42] ``` #### Escaping strings Modules [`core.regexp.escape`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/core.regexp.escape.js), [`core.string.escape-html`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/core.string.escape-html.js) and [`core.string.unescape-html`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/core.string.unescape-html.js). ```js RegExp .escape(str) -> str String #escapeHTML() -> str #unescapeHTML() -> str ``` [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/core/regexp core-js(/library)/core/string core-js(/library)/fn/regexp/escape core-js(/library)/fn/string/escape-html core-js(/library)/fn/string/unescape-html core-js(/library)/fn/string/virtual/escape-html core-js(/library)/fn/string/virtual/unescape-html ``` [*Examples*](http://goo.gl/6bOvsQ): ```js RegExp.escape('Hello, []{}()*+?.\\^$|!'); // => 'Hello, \[\]\{\}\(\)\*\+\?\.\\\^\$\|!' '<script>doSomething();</script>'.escapeHTML(); // => '&lt;script&gt;doSomething();&lt;/script&gt;' '&lt;script&gt;doSomething();&lt;/script&gt;'.unescapeHTML(); // => '<script>doSomething();</script>' ``` #### delay Module [`core.delay`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/core.delay.js). [Promise](#ecmascript-6-promise)-returning delay function, [esdiscuss](https://esdiscuss.org/topic/promise-returning-delay-function). ```js delay(ms) -> promise ``` [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/core/delay core-js(/library)/fn/delay ``` [*Examples*](http://goo.gl/lbucba): ```js delay(1e3).then(() => console.log('after 1 sec')); (async () => { await delay(3e3); console.log('after 3 sec'); while(await delay(3e3))console.log('each 3 sec'); })(); ``` #### Helpers for iterators Modules [`core.is-iterable`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/core.is-iterable.js), [`core.get-iterator`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/core.get-iterator.js), [`core.get-iterator-method`](https://github.com/zloirock/core-js/blob/v2.6.11/modules/core.get-iterator-method.js) - helpers for check iterability / get iterator in the `library` version or, for example, for `arguments` object: ```js core .isIterable(var) -> bool .getIterator(iterable) -> iterator .getIteratorMethod(var) -> function | undefined ``` [*CommonJS entry points:*](#commonjs) ```js core-js(/library)/fn/is-iterable core-js(/library)/fn/get-iterator core-js(/library)/fn/get-iterator-method ``` [*Examples*](http://goo.gl/SXsM6D): ```js var list = (function(){ return arguments; })(1, 2, 3); console.log(core.isIterable(list)); // true; var iter = core.getIterator(list); console.log(iter.next().value); // 1 console.log(iter.next().value); // 2 console.log(iter.next().value); // 3 console.log(iter.next().value); // undefined core.getIterator({}); // TypeError: [object Object] is not iterable! var iterFn = core.getIteratorMethod(list); console.log(typeof iterFn); // 'function' var iter = iterFn.call(list); console.log(iter.next().value); // 1 console.log(iter.next().value); // 2 console.log(iter.next().value); // 3 console.log(iter.next().value); // undefined console.log(core.getIteratorMethod({})); // undefined ``` ## Missing polyfills - ES5 `JSON` is missing now only in IE7- and never will it be added to `core-js`, if you need it in these old browsers, many implementations are available, for example, [json3](https://github.com/bestiejs/json3). - ES6 `String#normalize` is not a very useful feature, but this polyfill will be very large. If you need it, you can use [unorm](https://github.com/walling/unorm/). - ES6 `Proxy` can't be polyfilled, but for Node.js / Chromium with additional flags you can try [harmony-reflect](https://github.com/tvcutsem/harmony-reflect) for adapt old style `Proxy` API to final ES6 version. - ES6 logic for `@@isConcatSpreadable` and `@@species` (in most places) can be polyfilled without problems, but it will cause a serious slowdown in popular cases in some engines. It will be polyfilled when it will be implemented in modern engines. - ES7 `SIMD`. `core-js` doesn't add polyfill of this feature because of large size and some other reasons. You can use [this polyfill](https://github.com/tc39/ecmascript_simd/blob/master/src/ecmascript_simd.js). - `window.fetch` is not a cross-platform feature, in some environments it makes no sense. For this reason, I don't think it should be in `core-js`. Looking at a large number of requests it *may be* added in the future. Now you can use, for example, [this polyfill](https://github.com/github/fetch). - ECMA-402 `Intl` is missed because of size. You can use [this polyfill](https://github.com/andyearnshaw/Intl.js/). #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/inspect-js/is-symbol.svg [3]: https://travis-ci.org/inspect-js/is-symbol.svg [4]: https://travis-ci.org/inspect-js/is-symbol [5]: https://david-dm.org/inspect-js/is-symbol.svg [6]: https://david-dm.org/inspect-js/is-symbol [7]: https://david-dm.org/inspect-js/is-symbol/dev-status.svg [8]: https://david-dm.org/inspect-js/is-symbol#info=devDependencies [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 # 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. 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 # color [![Build Status](https://travis-ci.org/Qix-/color.svg?branch=master)](https://travis-ci.org/Qix-/color) > JavaScript library for immutable color conversion and manipulation with support for CSS color strings. ```js var color = Color('#7743CE').alpha(0.5).lighten(0.5); console.log(color.hsl().string()); // 'hsla(262, 59%, 81%, 0.5)' console.log(color.cmyk().round().array()); // [ 16, 25, 0, 8, 0.5 ] console.log(color.ansi256().object()); // { ansi256: 183, alpha: 0.5 } ``` ## Install ```console $ npm install color ``` ## Usage ```js var Color = require('color'); ``` ### Constructors ```js var color = Color('rgb(255, 255, 255)') var color = Color({r: 255, g: 255, b: 255}) var color = Color.rgb(255, 255, 255) var color = Color.rgb([255, 255, 255]) ``` Set the values for individual channels with `alpha`, `red`, `green`, `blue`, `hue`, `saturationl` (hsl), `saturationv` (hsv), `lightness`, `whiteness`, `blackness`, `cyan`, `magenta`, `yellow`, `black` String constructors are handled by [color-string](https://www.npmjs.com/package/color-string) ### Getters ```js color.hsl(); ``` Convert a color to a different space (`hsl()`, `cmyk()`, etc.). ```js color.object(); // {r: 255, g: 255, b: 255} ``` Get a hash of the color value. Reflects the color's current model (see above). ```js color.rgb().array() // [255, 255, 255] ``` Get an array of the values with `array()`. Reflects the color's current model (see above). ```js color.rgbNumber() // 16777215 (0xffffff) ``` Get the rgb number value. ```js color.hex() // 0xffffff ``` Get the hex value. ```js color.red() // 255 ``` Get the value for an individual channel. ### CSS Strings ```js color.hsl().string() // 'hsl(320, 50%, 100%)' ``` Calling `.string()` with a number rounds the numbers to that decimal place. It defaults to 1. ### Luminosity ```js color.luminosity(); // 0.412 ``` The [WCAG luminosity](http://www.w3.org/TR/WCAG20/#relativeluminancedef) of the color. 0 is black, 1 is white. ```js color.contrast(Color("blue")) // 12 ``` The [WCAG contrast ratio](http://www.w3.org/TR/WCAG20/#contrast-ratiodef) to another color, from 1 (same color) to 21 (contrast b/w white and black). ```js color.isLight(); // true color.isDark(); // false ``` Get whether the color is "light" or "dark", useful for deciding text color. ### Manipulation ```js color.negate() // rgb(0, 100, 255) -> rgb(255, 155, 0) color.lighten(0.5) // hsl(100, 50%, 50%) -> hsl(100, 50%, 75%) color.darken(0.5) // hsl(100, 50%, 50%) -> hsl(100, 50%, 25%) color.saturate(0.5) // hsl(100, 50%, 50%) -> hsl(100, 75%, 50%) color.desaturate(0.5) // hsl(100, 50%, 50%) -> hsl(100, 25%, 50%) color.grayscale() // #5CBF54 -> #969696 color.whiten(0.5) // hwb(100, 50%, 50%) -> hwb(100, 75%, 50%) color.blacken(0.5) // hwb(100, 50%, 50%) -> hwb(100, 50%, 75%) color.fade(0.5) // rgba(10, 10, 10, 0.8) -> rgba(10, 10, 10, 0.4) color.opaquer(0.5) // rgba(10, 10, 10, 0.8) -> rgba(10, 10, 10, 1.0) color.rotate(180) // hsl(60, 20%, 20%) -> hsl(240, 20%, 20%) color.rotate(-90) // hsl(60, 20%, 20%) -> hsl(330, 20%, 20%) color.mix(Color("yellow")) // cyan -> rgb(128, 255, 128) color.mix(Color("yellow"), 0.3) // cyan -> rgb(77, 255, 179) // chaining color.green(100).grayscale().lighten(0.6) ``` ## Propers The API was inspired by [color-js](https://github.com/brehaut/color-js). Manipulation functions by CSS tools like Sass, LESS, and Stylus. # 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 9. **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-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 # 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. # 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) # 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>. ## 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 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 `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value components are invalid (`9999999999999999.4.7.4` is likely invalid). # 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._ # 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). # 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._ # 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) String.prototype.trimStart <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 ES2019-spec-compliant `String.prototype.trimStart` shim. Invoke its "shim" method to shim `String.prototype.trimStart` if it is unavailable. 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](http://www.ecma-international.org/ecma-262/6.0/#sec-object.assign). In an ES6 environment, it will also work properly with `Symbol`s. Most common usage: ```js var trimStart = require('string.prototype.trimstart'); assert(trimStart(' \t\na \t\n') === 'a \t\n'); if (!String.prototype.trimStart) { trimStart.shim(); } assert(trimStart(' \t\na \t\n') === ' \t\na \t\n'.trimStart()); ``` ## Tests Simply clone the repo, `npm install`, and run `npm test` [package-url]: https://npmjs.com/package/string.prototype.trimstart [npm-version-svg]: http://vb.teelaun.ch/es-shims/String.prototype.trimStart.svg [travis-svg]: https://travis-ci.org/es-shims/String.prototype.trimStart.svg [travis-url]: https://travis-ci.org/es-shims/String.prototype.trimStart [deps-svg]: https://david-dm.org/es-shims/String.prototype.trimStart.svg [deps-url]: https://david-dm.org/es-shims/String.prototype.trimStart [dev-deps-svg]: https://david-dm.org/es-shims/String.prototype.trimStart/dev-status.svg [dev-deps-url]: https://david-dm.org/es-shims/String.prototype.trimStart#info=devDependencies [testling-svg]: https://ci.testling.com/es-shims/String.prototype.trimStart.png [testling-url]: https://ci.testling.com/es-shims/String.prototype.trimStart [npm-badge-png]: https://nodei.co/npm/string.prototype.trimstart.png?downloads=true&stars=true [license-image]: http://img.shields.io/npm/l/string.prototype.trimstart.svg [license-url]: LICENSE [downloads-image]: http://img.shields.io/npm/dm/string.prototype.trimstart.svg [downloads-url]: http://npm-stat.com/charts.html?package=string.prototype.trimstart # babel-types > This module contains methods for building ASTs manually and for checking the types of AST nodes. ## Install ```sh npm install --save-dev babel-types ``` ## API <!-- begin generated section --> ### anyTypeAnnotation ```javascript t.anyTypeAnnotation() ``` See also `t.isAnyTypeAnnotation(node, opts)` and `t.assertAnyTypeAnnotation(node, opts)`. Aliases: `Flow`, `FlowBaseAnnotation` --- ### arrayExpression ```javascript t.arrayExpression(elements) ``` See also `t.isArrayExpression(node, opts)` and `t.assertArrayExpression(node, opts)`. Aliases: `Expression` - `elements`: `Array<null | Expression | SpreadElement>` (default: `[]`) --- ### arrayPattern ```javascript t.arrayPattern(elements, typeAnnotation) ``` See also `t.isArrayPattern(node, opts)` and `t.assertArrayPattern(node, opts)`. Aliases: `Pattern`, `LVal` - `elements`: `Array<Identifier | Pattern | RestElement>` (required) - `typeAnnotation` (required) - `decorators`: `Array<Decorator>` (default: `null`) --- ### arrayTypeAnnotation ```javascript t.arrayTypeAnnotation(elementType) ``` See also `t.isArrayTypeAnnotation(node, opts)` and `t.assertArrayTypeAnnotation(node, opts)`. Aliases: `Flow` - `elementType` (required) --- ### arrowFunctionExpression ```javascript t.arrowFunctionExpression(params, body, async) ``` See also `t.isArrowFunctionExpression(node, opts)` and `t.assertArrowFunctionExpression(node, opts)`. Aliases: `Scopable`, `Function`, `BlockParent`, `FunctionParent`, `Expression`, `Pureish` - `params`: `Array<LVal>` (required) - `body`: `BlockStatement | Expression` (required) - `async`: `boolean` (default: `false`) - `returnType` (default: `null`) - `typeParameters` (default: `null`) --- ### assignmentExpression ```javascript t.assignmentExpression(operator, left, right) ``` See also `t.isAssignmentExpression(node, opts)` and `t.assertAssignmentExpression(node, opts)`. Aliases: `Expression` - `operator`: `string` (required) - `left`: `LVal` (required) - `right`: `Expression` (required) --- ### assignmentPattern ```javascript t.assignmentPattern(left, right) ``` See also `t.isAssignmentPattern(node, opts)` and `t.assertAssignmentPattern(node, opts)`. Aliases: `Pattern`, `LVal` - `left`: `Identifier` (required) - `right`: `Expression` (required) - `decorators`: `Array<Decorator>` (default: `null`) --- ### awaitExpression ```javascript t.awaitExpression(argument) ``` See also `t.isAwaitExpression(node, opts)` and `t.assertAwaitExpression(node, opts)`. Aliases: `Expression`, `Terminatorless` - `argument`: `Expression` (required) --- ### binaryExpression ```javascript t.binaryExpression(operator, left, right) ``` See also `t.isBinaryExpression(node, opts)` and `t.assertBinaryExpression(node, opts)`. Aliases: `Binary`, `Expression` - `operator`: `'+' | '-' | '/' | '%' | '*' | '**' | '&' | '|' | '>>' | '>>>' | '<<' | '^' | '==' | '===' | '!=' | '!==' | 'in' | 'instanceof' | '>' | '<' | '>=' | '<='` (required) - `left`: `Expression` (required) - `right`: `Expression` (required) --- ### bindExpression ```javascript t.bindExpression(object, callee) ``` See also `t.isBindExpression(node, opts)` and `t.assertBindExpression(node, opts)`. Aliases: `Expression` - `object` (required) - `callee` (required) --- ### blockStatement ```javascript t.blockStatement(body, directives) ``` See also `t.isBlockStatement(node, opts)` and `t.assertBlockStatement(node, opts)`. Aliases: `Scopable`, `BlockParent`, `Block`, `Statement` - `body`: `Array<Statement>` (required) - `directives`: `Array<Directive>` (default: `[]`) --- ### booleanLiteral ```javascript t.booleanLiteral(value) ``` See also `t.isBooleanLiteral(node, opts)` and `t.assertBooleanLiteral(node, opts)`. Aliases: `Expression`, `Pureish`, `Literal`, `Immutable` - `value`: `boolean` (required) --- ### booleanLiteralTypeAnnotation ```javascript t.booleanLiteralTypeAnnotation() ``` See also `t.isBooleanLiteralTypeAnnotation(node, opts)` and `t.assertBooleanLiteralTypeAnnotation(node, opts)`. Aliases: `Flow` --- ### booleanTypeAnnotation ```javascript t.booleanTypeAnnotation() ``` See also `t.isBooleanTypeAnnotation(node, opts)` and `t.assertBooleanTypeAnnotation(node, opts)`. Aliases: `Flow`, `FlowBaseAnnotation` --- ### breakStatement ```javascript t.breakStatement(label) ``` See also `t.isBreakStatement(node, opts)` and `t.assertBreakStatement(node, opts)`. Aliases: `Statement`, `Terminatorless`, `CompletionStatement` - `label`: `Identifier` (default: `null`) --- ### callExpression ```javascript t.callExpression(callee, arguments) ``` See also `t.isCallExpression(node, opts)` and `t.assertCallExpression(node, opts)`. Aliases: `Expression` - `callee`: `Expression` (required) - `arguments`: `Array<Expression | SpreadElement>` (required) --- ### catchClause ```javascript t.catchClause(param, body) ``` See also `t.isCatchClause(node, opts)` and `t.assertCatchClause(node, opts)`. Aliases: `Scopable` - `param`: `Identifier` (required) - `body`: `BlockStatement` (required) --- ### classBody ```javascript t.classBody(body) ``` See also `t.isClassBody(node, opts)` and `t.assertClassBody(node, opts)`. - `body`: `Array<ClassMethod | ClassProperty>` (required) --- ### classDeclaration ```javascript t.classDeclaration(id, superClass, body, decorators) ``` See also `t.isClassDeclaration(node, opts)` and `t.assertClassDeclaration(node, opts)`. Aliases: `Scopable`, `Class`, `Statement`, `Declaration`, `Pureish` - `id`: `Identifier` (required) - `superClass`: `Expression` (default: `null`) - `body`: `ClassBody` (required) - `decorators`: `Array<Decorator>` (required) - `implements` (default: `null`) - `mixins` (default: `null`) - `superTypeParameters` (default: `null`) - `typeParameters` (default: `null`) --- ### classExpression ```javascript t.classExpression(id, superClass, body, decorators) ``` See also `t.isClassExpression(node, opts)` and `t.assertClassExpression(node, opts)`. Aliases: `Scopable`, `Class`, `Expression`, `Pureish` - `id`: `Identifier` (default: `null`) - `superClass`: `Expression` (default: `null`) - `body`: `ClassBody` (required) - `decorators`: `Array<Decorator>` (required) - `implements` (default: `null`) - `mixins` (default: `null`) - `superTypeParameters` (default: `null`) - `typeParameters` (default: `null`) --- ### classImplements ```javascript t.classImplements(id, typeParameters) ``` See also `t.isClassImplements(node, opts)` and `t.assertClassImplements(node, opts)`. Aliases: `Flow` - `id` (required) - `typeParameters` (required) --- ### classMethod ```javascript t.classMethod(kind, key, params, body, computed, static) ``` See also `t.isClassMethod(node, opts)` and `t.assertClassMethod(node, opts)`. Aliases: `Function`, `Scopable`, `BlockParent`, `FunctionParent`, `Method` - `kind`: `"get" | "set" | "method" | "constructor"` (default: `'method'`) - `key`if computed then `Expression` else `Identifier | Literal` (required) - `params`: `Array<LVal>` (required) - `body`: `BlockStatement` (required) - `computed`: `boolean` (default: `false`) - `static`: `boolean` (default: `false`) - `async`: `boolean` (default: `false`) - `decorators` (default: `null`) - `generator`: `boolean` (default: `false`) - `returnType` (default: `null`) - `typeParameters` (default: `null`) --- ### classProperty ```javascript t.classProperty(key, value, typeAnnotation, decorators, computed) ``` See also `t.isClassProperty(node, opts)` and `t.assertClassProperty(node, opts)`. Aliases: `Property` - `key` (required) - `value` (required) - `typeAnnotation` (required) - `decorators` (required) - `computed`: `boolean` (default: `false`) --- ### conditionalExpression ```javascript t.conditionalExpression(test, consequent, alternate) ``` See also `t.isConditionalExpression(node, opts)` and `t.assertConditionalExpression(node, opts)`. Aliases: `Expression`, `Conditional` - `test`: `Expression` (required) - `consequent`: `Expression` (required) - `alternate`: `Expression` (required) --- ### continueStatement ```javascript t.continueStatement(label) ``` See also `t.isContinueStatement(node, opts)` and `t.assertContinueStatement(node, opts)`. Aliases: `Statement`, `Terminatorless`, `CompletionStatement` - `label`: `Identifier` (default: `null`) --- ### debuggerStatement ```javascript t.debuggerStatement() ``` See also `t.isDebuggerStatement(node, opts)` and `t.assertDebuggerStatement(node, opts)`. Aliases: `Statement` --- ### declareClass ```javascript t.declareClass(id, typeParameters, extends, body) ``` See also `t.isDeclareClass(node, opts)` and `t.assertDeclareClass(node, opts)`. Aliases: `Flow`, `FlowDeclaration`, `Statement`, `Declaration` - `id` (required) - `typeParameters` (required) - `extends` (required) - `body` (required) --- ### declareExportDeclaration ```javascript t.declareExportDeclaration(declaration, specifiers, source) ``` See also `t.isDeclareExportDeclaration(node, opts)` and `t.assertDeclareExportDeclaration(node, opts)`. Aliases: `Flow`, `FlowDeclaration`, `Statement`, `Declaration` - `declaration` (required) - `specifiers` (required) - `source` (required) --- ### declareFunction ```javascript t.declareFunction(id) ``` See also `t.isDeclareFunction(node, opts)` and `t.assertDeclareFunction(node, opts)`. Aliases: `Flow`, `FlowDeclaration`, `Statement`, `Declaration` - `id` (required) --- ### declareInterface ```javascript t.declareInterface(id, typeParameters, extends, body) ``` See also `t.isDeclareInterface(node, opts)` and `t.assertDeclareInterface(node, opts)`. Aliases: `Flow`, `FlowDeclaration`, `Statement`, `Declaration` - `id` (required) - `typeParameters` (required) - `extends` (required) - `body` (required) --- ### declareModule ```javascript t.declareModule(id, body) ``` See also `t.isDeclareModule(node, opts)` and `t.assertDeclareModule(node, opts)`. Aliases: `Flow`, `FlowDeclaration`, `Statement`, `Declaration` - `id` (required) - `body` (required) --- ### declareModuleExports ```javascript t.declareModuleExports(typeAnnotation) ``` See also `t.isDeclareModuleExports(node, opts)` and `t.assertDeclareModuleExports(node, opts)`. Aliases: `Flow`, `FlowDeclaration`, `Statement`, `Declaration` - `typeAnnotation` (required) --- ### declareOpaqueType ```javascript t.declareOpaqueType(id, typeParameters, supertype) ``` See also `t.isDeclareOpaqueType(node, opts)` and `t.assertDeclareOpaqueType(node, opts)`. Aliases: `Flow`, `FlowDeclaration`, `Statement`, `Declaration` - `id` (required) - `typeParameters` (required) - `supertype` (required) --- ### declareTypeAlias ```javascript t.declareTypeAlias(id, typeParameters, right) ``` See also `t.isDeclareTypeAlias(node, opts)` and `t.assertDeclareTypeAlias(node, opts)`. Aliases: `Flow`, `FlowDeclaration`, `Statement`, `Declaration` - `id` (required) - `typeParameters` (required) - `right` (required) --- ### declareVariable ```javascript t.declareVariable(id) ``` See also `t.isDeclareVariable(node, opts)` and `t.assertDeclareVariable(node, opts)`. Aliases: `Flow`, `FlowDeclaration`, `Statement`, `Declaration` - `id` (required) --- ### decorator ```javascript t.decorator(expression) ``` See also `t.isDecorator(node, opts)` and `t.assertDecorator(node, opts)`. - `expression`: `Expression` (required) --- ### directive ```javascript t.directive(value) ``` See also `t.isDirective(node, opts)` and `t.assertDirective(node, opts)`. - `value`: `DirectiveLiteral` (required) --- ### directiveLiteral ```javascript t.directiveLiteral(value) ``` See also `t.isDirectiveLiteral(node, opts)` and `t.assertDirectiveLiteral(node, opts)`. - `value`: `string` (required) --- ### doExpression ```javascript t.doExpression(body) ``` See also `t.isDoExpression(node, opts)` and `t.assertDoExpression(node, opts)`. Aliases: `Expression` - `body`: `BlockStatement` (required) --- ### doWhileStatement ```javascript t.doWhileStatement(test, body) ``` See also `t.isDoWhileStatement(node, opts)` and `t.assertDoWhileStatement(node, opts)`. Aliases: `Statement`, `BlockParent`, `Loop`, `While`, `Scopable` - `test`: `Expression` (required) - `body`: `Statement` (required) --- ### emptyStatement ```javascript t.emptyStatement() ``` See also `t.isEmptyStatement(node, opts)` and `t.assertEmptyStatement(node, opts)`. Aliases: `Statement` --- ### emptyTypeAnnotation ```javascript t.emptyTypeAnnotation() ``` See also `t.isEmptyTypeAnnotation(node, opts)` and `t.assertEmptyTypeAnnotation(node, opts)`. Aliases: `Flow`, `FlowBaseAnnotation` --- ### existentialTypeParam ```javascript t.existentialTypeParam() ``` See also `t.isExistentialTypeParam(node, opts)` and `t.assertExistentialTypeParam(node, opts)`. Aliases: `Flow` --- ### exportAllDeclaration ```javascript t.exportAllDeclaration(source) ``` See also `t.isExportAllDeclaration(node, opts)` and `t.assertExportAllDeclaration(node, opts)`. Aliases: `Statement`, `Declaration`, `ModuleDeclaration`, `ExportDeclaration` - `source`: `StringLiteral` (required) --- ### exportDefaultDeclaration ```javascript t.exportDefaultDeclaration(declaration) ``` See also `t.isExportDefaultDeclaration(node, opts)` and `t.assertExportDefaultDeclaration(node, opts)`. Aliases: `Statement`, `Declaration`, `ModuleDeclaration`, `ExportDeclaration` - `declaration`: `FunctionDeclaration | ClassDeclaration | Expression` (required) --- ### exportDefaultSpecifier ```javascript t.exportDefaultSpecifier(exported) ``` See also `t.isExportDefaultSpecifier(node, opts)` and `t.assertExportDefaultSpecifier(node, opts)`. Aliases: `ModuleSpecifier` - `exported`: `Identifier` (required) --- ### exportNamedDeclaration ```javascript t.exportNamedDeclaration(declaration, specifiers, source) ``` See also `t.isExportNamedDeclaration(node, opts)` and `t.assertExportNamedDeclaration(node, opts)`. Aliases: `Statement`, `Declaration`, `ModuleDeclaration`, `ExportDeclaration` - `declaration`: `Declaration` (default: `null`) - `specifiers`: `Array<ExportSpecifier>` (required) - `source`: `StringLiteral` (default: `null`) --- ### exportNamespaceSpecifier ```javascript t.exportNamespaceSpecifier(exported) ``` See also `t.isExportNamespaceSpecifier(node, opts)` and `t.assertExportNamespaceSpecifier(node, opts)`. Aliases: `ModuleSpecifier` - `exported`: `Identifier` (required) --- ### exportSpecifier ```javascript t.exportSpecifier(local, exported) ``` See also `t.isExportSpecifier(node, opts)` and `t.assertExportSpecifier(node, opts)`. Aliases: `ModuleSpecifier` - `local`: `Identifier` (required) - `exported`: `Identifier` (required) --- ### expressionStatement ```javascript t.expressionStatement(expression) ``` See also `t.isExpressionStatement(node, opts)` and `t.assertExpressionStatement(node, opts)`. Aliases: `Statement`, `ExpressionWrapper` - `expression`: `Expression` (required) --- ### file ```javascript t.file(program, comments, tokens) ``` See also `t.isFile(node, opts)` and `t.assertFile(node, opts)`. - `program`: `Program` (required) - `comments` (required) - `tokens` (required) --- ### forAwaitStatement ```javascript t.forAwaitStatement(left, right, body) ``` See also `t.isForAwaitStatement(node, opts)` and `t.assertForAwaitStatement(node, opts)`. Aliases: `Scopable`, `Statement`, `For`, `BlockParent`, `Loop`, `ForXStatement` - `left`: `VariableDeclaration | LVal` (required) - `right`: `Expression` (required) - `body`: `Statement` (required) --- ### forInStatement ```javascript t.forInStatement(left, right, body) ``` See also `t.isForInStatement(node, opts)` and `t.assertForInStatement(node, opts)`. Aliases: `Scopable`, `Statement`, `For`, `BlockParent`, `Loop`, `ForXStatement` - `left`: `VariableDeclaration | LVal` (required) - `right`: `Expression` (required) - `body`: `Statement` (required) --- ### forOfStatement ```javascript t.forOfStatement(left, right, body) ``` See also `t.isForOfStatement(node, opts)` and `t.assertForOfStatement(node, opts)`. Aliases: `Scopable`, `Statement`, `For`, `BlockParent`, `Loop`, `ForXStatement` - `left`: `VariableDeclaration | LVal` (required) - `right`: `Expression` (required) - `body`: `Statement` (required) --- ### forStatement ```javascript t.forStatement(init, test, update, body) ``` See also `t.isForStatement(node, opts)` and `t.assertForStatement(node, opts)`. Aliases: `Scopable`, `Statement`, `For`, `BlockParent`, `Loop` - `init`: `VariableDeclaration | Expression` (default: `null`) - `test`: `Expression` (default: `null`) - `update`: `Expression` (default: `null`) - `body`: `Statement` (required) --- ### functionDeclaration ```javascript t.functionDeclaration(id, params, body, generator, async) ``` See also `t.isFunctionDeclaration(node, opts)` and `t.assertFunctionDeclaration(node, opts)`. Aliases: `Scopable`, `Function`, `BlockParent`, `FunctionParent`, `Statement`, `Pureish`, `Declaration` - `id`: `Identifier` (required) - `params`: `Array<LVal>` (required) - `body`: `BlockStatement` (required) - `generator`: `boolean` (default: `false`) - `async`: `boolean` (default: `false`) - `returnType` (default: `null`) - `typeParameters` (default: `null`) --- ### functionExpression ```javascript t.functionExpression(id, params, body, generator, async) ``` See also `t.isFunctionExpression(node, opts)` and `t.assertFunctionExpression(node, opts)`. Aliases: `Scopable`, `Function`, `BlockParent`, `FunctionParent`, `Expression`, `Pureish` - `id`: `Identifier` (default: `null`) - `params`: `Array<LVal>` (required) - `body`: `BlockStatement` (required) - `generator`: `boolean` (default: `false`) - `async`: `boolean` (default: `false`) - `returnType` (default: `null`) - `typeParameters` (default: `null`) --- ### functionTypeAnnotation ```javascript t.functionTypeAnnotation(typeParameters, params, rest, returnType) ``` See also `t.isFunctionTypeAnnotation(node, opts)` and `t.assertFunctionTypeAnnotation(node, opts)`. Aliases: `Flow` - `typeParameters` (required) - `params` (required) - `rest` (required) - `returnType` (required) --- ### functionTypeParam ```javascript t.functionTypeParam(name, typeAnnotation) ``` See also `t.isFunctionTypeParam(node, opts)` and `t.assertFunctionTypeParam(node, opts)`. Aliases: `Flow` - `name` (required) - `typeAnnotation` (required) --- ### genericTypeAnnotation ```javascript t.genericTypeAnnotation(id, typeParameters) ``` See also `t.isGenericTypeAnnotation(node, opts)` and `t.assertGenericTypeAnnotation(node, opts)`. Aliases: `Flow` - `id` (required) - `typeParameters` (required) --- ### identifier ```javascript t.identifier(name) ``` See also `t.isIdentifier(node, opts)` and `t.assertIdentifier(node, opts)`. Aliases: `Expression`, `LVal` - `name``string` (required) - `decorators`: `Array<Decorator>` (default: `null`) - `typeAnnotation` (default: `null`) --- ### ifStatement ```javascript t.ifStatement(test, consequent, alternate) ``` See also `t.isIfStatement(node, opts)` and `t.assertIfStatement(node, opts)`. Aliases: `Statement`, `Conditional` - `test`: `Expression` (required) - `consequent`: `Statement` (required) - `alternate`: `Statement` (default: `null`) --- ### import ```javascript t.import() ``` See also `t.isImport(node, opts)` and `t.assertImport(node, opts)`. Aliases: `Expression` --- ### importDeclaration ```javascript t.importDeclaration(specifiers, source) ``` See also `t.isImportDeclaration(node, opts)` and `t.assertImportDeclaration(node, opts)`. Aliases: `Statement`, `Declaration`, `ModuleDeclaration` - `specifiers`: `Array<ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier>` (required) - `source`: `StringLiteral` (required) --- ### importDefaultSpecifier ```javascript t.importDefaultSpecifier(local) ``` See also `t.isImportDefaultSpecifier(node, opts)` and `t.assertImportDefaultSpecifier(node, opts)`. Aliases: `ModuleSpecifier` - `local`: `Identifier` (required) --- ### importNamespaceSpecifier ```javascript t.importNamespaceSpecifier(local) ``` See also `t.isImportNamespaceSpecifier(node, opts)` and `t.assertImportNamespaceSpecifier(node, opts)`. Aliases: `ModuleSpecifier` - `local`: `Identifier` (required) --- ### importSpecifier ```javascript t.importSpecifier(local, imported) ``` See also `t.isImportSpecifier(node, opts)` and `t.assertImportSpecifier(node, opts)`. Aliases: `ModuleSpecifier` - `local`: `Identifier` (required) - `imported`: `Identifier` (required) - `importKind`: `null | 'type' | 'typeof'` (default: `null`) --- ### interfaceDeclaration ```javascript t.interfaceDeclaration(id, typeParameters, extends, body) ``` See also `t.isInterfaceDeclaration(node, opts)` and `t.assertInterfaceDeclaration(node, opts)`. Aliases: `Flow`, `FlowDeclaration`, `Statement`, `Declaration` - `id` (required) - `typeParameters` (required) - `extends` (required) - `body` (required) --- ### interfaceExtends ```javascript t.interfaceExtends(id, typeParameters) ``` See also `t.isInterfaceExtends(node, opts)` and `t.assertInterfaceExtends(node, opts)`. Aliases: `Flow` - `id` (required) - `typeParameters` (required) --- ### intersectionTypeAnnotation ```javascript t.intersectionTypeAnnotation(types) ``` See also `t.isIntersectionTypeAnnotation(node, opts)` and `t.assertIntersectionTypeAnnotation(node, opts)`. Aliases: `Flow` - `types` (required) --- ### jSXAttribute ```javascript t.jSXAttribute(name, value) ``` See also `t.isJSXAttribute(node, opts)` and `t.assertJSXAttribute(node, opts)`. Aliases: `JSX`, `Immutable` - `name`: `JSXIdentifier | JSXNamespacedName` (required) - `value`: `JSXElement | StringLiteral | JSXExpressionContainer` (default: `null`) --- ### jSXClosingElement ```javascript t.jSXClosingElement(name) ``` See also `t.isJSXClosingElement(node, opts)` and `t.assertJSXClosingElement(node, opts)`. Aliases: `JSX`, `Immutable` - `name`: `JSXIdentifier | JSXMemberExpression` (required) --- ### jSXElement ```javascript t.jSXElement(openingElement, closingElement, children, selfClosing) ``` See also `t.isJSXElement(node, opts)` and `t.assertJSXElement(node, opts)`. Aliases: `JSX`, `Immutable`, `Expression` - `openingElement`: `JSXOpeningElement` (required) - `closingElement`: `JSXClosingElement` (default: `null`) - `children`: `Array<JSXText | JSXExpressionContainer | JSXSpreadChild | JSXElement>` (required) - `selfClosing` (required) --- ### jSXEmptyExpression ```javascript t.jSXEmptyExpression() ``` See also `t.isJSXEmptyExpression(node, opts)` and `t.assertJSXEmptyExpression(node, opts)`. Aliases: `JSX`, `Expression` --- ### jSXExpressionContainer ```javascript t.jSXExpressionContainer(expression) ``` See also `t.isJSXExpressionContainer(node, opts)` and `t.assertJSXExpressionContainer(node, opts)`. Aliases: `JSX`, `Immutable` - `expression`: `Expression` (required) --- ### jSXIdentifier ```javascript t.jSXIdentifier(name) ``` See also `t.isJSXIdentifier(node, opts)` and `t.assertJSXIdentifier(node, opts)`. Aliases: `JSX`, `Expression` - `name`: `string` (required) --- ### jSXMemberExpression ```javascript t.jSXMemberExpression(object, property) ``` See also `t.isJSXMemberExpression(node, opts)` and `t.assertJSXMemberExpression(node, opts)`. Aliases: `JSX`, `Expression` - `object`: `JSXMemberExpression | JSXIdentifier` (required) - `property`: `JSXIdentifier` (required) --- ### jSXNamespacedName ```javascript t.jSXNamespacedName(namespace, name) ``` See also `t.isJSXNamespacedName(node, opts)` and `t.assertJSXNamespacedName(node, opts)`. Aliases: `JSX` - `namespace`: `JSXIdentifier` (required) - `name`: `JSXIdentifier` (required) --- ### jSXOpeningElement ```javascript t.jSXOpeningElement(name, attributes, selfClosing) ``` See also `t.isJSXOpeningElement(node, opts)` and `t.assertJSXOpeningElement(node, opts)`. Aliases: `JSX`, `Immutable` - `name`: `JSXIdentifier | JSXMemberExpression` (required) - `attributes`: `Array<JSXAttribute | JSXSpreadAttribute>` (required) - `selfClosing`: `boolean` (default: `false`) --- ### jSXSpreadAttribute ```javascript t.jSXSpreadAttribute(argument) ``` See also `t.isJSXSpreadAttribute(node, opts)` and `t.assertJSXSpreadAttribute(node, opts)`. Aliases: `JSX` - `argument`: `Expression` (required) --- ### jSXSpreadChild ```javascript t.jSXSpreadChild(expression) ``` See also `t.isJSXSpreadChild(node, opts)` and `t.assertJSXSpreadChild(node, opts)`. Aliases: `JSX`, `Immutable` - `expression`: `Expression` (required) --- ### jSXText ```javascript t.jSXText(value) ``` See also `t.isJSXText(node, opts)` and `t.assertJSXText(node, opts)`. Aliases: `JSX`, `Immutable` - `value`: `string` (required) --- ### labeledStatement ```javascript t.labeledStatement(label, body) ``` See also `t.isLabeledStatement(node, opts)` and `t.assertLabeledStatement(node, opts)`. Aliases: `Statement` - `label`: `Identifier` (required) - `body`: `Statement` (required) --- ### logicalExpression ```javascript t.logicalExpression(operator, left, right) ``` See also `t.isLogicalExpression(node, opts)` and `t.assertLogicalExpression(node, opts)`. Aliases: `Binary`, `Expression` - `operator`: `'||' | '&&'` (required) - `left`: `Expression` (required) - `right`: `Expression` (required) --- ### memberExpression ```javascript t.memberExpression(object, property, computed) ``` See also `t.isMemberExpression(node, opts)` and `t.assertMemberExpression(node, opts)`. Aliases: `Expression`, `LVal` - `object`: `Expression` (required) - `property`if computed then `Expression` else `Identifier` (required) - `computed`: `boolean` (default: `false`) --- ### metaProperty ```javascript t.metaProperty(meta, property) ``` See also `t.isMetaProperty(node, opts)` and `t.assertMetaProperty(node, opts)`. Aliases: `Expression` - `meta`: `string` (required) - `property`: `string` (required) --- ### mixedTypeAnnotation ```javascript t.mixedTypeAnnotation() ``` See also `t.isMixedTypeAnnotation(node, opts)` and `t.assertMixedTypeAnnotation(node, opts)`. Aliases: `Flow`, `FlowBaseAnnotation` --- ### newExpression ```javascript t.newExpression(callee, arguments) ``` See also `t.isNewExpression(node, opts)` and `t.assertNewExpression(node, opts)`. Aliases: `Expression` - `callee`: `Expression` (required) - `arguments`: `Array<Expression | SpreadElement>` (required) --- ### noop ```javascript t.noop() ``` See also `t.isNoop(node, opts)` and `t.assertNoop(node, opts)`. --- ### nullLiteral ```javascript t.nullLiteral() ``` See also `t.isNullLiteral(node, opts)` and `t.assertNullLiteral(node, opts)`. Aliases: `Expression`, `Pureish`, `Literal`, `Immutable` --- ### nullLiteralTypeAnnotation ```javascript t.nullLiteralTypeAnnotation() ``` See also `t.isNullLiteralTypeAnnotation(node, opts)` and `t.assertNullLiteralTypeAnnotation(node, opts)`. Aliases: `Flow`, `FlowBaseAnnotation` --- ### nullableTypeAnnotation ```javascript t.nullableTypeAnnotation(typeAnnotation) ``` See also `t.isNullableTypeAnnotation(node, opts)` and `t.assertNullableTypeAnnotation(node, opts)`. Aliases: `Flow` - `typeAnnotation` (required) --- ### numberTypeAnnotation ```javascript t.numberTypeAnnotation() ``` See also `t.isNumberTypeAnnotation(node, opts)` and `t.assertNumberTypeAnnotation(node, opts)`. Aliases: `Flow`, `FlowBaseAnnotation` --- ### numericLiteral ```javascript t.numericLiteral(value) ``` See also `t.isNumericLiteral(node, opts)` and `t.assertNumericLiteral(node, opts)`. Aliases: `Expression`, `Pureish`, `Literal`, `Immutable` - `value`: `number` (required) --- ### numericLiteralTypeAnnotation ```javascript t.numericLiteralTypeAnnotation() ``` See also `t.isNumericLiteralTypeAnnotation(node, opts)` and `t.assertNumericLiteralTypeAnnotation(node, opts)`. Aliases: `Flow` --- ### objectExpression ```javascript t.objectExpression(properties) ``` See also `t.isObjectExpression(node, opts)` and `t.assertObjectExpression(node, opts)`. Aliases: `Expression` - `properties`: `Array<ObjectMethod | ObjectProperty | SpreadProperty>` (required) --- ### objectMethod ```javascript t.objectMethod(kind, key, params, body, computed) ``` See also `t.isObjectMethod(node, opts)` and `t.assertObjectMethod(node, opts)`. Aliases: `UserWhitespacable`, `Function`, `Scopable`, `BlockParent`, `FunctionParent`, `Method`, `ObjectMember` - `kind`: `"method" | "get" | "set"` (default: `'method'`) - `key`if computed then `Expression` else `Identifier | Literal` (required) - `params` (required) - `body`: `BlockStatement` (required) - `computed`: `boolean` (default: `false`) - `async`: `boolean` (default: `false`) - `decorators`: `Array<Decorator>` (default: `null`) - `generator`: `boolean` (default: `false`) - `returnType` (default: `null`) - `typeParameters` (default: `null`) --- ### objectPattern ```javascript t.objectPattern(properties, typeAnnotation) ``` See also `t.isObjectPattern(node, opts)` and `t.assertObjectPattern(node, opts)`. Aliases: `Pattern`, `LVal` - `properties`: `Array<RestProperty | Property>` (required) - `typeAnnotation` (required) - `decorators`: `Array<Decorator>` (default: `null`) --- ### objectProperty ```javascript t.objectProperty(key, value, computed, shorthand, decorators) ``` See also `t.isObjectProperty(node, opts)` and `t.assertObjectProperty(node, opts)`. Aliases: `UserWhitespacable`, `Property`, `ObjectMember` - `key`if computed then `Expression` else `Identifier | Literal` (required) - `value`: `Expression | Pattern | RestElement` (required) - `computed`: `boolean` (default: `false`) - `shorthand`: `boolean` (default: `false`) - `decorators`: `Array<Decorator>` (default: `null`) --- ### objectTypeAnnotation ```javascript t.objectTypeAnnotation(properties, indexers, callProperties) ``` See also `t.isObjectTypeAnnotation(node, opts)` and `t.assertObjectTypeAnnotation(node, opts)`. Aliases: `Flow` - `properties` (required) - `indexers` (required) - `callProperties` (required) --- ### objectTypeCallProperty ```javascript t.objectTypeCallProperty(value) ``` See also `t.isObjectTypeCallProperty(node, opts)` and `t.assertObjectTypeCallProperty(node, opts)`. Aliases: `Flow`, `UserWhitespacable` - `value` (required) --- ### objectTypeIndexer ```javascript t.objectTypeIndexer(id, key, value) ``` See also `t.isObjectTypeIndexer(node, opts)` and `t.assertObjectTypeIndexer(node, opts)`. Aliases: `Flow`, `UserWhitespacable` - `id` (required) - `key` (required) - `value` (required) --- ### objectTypeProperty ```javascript t.objectTypeProperty(key, value) ``` See also `t.isObjectTypeProperty(node, opts)` and `t.assertObjectTypeProperty(node, opts)`. Aliases: `Flow`, `UserWhitespacable` - `key` (required) - `value` (required) --- ### objectTypeSpreadProperty ```javascript t.objectTypeSpreadProperty(argument) ``` See also `t.isObjectTypeSpreadProperty(node, opts)` and `t.assertObjectTypeSpreadProperty(node, opts)`. Aliases: `Flow`, `UserWhitespacable` - `argument` (required) --- ### opaqueType ```javascript t.opaqueType(id, typeParameters, impltype, supertype) ``` See also `t.isOpaqueType(node, opts)` and `t.assertOpaqueType(node, opts)`. Aliases: `Flow`, `FlowDeclaration`, `Statement`, `Declaration` - `id` (required) - `typeParameters` (required) - `impltype` (required) - `supertype` (required) --- ### parenthesizedExpression ```javascript t.parenthesizedExpression(expression) ``` See also `t.isParenthesizedExpression(node, opts)` and `t.assertParenthesizedExpression(node, opts)`. Aliases: `Expression`, `ExpressionWrapper` - `expression`: `Expression` (required) --- ### program ```javascript t.program(body, directives) ``` See also `t.isProgram(node, opts)` and `t.assertProgram(node, opts)`. Aliases: `Scopable`, `BlockParent`, `Block`, `FunctionParent` - `body`: `Array<Statement>` (required) - `directives`: `Array<Directive>` (default: `[]`) --- ### qualifiedTypeIdentifier ```javascript t.qualifiedTypeIdentifier(id, qualification) ``` See also `t.isQualifiedTypeIdentifier(node, opts)` and `t.assertQualifiedTypeIdentifier(node, opts)`. Aliases: `Flow` - `id` (required) - `qualification` (required) --- ### regExpLiteral ```javascript t.regExpLiteral(pattern, flags) ``` See also `t.isRegExpLiteral(node, opts)` and `t.assertRegExpLiteral(node, opts)`. Aliases: `Expression`, `Literal` - `pattern`: `string` (required) - `flags`: `string` (default: `''`) --- ### restElement ```javascript t.restElement(argument, typeAnnotation) ``` See also `t.isRestElement(node, opts)` and `t.assertRestElement(node, opts)`. Aliases: `LVal` - `argument`: `LVal` (required) - `typeAnnotation` (required) - `decorators`: `Array<Decorator>` (default: `null`) --- ### restProperty ```javascript t.restProperty(argument) ``` See also `t.isRestProperty(node, opts)` and `t.assertRestProperty(node, opts)`. Aliases: `UnaryLike` - `argument`: `LVal` (required) --- ### returnStatement ```javascript t.returnStatement(argument) ``` See also `t.isReturnStatement(node, opts)` and `t.assertReturnStatement(node, opts)`. Aliases: `Statement`, `Terminatorless`, `CompletionStatement` - `argument`: `Expression` (default: `null`) --- ### sequenceExpression ```javascript t.sequenceExpression(expressions) ``` See also `t.isSequenceExpression(node, opts)` and `t.assertSequenceExpression(node, opts)`. Aliases: `Expression` - `expressions`: `Array<Expression>` (required) --- ### spreadElement ```javascript t.spreadElement(argument) ``` See also `t.isSpreadElement(node, opts)` and `t.assertSpreadElement(node, opts)`. Aliases: `UnaryLike` - `argument`: `Expression` (required) --- ### spreadProperty ```javascript t.spreadProperty(argument) ``` See also `t.isSpreadProperty(node, opts)` and `t.assertSpreadProperty(node, opts)`. Aliases: `UnaryLike` - `argument`: `Expression` (required) --- ### stringLiteral ```javascript t.stringLiteral(value) ``` See also `t.isStringLiteral(node, opts)` and `t.assertStringLiteral(node, opts)`. Aliases: `Expression`, `Pureish`, `Literal`, `Immutable` - `value`: `string` (required) --- ### stringLiteralTypeAnnotation ```javascript t.stringLiteralTypeAnnotation() ``` See also `t.isStringLiteralTypeAnnotation(node, opts)` and `t.assertStringLiteralTypeAnnotation(node, opts)`. Aliases: `Flow` --- ### stringTypeAnnotation ```javascript t.stringTypeAnnotation() ``` See also `t.isStringTypeAnnotation(node, opts)` and `t.assertStringTypeAnnotation(node, opts)`. Aliases: `Flow`, `FlowBaseAnnotation` --- ### super ```javascript t.super() ``` See also `t.isSuper(node, opts)` and `t.assertSuper(node, opts)`. Aliases: `Expression` --- ### switchCase ```javascript t.switchCase(test, consequent) ``` See also `t.isSwitchCase(node, opts)` and `t.assertSwitchCase(node, opts)`. - `test`: `Expression` (default: `null`) - `consequent`: `Array<Statement>` (required) --- ### switchStatement ```javascript t.switchStatement(discriminant, cases) ``` See also `t.isSwitchStatement(node, opts)` and `t.assertSwitchStatement(node, opts)`. Aliases: `Statement`, `BlockParent`, `Scopable` - `discriminant`: `Expression` (required) - `cases`: `Array<SwitchCase>` (required) --- ### taggedTemplateExpression ```javascript t.taggedTemplateExpression(tag, quasi) ``` See also `t.isTaggedTemplateExpression(node, opts)` and `t.assertTaggedTemplateExpression(node, opts)`. Aliases: `Expression` - `tag`: `Expression` (required) - `quasi`: `TemplateLiteral` (required) --- ### templateElement ```javascript t.templateElement(value, tail) ``` See also `t.isTemplateElement(node, opts)` and `t.assertTemplateElement(node, opts)`. - `value` (required) - `tail`: `boolean` (default: `false`) --- ### templateLiteral ```javascript t.templateLiteral(quasis, expressions) ``` See also `t.isTemplateLiteral(node, opts)` and `t.assertTemplateLiteral(node, opts)`. Aliases: `Expression`, `Literal` - `quasis`: `Array<TemplateElement>` (required) - `expressions`: `Array<Expression>` (required) --- ### thisExpression ```javascript t.thisExpression() ``` See also `t.isThisExpression(node, opts)` and `t.assertThisExpression(node, opts)`. Aliases: `Expression` --- ### thisTypeAnnotation ```javascript t.thisTypeAnnotation() ``` See also `t.isThisTypeAnnotation(node, opts)` and `t.assertThisTypeAnnotation(node, opts)`. Aliases: `Flow`, `FlowBaseAnnotation` --- ### throwStatement ```javascript t.throwStatement(argument) ``` See also `t.isThrowStatement(node, opts)` and `t.assertThrowStatement(node, opts)`. Aliases: `Statement`, `Terminatorless`, `CompletionStatement` - `argument`: `Expression` (required) --- ### tryStatement ```javascript t.tryStatement(block, handler, finalizer) ``` See also `t.isTryStatement(node, opts)` and `t.assertTryStatement(node, opts)`. Aliases: `Statement` - `block` (required) - `handler` (default: `null`) - `finalizer`: `BlockStatement` (default: `null`) - `body`: `BlockStatement` (default: `null`) --- ### tupleTypeAnnotation ```javascript t.tupleTypeAnnotation(types) ``` See also `t.isTupleTypeAnnotation(node, opts)` and `t.assertTupleTypeAnnotation(node, opts)`. Aliases: `Flow` - `types` (required) --- ### typeAlias ```javascript t.typeAlias(id, typeParameters, right) ``` See also `t.isTypeAlias(node, opts)` and `t.assertTypeAlias(node, opts)`. Aliases: `Flow`, `FlowDeclaration`, `Statement`, `Declaration` - `id` (required) - `typeParameters` (required) - `right` (required) --- ### typeAnnotation ```javascript t.typeAnnotation(typeAnnotation) ``` See also `t.isTypeAnnotation(node, opts)` and `t.assertTypeAnnotation(node, opts)`. Aliases: `Flow` - `typeAnnotation` (required) --- ### typeCastExpression ```javascript t.typeCastExpression(expression, typeAnnotation) ``` See also `t.isTypeCastExpression(node, opts)` and `t.assertTypeCastExpression(node, opts)`. Aliases: `Flow`, `ExpressionWrapper`, `Expression` - `expression` (required) - `typeAnnotation` (required) --- ### typeParameter ```javascript t.typeParameter(bound) ``` See also `t.isTypeParameter(node, opts)` and `t.assertTypeParameter(node, opts)`. Aliases: `Flow` - `bound` (required) --- ### typeParameterDeclaration ```javascript t.typeParameterDeclaration(params) ``` See also `t.isTypeParameterDeclaration(node, opts)` and `t.assertTypeParameterDeclaration(node, opts)`. Aliases: `Flow` - `params` (required) --- ### typeParameterInstantiation ```javascript t.typeParameterInstantiation(params) ``` See also `t.isTypeParameterInstantiation(node, opts)` and `t.assertTypeParameterInstantiation(node, opts)`. Aliases: `Flow` - `params` (required) --- ### typeofTypeAnnotation ```javascript t.typeofTypeAnnotation(argument) ``` See also `t.isTypeofTypeAnnotation(node, opts)` and `t.assertTypeofTypeAnnotation(node, opts)`. Aliases: `Flow` - `argument` (required) --- ### unaryExpression ```javascript t.unaryExpression(operator, argument, prefix) ``` See also `t.isUnaryExpression(node, opts)` and `t.assertUnaryExpression(node, opts)`. Aliases: `UnaryLike`, `Expression` - `operator`: `'void' | 'delete' | '!' | '+' | '-' | '++' | '--' | '~' | 'typeof'` (required) - `argument`: `Expression` (required) - `prefix`: `boolean` (default: `true`) --- ### unionTypeAnnotation ```javascript t.unionTypeAnnotation(types) ``` See also `t.isUnionTypeAnnotation(node, opts)` and `t.assertUnionTypeAnnotation(node, opts)`. Aliases: `Flow` - `types` (required) --- ### updateExpression ```javascript t.updateExpression(operator, argument, prefix) ``` See also `t.isUpdateExpression(node, opts)` and `t.assertUpdateExpression(node, opts)`. Aliases: `Expression` - `operator`: `'++' | '--'` (required) - `argument`: `Expression` (required) - `prefix`: `boolean` (default: `false`) --- ### variableDeclaration ```javascript t.variableDeclaration(kind, declarations) ``` See also `t.isVariableDeclaration(node, opts)` and `t.assertVariableDeclaration(node, opts)`. Aliases: `Statement`, `Declaration` - `kind`: `"var" | "let" | "const"` (required) - `declarations`: `Array<VariableDeclarator>` (required) --- ### variableDeclarator ```javascript t.variableDeclarator(id, init) ``` See also `t.isVariableDeclarator(node, opts)` and `t.assertVariableDeclarator(node, opts)`. - `id`: `LVal` (required) - `init`: `Expression` (default: `null`) --- ### voidTypeAnnotation ```javascript t.voidTypeAnnotation() ``` See also `t.isVoidTypeAnnotation(node, opts)` and `t.assertVoidTypeAnnotation(node, opts)`. Aliases: `Flow`, `FlowBaseAnnotation` --- ### whileStatement ```javascript t.whileStatement(test, body) ``` See also `t.isWhileStatement(node, opts)` and `t.assertWhileStatement(node, opts)`. Aliases: `Statement`, `BlockParent`, `Loop`, `While`, `Scopable` - `test`: `Expression` (required) - `body`: `BlockStatement | Statement` (required) --- ### withStatement ```javascript t.withStatement(object, body) ``` See also `t.isWithStatement(node, opts)` and `t.assertWithStatement(node, opts)`. Aliases: `Statement` - `object` (required) - `body`: `BlockStatement | Statement` (required) --- ### yieldExpression ```javascript t.yieldExpression(argument, delegate) ``` See also `t.isYieldExpression(node, opts)` and `t.assertYieldExpression(node, opts)`. Aliases: `Expression`, `Terminatorless` - `argument`: `Expression` (default: `null`) - `delegate`: `boolean` (default: `false`) --- <!-- end generated section --> # ws: a Node.js WebSocket library [![Version npm](https://img.shields.io/npm/v/ws.svg?logo=npm)](https://www.npmjs.com/package/ws) [![Build](https://img.shields.io/travis/websockets/ws/master.svg?logo=travis)](https://travis-ci.com/websockets/ws) [![Windows x86 Build](https://img.shields.io/appveyor/ci/lpinca/ws/master.svg?logo=appveyor)](https://ci.appveyor.com/project/lpinca/ws) [![Coverage Status](https://img.shields.io/coveralls/websockets/ws/master.svg)](https://coveralls.io/github/websockets/ws) ws is a simple to use, blazing fast, and thoroughly tested WebSocket client and server implementation. Passes the quite extensive Autobahn test suite: [server][server-report], [client][client-report]. **Note**: This module does not work in the browser. The client in the docs is a reference to a back end with the role of a client in the WebSocket communication. Browser clients must use the native [`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) object. To make the same code work seamlessly on Node.js and the browser, you can use one of the many wrappers available on npm, like [isomorphic-ws](https://github.com/heineiuo/isomorphic-ws). ## Table of Contents - [Protocol support](#protocol-support) - [Installing](#installing) - [Opt-in for performance and spec compliance](#opt-in-for-performance-and-spec-compliance) - [API docs](#api-docs) - [WebSocket compression](#websocket-compression) - [Usage examples](#usage-examples) - [Sending and receiving text data](#sending-and-receiving-text-data) - [Sending binary data](#sending-binary-data) - [Simple server](#simple-server) - [External HTTP/S server](#external-https-server) - [Multiple servers sharing a single HTTP/S server](#multiple-servers-sharing-a-single-https-server) - [Client authentication](#client-authentication) - [Server broadcast](#server-broadcast) - [echo.websocket.org demo](#echowebsocketorg-demo) - [Use the Node.js streams API](#use-the-nodejs-streams-api) - [Other examples](#other-examples) - [FAQ](#faq) - [How to get the IP address of the client?](#how-to-get-the-ip-address-of-the-client) - [How to detect and close broken connections?](#how-to-detect-and-close-broken-connections) - [How to connect via a proxy?](#how-to-connect-via-a-proxy) - [Changelog](#changelog) - [License](#license) ## Protocol support - **HyBi drafts 07-12** (Use the option `protocolVersion: 8`) - **HyBi drafts 13-17** (Current default, alternatively option `protocolVersion: 13`) ## Installing ``` npm install ws ``` ### Opt-in for performance and spec compliance There are 2 optional modules that can be installed along side with the ws module. These modules are binary addons which improve certain operations. Prebuilt binaries are available for the most popular platforms so you don't necessarily need to have a C++ compiler installed on your machine. - `npm install --save-optional bufferutil`: Allows to efficiently perform operations such as masking and unmasking the data payload of the WebSocket frames. - `npm install --save-optional utf-8-validate`: Allows to efficiently check if a message contains valid UTF-8 as required by the spec. ## API docs See [`/doc/ws.md`](./doc/ws.md) for Node.js-like documentation of ws classes and utility functions. ## WebSocket compression ws supports the [permessage-deflate extension][permessage-deflate] which enables the client and server to negotiate a compression algorithm and its parameters, and then selectively apply it to the data payloads of each WebSocket message. The extension is disabled by default on the server and enabled by default on the client. It adds a significant overhead in terms of performance and memory consumption so we suggest to enable it only if it is really needed. Note that Node.js has a variety of issues with high-performance compression, where increased concurrency, especially on Linux, can lead to [catastrophic memory fragmentation][node-zlib-bug] and slow performance. If you intend to use permessage-deflate in production, it is worthwhile to set up a test representative of your workload and ensure Node.js/zlib will handle it with acceptable performance and memory usage. Tuning of permessage-deflate can be done via the options defined below. You can also use `zlibDeflateOptions` and `zlibInflateOptions`, which is passed directly into the creation of [raw deflate/inflate streams][node-zlib-deflaterawdocs]. See [the docs][ws-server-options] for more options. ```js const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080, perMessageDeflate: { zlibDeflateOptions: { // See zlib defaults. chunkSize: 1024, memLevel: 7, level: 3 }, zlibInflateOptions: { chunkSize: 10 * 1024 }, // Other options settable: clientNoContextTakeover: true, // Defaults to negotiated value. serverNoContextTakeover: true, // Defaults to negotiated value. serverMaxWindowBits: 10, // Defaults to negotiated value. // Below options specified as default values. concurrencyLimit: 10, // Limits zlib concurrency for perf. threshold: 1024 // Size (in bytes) below which messages // should not be compressed. } }); ``` The client will only use the extension if it is supported and enabled on the server. To always disable the extension on the client set the `perMessageDeflate` option to `false`. ```js const WebSocket = require('ws'); const ws = new WebSocket('ws://www.host.com/path', { perMessageDeflate: false }); ``` ## Usage examples ### Sending and receiving text data ```js const WebSocket = require('ws'); const ws = new WebSocket('ws://www.host.com/path'); ws.on('open', function open() { ws.send('something'); }); ws.on('message', function incoming(data) { console.log(data); }); ``` ### Sending binary data ```js const WebSocket = require('ws'); const ws = new WebSocket('ws://www.host.com/path'); ws.on('open', function open() { const array = new Float32Array(5); for (var i = 0; i < array.length; ++i) { array[i] = i / 2; } ws.send(array); }); ``` ### Simple server ```js const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', function connection(ws) { ws.on('message', function incoming(message) { console.log('received: %s', message); }); ws.send('something'); }); ``` ### External HTTP/S server ```js const fs = require('fs'); const https = require('https'); const WebSocket = require('ws'); const server = https.createServer({ cert: fs.readFileSync('/path/to/cert.pem'), key: fs.readFileSync('/path/to/key.pem') }); const wss = new WebSocket.Server({ server }); wss.on('connection', function connection(ws) { ws.on('message', function incoming(message) { console.log('received: %s', message); }); ws.send('something'); }); server.listen(8080); ``` ### Multiple servers sharing a single HTTP/S server ```js const http = require('http'); const WebSocket = require('ws'); const url = require('url'); const server = http.createServer(); const wss1 = new WebSocket.Server({ noServer: true }); const wss2 = new WebSocket.Server({ noServer: true }); wss1.on('connection', function connection(ws) { // ... }); wss2.on('connection', function connection(ws) { // ... }); server.on('upgrade', function upgrade(request, socket, head) { const pathname = url.parse(request.url).pathname; if (pathname === '/foo') { wss1.handleUpgrade(request, socket, head, function done(ws) { wss1.emit('connection', ws, request); }); } else if (pathname === '/bar') { wss2.handleUpgrade(request, socket, head, function done(ws) { wss2.emit('connection', ws, request); }); } else { socket.destroy(); } }); server.listen(8080); ``` ### Client authentication ```js const http = require('http'); const WebSocket = require('ws'); const server = http.createServer(); const wss = new WebSocket.Server({ noServer: true }); wss.on('connection', function connection(ws, request, client) { ws.on('message', function message(msg) { console.log(`Received message ${msg} from user ${client}`); }); }); server.on('upgrade', function upgrade(request, socket, head) { // This function is not defined on purpose. Implement it with your own logic. authenticate(request, (err, client) => { if (err || !client) { socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n'); socket.destroy(); return; } wss.handleUpgrade(request, socket, head, function done(ws) { wss.emit('connection', ws, request, client); }); }); }); server.listen(8080); ``` Also see the provided [example][session-parse-example] using `express-session`. ### Server broadcast A client WebSocket broadcasting to all connected WebSocket clients, including itself. ```js const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', function connection(ws) { ws.on('message', function incoming(data) { wss.clients.forEach(function each(client) { if (client.readyState === WebSocket.OPEN) { client.send(data); } }); }); }); ``` A client WebSocket broadcasting to every other connected WebSocket clients, excluding itself. ```js const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', function connection(ws) { ws.on('message', function incoming(data) { wss.clients.forEach(function each(client) { if (client !== ws && client.readyState === WebSocket.OPEN) { client.send(data); } }); }); }); ``` ### echo.websocket.org demo ```js const WebSocket = require('ws'); const ws = new WebSocket('wss://echo.websocket.org/', { origin: 'https://websocket.org' }); ws.on('open', function open() { console.log('connected'); ws.send(Date.now()); }); ws.on('close', function close() { console.log('disconnected'); }); ws.on('message', function incoming(data) { console.log(`Roundtrip time: ${Date.now() - data} ms`); setTimeout(function timeout() { ws.send(Date.now()); }, 500); }); ``` ### Use the Node.js streams API ```js const WebSocket = require('ws'); const ws = new WebSocket('wss://echo.websocket.org/', { origin: 'https://websocket.org' }); const duplex = WebSocket.createWebSocketStream(ws, { encoding: 'utf8' }); duplex.pipe(process.stdout); process.stdin.pipe(duplex); ``` ### Other examples For a full example with a browser client communicating with a ws server, see the examples folder. Otherwise, see the test cases. ## FAQ ### How to get the IP address of the client? The remote IP address can be obtained from the raw socket. ```js const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', function connection(ws, req) { const ip = req.socket.remoteAddress; }); ``` When the server runs behind a proxy like NGINX, the de-facto standard is to use the `X-Forwarded-For` header. ```js wss.on('connection', function connection(ws, req) { const ip = req.headers['x-forwarded-for'].split(/\s*,\s*/)[0]; }); ``` ### How to detect and close broken connections? Sometimes the link between the server and the client can be interrupted in a way that keeps both the server and the client unaware of the broken state of the connection (e.g. when pulling the cord). In these cases ping messages can be used as a means to verify that the remote endpoint is still responsive. ```js const WebSocket = require('ws'); function noop() {} function heartbeat() { this.isAlive = true; } const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', function connection(ws) { ws.isAlive = true; ws.on('pong', heartbeat); }); const interval = setInterval(function ping() { wss.clients.forEach(function each(ws) { if (ws.isAlive === false) return ws.terminate(); ws.isAlive = false; ws.ping(noop); }); }, 30000); wss.on('close', function close() { clearInterval(interval); }); ``` Pong messages are automatically sent in response to ping messages as required by the spec. Just like the server example above your clients might as well lose connection without knowing it. You might want to add a ping listener on your clients to prevent that. A simple implementation would be: ```js const WebSocket = require('ws'); function heartbeat() { clearTimeout(this.pingTimeout); // Use `WebSocket#terminate()`, which immediately destroys the connection, // instead of `WebSocket#close()`, which waits for the close timer. // Delay should be equal to the interval at which your server // sends out pings plus a conservative assumption of the latency. this.pingTimeout = setTimeout(() => { this.terminate(); }, 30000 + 1000); } const client = new WebSocket('wss://echo.websocket.org/'); client.on('open', heartbeat); client.on('ping', heartbeat); client.on('close', function clear() { clearTimeout(this.pingTimeout); }); ``` ### How to connect via a proxy? Use a custom `http.Agent` implementation like [https-proxy-agent][] or [socks-proxy-agent][]. ## Changelog We're using the GitHub [releases][changelog] for changelog entries. ## License [MIT](LICENSE) [changelog]: https://github.com/websockets/ws/releases [client-report]: http://websockets.github.io/ws/autobahn/clients/ [https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent [node-zlib-bug]: https://github.com/nodejs/node/issues/8871 [node-zlib-deflaterawdocs]: https://nodejs.org/api/zlib.html#zlib_zlib_createdeflateraw_options [permessage-deflate]: https://tools.ietf.org/html/rfc7692 [server-report]: http://websockets.github.io/ws/autobahn/servers/ [session-parse-example]: ./examples/express-session-parse [socks-proxy-agent]: https://github.com/TooTallNate/node-socks-proxy-agent [ws-server-options]: https://github.com/websockets/ws/blob/master/doc/ws.md#new-websocketserveroptions-callback # [postcss][postcss]-merge-longhand > Merge longhand properties into shorthand with PostCSS. ## Install With [npm](https://npmjs.org/package/postcss-merge-longhand) do: ``` npm install postcss-merge-longhand --save ``` ## Example Merge longhand properties into shorthand; works with `margin`, `padding` & `border`. For more examples see the [tests](src/__tests__/index.js). ### Input ```css h1 { margin-top: 10px; margin-right: 20px; margin-bottom: 10px; margin-left: 20px; } ``` ### Output ```css h1 { margin: 10px 20px; } ``` ## Usage See the [PostCSS documentation](https://github.com/postcss/postcss#usage) for examples for your environment. ## Contributors See [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md). ## License MIT © [Ben Briggs](http://beneb.info) [postcss]: https://github.com/postcss/postcss # 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._ 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> command-exists ============== node module to check if a command-line command exists ## installation ```bash npm install command-exists ``` ## usage ### async ```js var commandExists = require('command-exists'); commandExists('ls', function(err, commandExists) { if(commandExists) { // proceed confidently knowing this command is available } }); ``` ### promise ```js var commandExists = require('command-exists'); // invoked without a callback, it returns a promise commandExists('ls') .then(function(command){ // proceed }).catch(function(){ // command doesn't exist }); ``` ### sync ```js var commandExistsSync = require('command-exists').sync; // returns true/false; doesn't throw if (commandExistsSync('ls')) { // proceed } else { // ... } ``` ## changelog ### v1.2.7 Removes unnecessary printed output on windows. ### v1.2.6 Small bugfixes. ### v1.2.5 Fix windows bug introduced in 1.2.4. ### v1.2.4 Fix potential security issue. ### v1.2.0 Add support for promises ### v1.1.0 Add synchronous version ### v1.0.2 Support for windows # istanbul-reports [![Greenkeeper badge](https://badges.greenkeeper.io/istanbuljs/istanbul-reports.svg)](https://greenkeeper.io/) [![Build Status](https://travis-ci.org/istanbuljs/istanbul-reports.svg?branch=master)](https://travis-ci.org/istanbuljs/istanbul-reports) - node.getRelativeName - context.getSource(filePath) - context.classForPercent(type, percent) - context.console.colorize(str, class) - context.writer - context.console.write - context.console.println <a href="http://promisesaplus.com/"> <img src="https://promises-aplus.github.io/promises-spec/assets/logo-small.png" align="right" alt="Promises/A+ logo" /> </a> # Request-Promise-Native [![Gitter](https://img.shields.io/badge/gitter-join_chat-blue.svg?style=flat-square&maxAge=2592000)](https://gitter.im/request/request-promise?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Build Status](https://img.shields.io/travis/request/request-promise-native/master.svg?style=flat-square&maxAge=2592000)](https://travis-ci.org/request/request-promise-native) [![Coverage Status](https://img.shields.io/coveralls/request/request-promise-native.svg?style=flat-square&maxAge=2592000)](https://coveralls.io/r/request/request-promise-native) [![Dependency Status](https://img.shields.io/david/request/request-promise-native.svg?style=flat-square&maxAge=2592000)](https://david-dm.org/request/request-promise-native) [![Known Vulnerabilities](https://snyk.io/test/npm/request-promise-native/badge.svg?style=flat-square&maxAge=2592000)](https://snyk.io/test/npm/request-promise-native) # Deprecated! As of Feb 11th 2020, [`request`](https://github.com/request/request) is fully deprecated. No new changes are expected to land. In fact, none have landed for some time. This package is also deprecated because it depends on `request`. Fyi, here is the [reasoning of `request`'s deprecation](https://github.com/request/request/issues/3142) and a [list of alternative libraries](https://github.com/request/request/issues/3143). --- This package is similar to [`request-promise`](https://www.npmjs.com/package/request-promise) but uses native ES6+ promises. Please refer to the [`request-promise` documentation](https://www.npmjs.com/package/request-promise). Everything applies to `request-promise-native` except the following: - Instead of using Bluebird promises this library uses native ES6+ promises. - Native ES6+ promises may have fewer features than Bluebird promises do. In particular, the `.finally(...)` method was not included until Node v10. ## Installation This module is installed via npm: ``` npm install --save request npm install --save request-promise-native ``` `request` is defined as a peer-dependency and thus has to be installed separately. ## Migration from `request-promise` to `request-promise-native` 1. Go through the [migration instructions](https://github.com/request/request-promise#migration-from-v3-to-v4) to upgrade to `request-promise` v4. 2. Ensure that you don't use Bluebird-specific features on the promise returned by your request calls. In particular, you can't use `.finally(...)` anymore. 3. You are done. ## Contributing To set up your development environment: 1. clone the repo to your desktop, 2. in the shell `cd` to the main folder, 3. hit `npm install`, 4. hit `npm install gulp -g` if you haven't installed gulp globally yet, and 5. run `gulp dev`. (Or run `node ./node_modules/.bin/gulp dev` if you don't want to install gulp globally.) `gulp dev` watches all source files and if you save some changes it will lint the code and execute all tests. The test coverage report can be viewed from `./coverage/lcov-report/index.html`. If you want to debug a test you should use `gulp test-without-coverage` to run all tests without obscuring the code by the test coverage instrumentation. ## Change History - v1.0.9 (2020-07-21) - Security fix: bumped `request-promise-core` which bumps `lodash` to `^4.17.19` following [this advisory](https://www.npmjs.com/advisories/1523). - v1.0.8 (2019-11-03) - Security fix: bumped `request-promise-core` which bumps `lodash` to `^4.17.15`. See [vulnerabilty reports](https://snyk.io/vuln/search?q=lodash&type=npm). *(Thanks to @aw-davidson for reporting this in issue [#49](https://github.com/request/request-promise-native/issues/49).)* - v1.0.7 (2019-02-14) - Corrected mistakenly set `tough-cookie` version, now `^2.3.3` *(Thanks to @evocateur for pointing this out.)* - If you installed `request-promise-native@1.0.6` please make sure after the upgrade that `request` and `request-promise-native` use the same physical copy of `tough-cookie`. - v1.0.6 (2019-02-14) - Using stricter `tough-cookie@~2.3.3` to avoid installing `tough-cookie@3` which introduces breaking changes *(Thanks to @jasonmit for pull request [#33](https://github.com/request/request-promise-native/pull/33/))* - Security fix: bumped `lodash` to `^4.17.11`, see [vulnerabilty reports](https://snyk.io/vuln/search?q=lodash&type=npm) - v1.0.5 (2017-09-22) - Upgraded `tough-cookie` to a version without regex DoS vulnerability *(Thanks to @sophieklm for [pull request #13](https://github.com/request/request-promise-native/pull/13))* - v1.0.4 (2017-05-07) - Fix that allows to use `tough-cookie` for [cookie creation](https://github.com/request/request-promise#include-a-cookie) - v1.0.3 (2016-08-08) - Renamed internally used package `@request/promise-core` to `request-promise-core` because there where [too](https://github.com/request/request-promise/issues/137) [many](https://github.com/request/request-promise/issues/141) issues with the scoped package name - v1.0.2 (2016-07-18) - Fix for using with module bundlers like Webpack and Browserify - v1.0.1 (2016-07-17) - Fixed `@request/promise-core` version for safer versioning - v1.0.0 (2016-07-15) - Initial version similar to [`request-promise`](https://www.npmjs.com/package/request-promise) v4 ## License (ISC) In case you never heard about the [ISC license](http://en.wikipedia.org/wiki/ISC_license) it is functionally equivalent to the MIT license. See the [LICENSE file](LICENSE) for details. # 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). # 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). # 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. # 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 ``` [`core-js-compat` package](https://github.com/zloirock/core-js/tree/master/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 or object of minimum environment versions to support filter: /^(es|web)\./, // optional filter - string-prefix, regexp or list of modules version: '3.4', // used `core-js` version, by default - the latest }); console.log(targets); /* => { 'es.symbol.match-all': { ios: '12.2-12.4' }, 'es.array.unscopables.flat': { ios: '12.2-12.4' }, 'es.array.unscopables.flat-map': { ios: '12.2-12.4' }, 'es.math.hypot': { chrome: '77' }, 'es.promise.all-settled': { firefox: '69', ios: '12.2-12.4' }, 'es.promise.finally': { ios: '12.2-12.4' }, 'es.string.match-all': { chrome: '77', firefox: '69', ios: '12.2-12.4' }, 'es.string.replace': { firefox: '69', ios: '12.2-12.4' }, 'es.typed-array.float32-array': { ios: '12.2-12.4' }, 'es.typed-array.float64-array': { ios: '12.2-12.4' }, 'es.typed-array.int8-array': { ios: '12.2-12.4' }, 'es.typed-array.int16-array': { ios: '12.2-12.4' }, 'es.typed-array.int32-array': { ios: '12.2-12.4' }, 'es.typed-array.uint8-array': { ios: '12.2-12.4' }, 'es.typed-array.uint8-clamped-array': { ios: '12.2-12.4' }, 'es.typed-array.uint16-array': { ios: '12.2-12.4' }, 'es.typed-array.uint32-array': { ios: '12.2-12.4' }, 'es.typed-array.from': { ios: '12.2-12.4' }, 'es.typed-array.of': { ios: '12.2-12.4' }, 'web.dom-collections.iterator': { ios: '12.2-12.4' }, 'web.immediate': { chrome: '77', firefox: '69', ios: '12.2-12.4' }, 'web.url': { ios: '12.2-12.4' }, 'web.url.to-json': { ios: '12.2-12.4' }, 'web.url-search-params': { ios: '12.2-12.4' } } */ ``` Additional API: ```js // equals of of the method from the example above require('core-js-compat/compat')({ targets, filter, version }); // => { list: Array<ModuleName>, targets: { [ModuleName]: { [EngineName]: EngineVersion } } } // or require('core-js-compat').compat({ targets, filter, version }); // => { list: Array<ModuleName>, targets: { [ModuleName]: { [EngineName]: EngineVersion } } } // full compat data: require('core-js-compat/data'); // => { [ModuleName]: { [EngineName]: EngineVersion } } // or require('core-js-compat').data; // => { [ModuleName]: { [EngineName]: EngineVersion } } // map of modules by `core-js` entry points: require('core-js-compat/entries'); // => { [EntryPoint]: Array<ModuleName> } // or require('core-js-compat').entries; // => { [EntryPoint]: Array<ModuleName> } // full list of modules: require('core-js-compat/modules'); // => Array<ModuleName> // or require('core-js-compat').modules; // => Array<ModuleName> // the subset of modules which available in the passed `core-js` version: require('core-js-compat/get-modules-list-for-target-version')('3.3'); // => Array<ModuleName> // or require('core-js-compat').getModulesListForTargetVersion('3.3'); // => Array<ModuleName> ``` 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). # babylon-walk Lightweight AST traversal tools for [Babylon] ASTs. Babylon is the parser used by the [Babel] project, which supplies the wonderful [babel-traverse] module for walking Babylon ASTs. Problem is, babel-traverse is very heavyweight, as it is designed to supply utilities to make all sorts of AST transformations possible. For simple AST walking without transformation, babel-traverse brings a lot of overhead. This module loosely implements the API of Acorn parser's [walk module], which is a lightweight AST walker for the ESTree AST format. In my tests, babylon-walk's ancestor walker (the most complex walker provided by this module) is about 8 times faster than babel-traverse, if the visitors are cached and the same AST is used for all runs. It is about 16 times faster if a fresh AST is used every run. [![Dependency Status](https://img.shields.io/david/pugjs/babylon-walk.svg)](https://david-dm.org/pugjs/babylon-walk) [![NPM version](https://img.shields.io/npm/v/babylon-walk.svg)](https://www.npmjs.com/package/babylon-walk) [Babylon]: https://github.com/babel/babylon [Babel]: https://babeljs.io/ [babel-traverse]: https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#toc-babel-traverse [walk module]: https://github.com/ternjs/acorn#distwalkjs ## Installation ```sh $ npm install babylon-walk ``` ## API ```js var walk = require('babylon-walk'); ``` ### walk.simple(node, visitors, state) Do a simple walk over the AST. `node` should be the AST node to walk, and `visitors` an object containing Babel [visitors]. Each visitor function will be called as `(node, state)`, where `node` is the AST node, and `state` is the same `state` passed to `walk.simple`. When `walk.simple` is called with a fresh set of visitors, it will first "explode" the visitors (e.g. expanding `Visitor(node, state) {}` to `Visitor() { enter(node, state) {} }`). This exploding process can take some time, so it is recommended to [cache your visitors] and communicate state leveraging the `state` parameter. (One difference between the linked article and babylon-walk is that the state is only accessible through the `state` variable, never as `this`.) All [babel-types] aliases (e.g. `Expression`) and the union syntax (e.g. `'Identifier|AssignmentPattern'(node, state) {}`) work. ### walk.ancestor(node, visitors, state) Do a simple walk over the AST, but memoizing the ancestors of the node and making them available to the visitors. `node` should be the AST node to walk, and `visitors` an object containing Babel [visitors]. Each visitor function will be called as `(node, state, ancestors)`, where `node` is the AST node, `state` is the same `state` passed to `walk.ancestor`, and `ancestors` is an array of ancestors to the node (with the outermost node being `[0]` and the current node being `[ancestors.length - 1]`). If `state` is not specified in the call to `walk.ancestor`, the `state` parameter will be set to `ancestors`. When `walk.ancestor` is called with a fresh set of visitors, it will first "explode" the visitors (e.g. expanding `Visitor(node, state) {}` to `Visitor() { enter(node, state) {} }`). This exploding process can take some time, so it is recommended to [cache your visitors] and communicate state leveraging the `state` parameter. (One difference between the linked article and babylon-walk is that the state is only accessible through the `state` variable, never as `this`.) All [babel-types] aliases (e.g. `Expression`) and the union syntax (e.g. `'Identifier|AssignmentPattern'(node, state) {}`) work. ### walk.recursive(node, visitors, state) Do a recursive walk over the AST, where the visitors are responsible for continuing the walk on the child nodes of their target node. `node` should be the AST node to walk, and `visitors` an object containing Babel [visitors]. Each visitor function will be called as `(node, state, c)`, where `node` is the AST node, `state` is the same `state` passed to `walk.recursive`, and `c` is a function that takes a single node as argument and continues walking _that_ node. If no visitor for a node is provided, the default walker algorithm will still be used. When `walk.recursive` is called with a fresh set of visitors, it will first "explode" the visitors (e.g. expanding `Visitor(node, state) {}` to `Visitor() { enter(node, state) {} }`). This exploding process can take some time, so it is recommended to [cache your visitors] and communicate state leveraging the `state` parameter. (One difference between the linked article and babylon-walk is that the state is only accessible through the `state` variable, never as `this`.) Unlike other babylon-walk walkers, `walk.recursive` does not call the `exit` visitor, only the `enter` (the default) visitor, of a specific node type. All [babel-types] aliases (e.g. `Expression`) and the union syntax (e.g. `'Identifier|AssignmentPattern'(node, state) {}`) work. In the following example, we are trying to count the number of functions in the outermost scope. This means, that we can simply walk all the statements and increment a counter if it is a function declaration or expression, and then stop walking. Note that we do not specify a visitor for the `Program` node, and the default algorithm for walking `Program` nodes is used (which is what we want). Also of note is how I bring the `visitors` object outside of `countFunctions` so that the object can be cached to improve performance. ```js import * as t from 'babel-types'; import {parse} from 'babylon'; const visitors = { Statement(node, state, c) { if (t.isVariableDeclaration(node)) { for (let declarator of node.declarations) { // Continue walking the declarator c(declarator); } } else if (t.isFunctionDeclaration(node)) { state.counter++; } }, VariableDeclarator(node, state) { if (t.isFunction(node.init)) { state.counter++; } } }; function countFunctions(node) { const state = { counter: 0 }; walk.recursive(node, visitors, state); return state.counter; } const ast = parse(` // Counts var a = () => {}; // Counts function b() { // Doesn't count function c() { } } // Counts const c = function d() {}; `); countFunctions(ast); // = 3 ``` [babel-types]: https://github.com/babel/babel/tree/master/packages/babel-types [cache your visitors]: https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#toc-optimizing-nested-visitors [visitors]: https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#toc-visitors ## Caveat For those of you migrating from Acorn to Babylon, there are a few things to be aware of. 1. The visitor caching suggestions do not apply to Acorn's walk module, but do for babylon-walk. 2. babylon-walk does not provide any of the other functions Acorn's walk module provides (e.g. `make`, `findNode*`). 3. babylon-walk does not use a `base` variable. The walker algorithm is the same as what babel-traverse uses. - That means certain nodes that are not walked by Acorn, such as the `property` property of a non-computed `MemberExpression`, are walked by babylon-walk. ## License MIT # 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][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. ### 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`. <!-- 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 ### 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, no-undef, no-unused-vars --> ```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 ### new createError\[code || name\](\[msg]\)) Create a new error object with the given message `msg`. The error object inherits from `createError.HttpError`. <!-- 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) [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 # <img src="https://github.com/facebook/jest/blob/master/website/static/img/jest.png" height="40" align="right" /> [Plug'n'Play](https://github.com/yarnpkg/rfcs/pull/101) resolver for Jest [![npm version](https://img.shields.io/npm/v/jest-pnp-resolver.svg)](https://www.npmjs.com/package/jest-pnp-resolver) [![node version](https://img.shields.io/node/v/jest-pnp-resolver.svg)](https://www.npmjs.com/package/jest-pnp-resolver) *This plugin is also available for Rollup ([rollup-plugin-pnp-resolve](https://github.com/arcanis/rollup-plugin-pnp-resolve)), TypeScript ([ts-pnp](https://github.com/arcanis/ts-pnp)), and Webpack ([pnp-webpack-plugin](https://github.com/arcanis/pnp-webpack-plugin))* ## Installation ``` yarn add -D jest-pnp-resolver ``` ## Usage As of `jest@^24.4.0` you don't need to manually add this package anymore. The default resolver will already use PnP. Simply add the resolver to your configuration. For example, a minimal `jest.config.js` would be as such: ```js module.exports = { resolver: require.resolve(`jest-pnp-resolver`) }; ``` ## License (MIT) > **Copyright © 2016 Maël Nison** > > 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. ## 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] [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). # 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 <p align="center"> <img src="https://user-images.githubusercontent.com/13700/35731649-652807e8-080e-11e8-88fd-1b2f6d553b2d.png" alt="Nodemon Logo"> </p> # nodemon nodemon is a tool that helps develop node.js based applications by automatically restarting the node application when file changes in the directory are detected. nodemon does **not** require *any* additional changes to your code or method of development. nodemon is a replacement wrapper for `node`. To use `nodemon`, replace the word `node` on the command line when executing your script. [![NPM version](https://badge.fury.io/js/nodemon.svg)](https://npmjs.org/package/nodemon) [![Travis Status](https://travis-ci.org/remy/nodemon.svg?branch=master)](https://travis-ci.org/remy/nodemon) [![Backers on Open Collective](https://opencollective.com/nodemon/backers/badge.svg)](#backers) [![Sponsors on Open Collective](https://opencollective.com/nodemon/sponsors/badge.svg)](#sponsors) # Installation Either through cloning with git or by using [npm](http://npmjs.org) (the recommended way): ```bash npm install -g nodemon ``` And nodemon will be installed globally to your system path. You can also install nodemon as a development dependency: ```bash npm install --save-dev nodemon ``` With a local installation, nodemon will not be available in your system path. Instead, the local installation of nodemon can be run by calling it from within an npm script (such as `npm start`) or using `npx nodemon`. # Usage nodemon wraps your application, so you can pass all the arguments you would normally pass to your app: ```bash nodemon [your node app] ``` For CLI options, use the `-h` (or `--help`) argument: ```bash nodemon -h ``` Using nodemon is simple, if my application accepted a host and port as the arguments, I would start it as so: ```bash nodemon ./server.js localhost 8080 ``` Any output from this script is prefixed with `[nodemon]`, otherwise all output from your application, errors included, will be echoed out as expected. If no script is given, nodemon will test for a `package.json` file and if found, will run the file associated with the *main* property ([ref](https://github.com/remy/nodemon/issues/14)). You can also pass the `inspect` flag to node through the command line as you would normally: ```bash nodemon --inspect ./server.js 80 ``` If you have a `package.json` file for your app, you can omit the main script entirely and nodemon will read the `package.json` for the `main` property and use that value as the app. nodemon will also search for the `scripts.start` property in `package.json` (as of nodemon 1.1.x). Also check out the [FAQ](https://github.com/remy/nodemon/blob/master/faq.md) or [issues](https://github.com/remy/nodemon/issues) for nodemon. ## Automatic re-running nodemon was originally written to restart hanging processes such as web servers, but now supports apps that cleanly exit. If your script exits cleanly, nodemon will continue to monitor the directory (or directories) and restart the script if there are any changes. ## Manual restarting Whilst nodemon is running, if you need to manually restart your application, instead of stopping and restart nodemon, you can type `rs` with a carriage return, and nodemon will restart your process. ## Config files nodemon supports local and global configuration files. These are usually named `nodemon.json` and can be located in the current working directory or in your home directory. An alternative local configuration file can be specified with the `--config <file>` option. The specificity is as follows, so that a command line argument will always override the config file settings: - command line arguments - local config - global config A config file can take any of the command line arguments as JSON key values, for example: ```json { "verbose": true, "ignore": ["*.test.js", "fixtures/*"], "execMap": { "rb": "ruby", "pde": "processing --sketch={{pwd}} --run" } } ``` The above `nodemon.json` file might be my global config so that I have support for ruby files and processing files, and I can run `nodemon demo.pde` and nodemon will automatically know how to run the script even though out of the box support for processing scripts. A further example of options can be seen in [sample-nodemon.md](https://github.com/remy/nodemon/blob/master/doc/sample-nodemon.md) ### package.json If you want to keep all your package configurations in one place, nodemon supports using `package.json` for configuration. Specify the config in the same format as you would for a config file but under `nodemonConfig` in the `package.json` file, for example, take the following `package.json`: ```json { "name": "nodemon", "homepage": "http://nodemon.io", "...": "... other standard package.json values", "nodemonConfig": { "ignore": ["test/*", "docs/*"], "delay": "2500" } } ``` Note that if you specify a `--config` file or provide a local `nodemon.json` any `package.json` config is ignored. *This section needs better documentation, but for now you can also see `nodemon --help config` ([also here](https://github.com/remy/nodemon/blob/master/doc/cli/config.txt))*. ## Using nodemon as a module Please see [doc/requireable.md](doc/requireable.md) ## Using nodemon as child process Please see [doc/events.md](doc/events.md#Using_nodemon_as_child_process) ## Running non-node scripts nodemon can also be used to execute and monitor other programs. nodemon will read the file extension of the script being run and monitor that extension instead of `.js` if there's no `nodemon.json`: ```bash nodemon --exec "python -v" ./app.py ``` Now nodemon will run `app.py` with python in verbose mode (note that if you're not passing args to the exec program, you don't need the quotes), and look for new or modified files with the `.py` extension. ### Default executables Using the `nodemon.json` config file, you can define your own default executables using the `execMap` property. This is particularly useful if you're working with a language that isn't supported by default by nodemon. To add support for nodemon to know about the `.pl` extension (for Perl), the `nodemon.json` file would add: ```json { "execMap": { "pl": "perl" } } ``` Now running the following, nodemon will know to use `perl` as the executable: ```bash nodemon script.pl ``` It's generally recommended to use the global `nodemon.json` to add your own `execMap` options. However, if there's a common default that's missing, this can be merged in to the project so that nodemon supports it by default, by changing [default.js](https://github.com/remy/nodemon/blob/master/lib/config/defaults.js) and sending a pull request. ## Monitoring multiple directories By default nodemon monitors the current working directory. If you want to take control of that option, use the `--watch` option to add specific paths: ```bash nodemon --watch app --watch libs app/server.js ``` Now nodemon will only restart if there are changes in the `./app` or `./libs` directory. By default nodemon will traverse sub-directories, so there's no need in explicitly including sub-directories. Don't use unix globbing to pass multiple directories, e.g `--watch ./lib/*`, it won't work. You need a `--watch` flag per directory watched. ## Specifying extension watch list By default, nodemon looks for files with the `.js`, `.mjs`, `.coffee`, `.litcoffee`, and `.json` extensions. If you use the `--exec` option and monitor `app.py` nodemon will monitor files with the extension of `.py`. However, you can specify your own list with the `-e` (or `--ext`) switch like so: ```bash nodemon -e js,pug ``` Now nodemon will restart on any changes to files in the directory (or subdirectories) with the extensions `.js`, `.pug`. ## Ignoring files By default, nodemon will only restart when a `.js` JavaScript file changes. In some cases you will want to ignore some specific files, directories or file patterns, to prevent nodemon from prematurely restarting your application. This can be done via the command line: ```bash nodemon --ignore lib/ --ignore tests/ ``` Or specific files can be ignored: ```bash nodemon --ignore lib/app.js ``` Patterns can also be ignored (but be sure to quote the arguments): ```bash nodemon --ignore 'lib/*.js' ``` Note that by default, nodemon will ignore the `.git`, `node_modules`, `bower_components`, `.nyc_output`, `coverage` and `.sass-cache` directories and *add* your ignored patterns to the list. If you want to indeed watch a directory like `node_modules`, you need to [override the underlying default ignore rules](https://github.com/remy/nodemon/blob/master/faq.md#overriding-the-underlying-default-ignore-rules). ## Application isn't restarting In some networked environments (such as a container running nodemon reading across a mounted drive), you will need to use the `legacyWatch: true` which enables Chokidar's polling. Via the CLI, use either `--legacy-watch` or `-L` for short: ```bash nodemon -L ``` Though this should be a last resort as it will poll every file it can find. ## Delaying restarting In some situations, you may want to wait until a number of files have changed. The timeout before checking for new file changes is 1 second. If you're uploading a number of files and it's taking some number of seconds, this could cause your app to restart multiple times unnecessarily. To add an extra throttle, or delay restarting, use the `--delay` command: ```bash nodemon --delay 10 server.js ``` For more precision, milliseconds can be specified. Either as a float: ```bash nodemon --delay 2.5 server.js ``` Or using the time specifier (ms): ```bash nodemon --delay 2500ms server.js ``` The delay figure is number of seconds (or milliseconds, if specified) to delay before restarting. So nodemon will only restart your app the given number of seconds after the *last* file change. If you are setting this value in `nodemon.json`, the value will always be interpreted in milliseconds. E.g., the following are equivalent: ```bash nodemon --delay 2.5 { "delay": "2500" } ``` ## Gracefully reloading down your script It is possible to have nodemon send any signal that you specify to your application. ```bash nodemon --signal SIGHUP server.js ``` Your application can handle the signal as follows. ```js process.once("SIGHUP", function () { reloadSomeConfiguration(); }) ``` Please note that nodemon will send this signal to every process in the process tree. If you are using `cluster`, then each workers (as well as the master) will receive the signal. If you wish to terminate all workers on receiving a `SIGHUP`, a common pattern is to catch the `SIGHUP` in the master, and forward `SIGTERM` to all workers, while ensuring that all workers ignore `SIGHUP`. ```js if (cluster.isMaster) { process.on("SIGHUP", function () { for (const worker of Object.values(cluster.workers)) { worker.process.kill("SIGTERM"); } }); } else { process.on("SIGHUP", function() {}) } ``` ## Controlling shutdown of your script nodemon sends a kill signal to your application when it sees a file update. If you need to clean up on shutdown inside your script you can capture the kill signal and handle it yourself. The following example will listen once for the `SIGUSR2` signal (used by nodemon to restart), run the clean up process and then kill itself for nodemon to continue control: ```js process.once('SIGUSR2', function () { gracefulShutdown(function () { process.kill(process.pid, 'SIGUSR2'); }); }); ``` Note that the `process.kill` is *only* called once your shutdown jobs are complete. Hat tip to [Benjie Gillam](http://www.benjiegillam.com/2011/08/node-js-clean-restart-and-faster-development-with-nodemon/) for writing this technique up. ## Triggering events when nodemon state changes If you want growl like notifications when nodemon restarts or to trigger an action when an event happens, then you can either `require` nodemon or add event actions to your `nodemon.json` file. For example, to trigger a notification on a Mac when nodemon restarts, `nodemon.json` looks like this: ```json { "events": { "restart": "osascript -e 'display notification \"app restarted\" with title \"nodemon\"'" } } ``` A full list of available events is listed on the [event states wiki](https://github.com/remy/nodemon/wiki/Events#states). Note that you can bind to both states and messages. ## Pipe output to somewhere else ```js nodemon({ script: ..., stdout: false // important: this tells nodemon not to output to console }).on('readable', function() { // the `readable` event indicates that data is ready to pick up this.stdout.pipe(fs.createWriteStream('output.txt')); this.stderr.pipe(fs.createWriteStream('err.txt')); }); ``` ## Using nodemon in your gulp workflow Check out the [gulp-nodemon](https://github.com/JacksonGariety/gulp-nodemon) plugin to integrate nodemon with the rest of your project's gulp workflow. ## Using nodemon in your Grunt workflow Check out the [grunt-nodemon](https://github.com/ChrisWren/grunt-nodemon) plugin to integrate nodemon with the rest of your project's grunt workflow. ## Pronunciation > nodemon, is it pronounced: node-mon, no-demon or node-e-mon (like pokémon)? Well...I've been asked this many times before. I like that I've been asked this before. There's been bets as to which one it actually is. The answer is simple, but possibly frustrating. I'm not saying (how I pronounce it). It's up to you to call it as you like. All answers are correct :) ## Design principles - Fewer flags is better - Works across all platforms - Fewer features - Let individuals build on top of nodemon - Offer all CLI functionality as an API - Contributions must have and pass tests Nodemon is not perfect, and CLI arguments has sprawled beyond where I'm completely happy, but perhaps it can be reduced a little one day. ## FAQ See the [FAQ](https://github.com/remy/nodemon/blob/master/faq.md) and please add your own questions if you think they would help others. ## Backers Thank you to all [our backers](https://opencollective.com/nodemon#backer)! 🙏 [![nodemon backers](https://opencollective.com/nodemon/backers.svg?width=890)](https://opencollective.com/nodemon#backers) ## Sponsors Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Sponsor this project today ❤️](https://opencollective.com/nodemon#sponsor) [<img src="https://user-images.githubusercontent.com/13700/35731651-677aa3fc-080e-11e8-8580-75fa92db56ec.png" width="200">](https://sparkpo.st/nodemon) [<img src="https://user-images.githubusercontent.com/13700/35731622-421d4466-080e-11e8-8ddc-11c70e1cd79e.png" width="200">](https://mixmax.com) # License MIT [http://rem.mit-license.org](http://rem.mit-license.org) # json-parse-even-better-errors [`json-parse-even-better-errors`](https://github.com/npm/json-parse-even-better-errors) is a Node.js library for getting nicer errors out of `JSON.parse()`, including context and position of the parse errors. It also preserves the newline and indentation styles of the JSON data, by putting them in the object or array in the `Symbol.for('indent')` and `Symbol.for('newline')` properties. ## Install `$ npm install --save json-parse-even-better-errors` ## Table of Contents * [Example](#example) * [Features](#features) * [Contributing](#contributing) * [API](#api) * [`parse`](#parse) ### Example ```javascript const parseJson = require('json-parse-even-better-errors') parseJson('"foo"') // returns the string 'foo' parseJson('garbage') // more useful error message parseJson.noExceptions('garbage') // returns undefined ``` ### Features * Like JSON.parse, but the errors are better. * Strips a leading byte-order-mark that you sometimes get reading files. * Has a `noExceptions` method that returns undefined rather than throwing. * Attaches the newline character(s) used to the `Symbol.for('newline')` property on objects and arrays. * Attaches the indentation character(s) used to the `Symbol.for('indent')` property on objects and arrays. ## Indentation To preserve indentation when the file is saved back to disk, use `data[Symbol.for('indent')]` as the third argument to `JSON.stringify`, and if you want to preserve windows `\r\n` newlines, replace the `\n` chars in the string with `data[Symbol.for('newline')]`. For example: ```js const txt = await readFile('./package.json', 'utf8') const data = parseJsonEvenBetterErrors(txt) const indent = Symbol.for('indent') const newline = Symbol.for('newline') // .. do some stuff to the data .. const string = JSON.stringify(data, null, data[indent]) + '\n' const eolFixed = data[newline] === '\n' ? string : string.replace(/\n/g, data[newline]) await writeFile('./package.json', eolFixed) ``` Indentation is determined by looking at the whitespace between the initial `{` and `[` and the character that follows it. If you have lots of weird inconsistent indentation, then it won't track that or give you any way to preserve it. Whether this is a bug or a feature is debatable ;) ### API #### <a name="parse"></a> `parse(txt, reviver = null, context = 20)` Works just like `JSON.parse`, but will include a bit more information when an error happens, and attaches a `Symbol.for('indent')` and `Symbol.for('newline')` on objects and arrays. This throws a `JSONParseError`. #### <a name="parse"></a> `parse.noExceptions(txt, reviver = null)` Works just like `JSON.parse`, but will return `undefined` rather than throwing an error. #### <a name="jsonparseerror"></a> `class JSONParseError(er, text, context = 20, caller = null)` Extends the JavaScript `SyntaxError` class to parse the message and provide better metadata. Pass in the error thrown by the built-in `JSON.parse`, and the text being parsed, and it'll parse out the bits needed to be helpful. `context` defaults to 20. Set a `caller` function to trim internal implementation details out of the stack trace. When calling `parseJson`, this is set to the `parseJson` function. If not set, then the constructor defaults to itself, so the stack trace will point to the spot where you call `new JSONParseError`. # 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") # regjsgen [![Build status][travis-ci-img]][travis-ci] [![Code coverage status][codecov-img]][codecov] Generate regular expressions from [regjsparser][regjsparser]’s AST. ## Installation ```sh npm i regjsgen ``` ## API ### `regjsgen.generate(ast)` This function accepts an abstract syntax tree representing a regular expression (see [regjsparser][regjsparser]), and returns the generated regular expression string. ```js const regjsparser = require('regjsparser'); const regjsgen = require('regjsgen'); // Generate an AST with `regjsparser`. let ast = regjsparser.parse(regex); // Modify AST // … // Generate `RegExp` string with `regjsgen`. let regex = regjsgen.generate(ast); ``` ## Support Tested in Node.js 0.10, 0.12, 4, 6, 8, 10, 12 and 14.<br> Compatible with regjsparser v0.6.4’s AST. [travis-ci]: https://travis-ci.org/bnjmnt4n/regjsgen [travis-ci-img]: https://travis-ci.org/bnjmnt4n/regjsgen.svg?branch=master [codecov]: https://codecov.io/gh/bnjmnt4n/regjsgen [codecov-img]: https://codecov.io/gh/bnjmnt4n/regjsgen/branch/master/graph/badge.svg [regjsparser]: https://github.com/jviereck/regjsparser # 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) # 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;tj@vision-media.ca&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. # 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')` aws4 ---- [![Build Status](https://api.travis-ci.org/mhart/aws4.png?branch=master)](https://travis-ci.org/github/mhart/aws4) A small utility to sign vanilla Node.js http(s) request options using Amazon's [AWS Signature Version 4](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html). If you want to sign and send AWS requests in a modern browser, or an environment like [Cloudflare Workers](https://developers.cloudflare.com/workers/), then check out [aws4fetch](https://github.com/mhart/aws4fetch) – otherwise you can also bundle this library for use [in older browsers](./browser). The only AWS service that *doesn't* support v4 as of 2020-05-22 is [SimpleDB](https://docs.aws.amazon.com/AmazonSimpleDB/latest/DeveloperGuide/SDB_API.html) (it only supports [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 https = require('https') var aws4 = require('aws4') // to illustrate usage, we'll create a utility function to request and pipe to stdout function request(opts) { https.request(opts, function(res) { res.pipe(process.stdout) }).end(opts.body || '') } // aws4 will sign an options object as you'd pass to http.request, with an AWS service and region var opts = { host: 'my-bucket.s3.us-west-1.amazonaws.com', path: '/my-object', service: 's3', region: 'us-west-1' } // aws4.sign() will sign and modify these options, ready to pass to http.request aws4.sign(opts, { accessKeyId: '', secretAccessKey: '' }) // or it can get credentials from process.env.AWS_ACCESS_KEY_ID, etc aws4.sign(opts) // for most AWS services, aws4 can figure out the service and region if you pass a host opts = { host: 'my-bucket.s3.us-west-1.amazonaws.com', path: '/my-object' } // usually it will add/modify request headers, but you can also sign the query: opts = { host: 'my-bucket.s3.amazonaws.com', path: '/?X-Amz-Expires=12345', signQuery: true } // and for services with simple hosts, aws4 can infer the host from service and region: opts = { service: 'sqs', region: 'us-east-1', path: '/?Action=ListQueues' } // and if you're using us-east-1, it's the default: opts = { service: 'sqs', path: '/?Action=ListQueues' } aws4.sign(opts) 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 request(opts) /* <?xml version="1.0"?> <ListQueuesResponse xmlns="https://queue.amazonaws.com/doc/2012-11-05/"> ... */ // 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/"> ... */ // you 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":[]} ... */ // The raw RequestSigner can be used to generate CodeCommit Git passwords 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() // see example.js for examples with other services ``` API --- ### aws4.sign(requestOptions, [credentials]) Calculates and populates any necessary AWS headers and/or request options on `requestOptions`. Returns `requestOptions` as a convenience for chaining. `requestOptions` is an object holding the same options that the Node.js [http.request](https://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 try to 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 try to be calculated from `hostname` or `host` if not given) - `region` (will try to be calculated from `hostname` or `host` or use `'us-east-1'` if not given) - `signQuery` (to sign the query instead of adding an `Authorization` header, defaults to false) - `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_ACCESS_KEY_ID="<your-access-key-id>" export AWS_SECRET_ACCESS_KEY="<your-secret-access-key>" 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](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html). Installation ------------ With [npm](https://www.npmjs.com/) 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. # lodash v4.17.20 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.20-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. # 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`/`es2019` 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` ## Security Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. [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 # 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) tunnel-agent ============ HTTP proxy tunneling agent. Formerly part of mikeal/request, now a standalone module. # 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. # 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 # PurgeCSS ![David](https://img.shields.io/david/FullHuman/purgecss?style=for-the-badge) ![David](https://img.shields.io/david/dev/FullHuman/purgecss?style=for-the-badge) ![Dependabot](https://img.shields.io/badge/dependabot-enabled-%23024ea4?style=for-the-badge) ![npm](https://img.shields.io/npm/v/purgecss?style=for-the-badge) ![npm](https://img.shields.io/npm/dw/purgecss?style=for-the-badge) ![GitHub](https://img.shields.io/github/license/FullHuman/purgecss?style=for-the-badge) <p align="center"> <img src="https://i.imgur.com/UEiUiJ0.png" height="200" width="200" alt="PurgeCSS logo"/> </p> ## What is PurgeCSS? When you are building a website, chances are that you are using a css framework like Bootstrap, Materializecss, Foundation, etc... But you will only use a small set of the framework and a lot of unused css styles will be included. This is where PurgeCSS comes into play. PurgeCSS analyzes your content and your css files. Then it matches the selectors used in your files with the one in your content files. It removes unused selectors from your css, resulting in smaller css files. ## Version 1 If you are looking for [PurgeCSS 1](https://github.com/FullHuman/purgecss/tree/v1), the documentation is [here](https://v1.purgecss.com) ## Documentation You can find the PurgeCSS documentation on [this website](https://purgecss.com). ### Table of Contents #### PurgeCSS - [Configuration](https://purgecss.com/configuration.html) - [Command Line Interface](https://purgecss.com/CLI.html) - [Programmatic API](https://purgecss.com/api.html) - [Whitelisting](https://purgecss.com/whitelisting.html) - [Extractors](https://purgecss.com/extractors.html) - [Comparison](https://purgecss.com/comparison.html) #### Plugins - [PostCSS](https://purgecss.com/plugins/postcss.html) - [Webpack](https://purgecss.com/plugins/webpack.html) - [Gulp](https://purgecss.com/plugins/gulp.html) - [Grunt](https://purgecss.com/plugins/grunt.html) - [Gatsby](https://purgecss.com/plugins/gatsby.html) #### Guides - [Vue.js](https://purgecss.com/guides/vue.html) - [Nuxt.js](https://purgecss.com/guides/nuxt.html) - [React.js](https://purgecss.com/guides/react.html) - [Next.js](https://purgecss.com/guides/next.html) - [Razzle](https://purgecss.com/guides/razzle.html) ## Getting Started #### Installation ``` npm i --save-dev purgecss ``` ## Usage ```js import PurgeCSS from 'purgecss' const purgeCSSResults = await new Purgecss().purge({ content: ['**/*.html'], css: ['**/*.css'] }) ``` ## Contributing Please read [CONTRIBUTING.md](./../../CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests to us. ## Versioning PurgeCSS use [SemVer](http://semver.org/) for versioning. ## License This project is licensed under the MIT License - see the [LICENSE](./../../LICENSE) file for details. #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 # 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._ # clone [![build status](https://secure.travis-ci.org/pvorb/node-clone.png)](http://travis-ci.org/pvorb/node-clone) [![info badge](https://nodei.co/npm/clone.png?downloads=true&downloadRank=true&stars=true)](http://npm-stat.com/charts.html?package=clone) offers foolproof _deep cloning_ of objects, arrays, numbers, strings etc. in JavaScript. ## Installation npm install clone (It also works with browserify, ender or standalone.) ## Example ~~~ javascript var clone = require('clone'); var a, b; a = { foo: { bar: 'baz' } }; // initial value of a b = clone(a); // clone a -> b a.foo.bar = 'foo'; // change a console.log(a); // show a console.log(b); // show b ~~~ This will print: ~~~ javascript { foo: { bar: 'foo' } } { foo: { bar: 'baz' } } ~~~ **clone** masters cloning simple objects (even with custom prototype), arrays, Date objects, and RegExp objects. Everything is cloned recursively, so that you can clone dates in arrays in objects, for example. ## API `clone(val, circular, depth)` * `val` -- the value that you want to clone, any type allowed * `circular` -- boolean Call `clone` with `circular` set to `false` if you are certain that `obj` contains no circular references. This will give better performance if needed. There is no error if `undefined` or `null` is passed as `obj`. * `depth` -- depth to which the object is to be cloned (optional, defaults to infinity) `clone.clonePrototype(obj)` * `obj` -- the object that you want to clone Does a prototype clone as [described by Oran Looney](http://oranlooney.com/functional-javascript/). ## Circular References ~~~ javascript var a, b; a = { hello: 'world' }; a.myself = a; b = clone(a); console.log(b); ~~~ This will print: ~~~ javascript { hello: "world", myself: [Circular] } ~~~ So, `b.myself` points to `b`, not `a`. Neat! ## Test npm test ## Caveat Some special objects like a socket or `process.stdout`/`stderr` are known to not be cloneable. If you find other objects that cannot be cloned, please [open an issue](https://github.com/pvorb/node-clone/issues/new). ## Bugs and Issues If you encounter any bugs or issues, feel free to [open an issue at github](https://github.com/pvorb/node-clone/issues) or send me an email to <paul@vorba.ch>. I also always like to hear from you, if you’re using my code. ## License Copyright © 2011-2015 [Paul Vorbach](http://paul.vorba.ch/) and [contributors](https://github.com/pvorb/node-clone/graphs/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, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## 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 ``` # CSSStyleDeclaration A Node JS implementation of the CSS Object Model [CSSStyleDeclaration interface](https://www.w3.org/TR/cssom-1/#the-cssstyledeclaration-interface). [![NpmVersion](https://img.shields.io/npm/v/cssstyle.svg)](https://www.npmjs.com/package/cssstyle) [![Build Status](https://travis-ci.org/jsdom/cssstyle.svg?branch=master)](https://travis-ci.org/jsdom/cssstyle) [![codecov](https://codecov.io/gh/jsdom/cssstyle/branch/master/graph/badge.svg)](https://codecov.io/gh/jsdom/cssstyle) --- #### Background This package is an extension of the CSSStyleDeclaration class in Nikita Vasilyev's [CSSOM](https://github.com/NV/CSSOM) with added support for CSS 2 & 3 properties. The primary use case is for testing browser code in a Node environment. It was originally created by Chad Walker, it is now maintaind by Jon Sakas and other open source contributors. Bug reports and pull requests are welcome. 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 # 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. # 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). # Pirates [![Version][version-badge]][npm-link] [![Build Status][build-badge]][build-link] [![Coverage][codecov-badge]][codecov-link] [![Commitizen friendly][cz-badge]][cz-link] [![semantic-release][sr-badge]][sr-link] [![MIT License][license-badge]][license-link] ### Properly hijack require [version-badge]: https://img.shields.io/npm/v/pirates.svg "npm version" [downloads-badge]: https://img.shields.io/npm/dm/pirates.svg "npm downloads" [npm-link]: http://npm.im/pirates "npm" [codecov-badge]: https://img.shields.io/codecov/c/github/ariporad/pirates/master.svg?style=flat "codecov" [codecov-link]: https://codecov.io/gh/ariporad/pirates "codecov" [license-badge]: https://img.shields.io/npm/l/express.svg "MIT License" [license-link]: http://ariporad.mit-license.org "MIT License" [build-badge]: https://travis-ci.org/ariporad/pirates.svg "Travis CI Build Status" [build-link]: https://travis-ci.org/ariporad/pirates "Travis CI Build Status" [cz-badge]: https://img.shields.io/badge/commitizen-friendly-brightgreen.svg "Commitizen friendly" [cz-link]: http://commitizen.github.io/cz-cli/ "Commitizen friendly" [sr-badge]: https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg [sr-link]: https://github.com/semantic-release/semantic-release ## Why? Two reasons: 1. Babel and istanbul were breaking each other. 2. Everyone seemed to re-invent the wheel on this, and everyone wanted a solution that was DRY, simple, easy to use, and made everything Just Work™, while allowing multiple require hooks, in a fashion similar to calling `super`. For some context, see [the Babel issue thread][] which started this all, then [the nyc issue thread][], where discussion was moved (as we began to discuss just using the code nyc had developed), and finally to [#1][issue-1] where discussion was finally moved. [the Babel issue thread]: https://github.com/babel/babel/pull/3062 "Babel Issue Thread" [the nyc issue thread]: https://github.com/bcoe/nyc/issues/70 "NYC Issue Thread" [issue-1]: https://github.com/ariporad/pirates/issues/1 "Issue #1" ## Installation npm install --save pirates ## Usage Using pirates is really easy: ```javascript // my-module/register.js const addHook = require('pirates').addHook; // Or if you use ES modules // import { addHook } from 'pirates'; function matcher(filename) { // Here, you can inspect the filename to determine if it should be hooked or // not. Just return a truthy/falsey. Files in node_modules are automatically ignored, // unless otherwise specified in options (see below). // TODO: Implement your logic here return true; } const revert = addHook( (code, filename) => code.replace('@@foo', 'console.log(\'foo\');'), { exts: ['.js'], matcher } ); // And later, if you want to un-hook require, you can just do: revert(); ``` ## API ### pirates.addHook(hook, [opts={ [matcher: true], [exts: ['.js']], [ignoreNodeModules: true] }]); Add a require hook. `hook` must be a function that takes `(code, filename)`, and returns the modified code. `opts` is an optional options object. Available options are: `matcher`, which is a function that accepts a filename, and returns a truthy value if the file should be hooked (defaults to a function that always returns true), falsey if otherwise; `exts`, which is an array of extensions to hook, they should begin with `.` (defaults to `['.js']`); `ignoreNodeModules`, if true, any file in a `node_modules` folder wont be hooked (the matcher also wont be called), if false, then the matcher will be called for any files in `node_modules` (defaults to true). ## Projects that use Pirates See the [wiki page](https://github.com/ariporad/pirates/wiki/Projects-using-Pirates). If you add Pirates to your project, (And you should! It works best if everyone uses it. Then we can have a happy world full of happy require hooks!), please add yourself to the wiki. ## License [MIT](http://ariporad.mit-license.org) # 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 # 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. # 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> [![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). ## Stable A stable array sort, because `Array#sort()` is not guaranteed stable. MIT licensed. [![Node.js CI](https://secure.travis-ci.org/Two-Screen/stable.png)](http://travis-ci.org/Two-Screen/stable) [![Browser CI](http://ci.testling.com/Two-Screen/stable.png)](http://ci.testling.com/Two-Screen/stable) #### From npm Install with: ```sh npm install stable ``` Then use it in Node.js or some other CommonJS environment as: ```js const stable = require('stable') ``` #### From the browser Include [`stable.js`] or the minified version [`stable.min.js`] in your page, then call `stable()`. [`stable.js`]: https://raw.github.com/Two-Screen/stable/master/stable.js [`stable.min.js`]: https://raw.github.com/Two-Screen/stable/master/stable.min.js #### Usage The default sort is, as with `Array#sort`, lexicographical: ```js stable(['foo', 'bar', 'baz']) // => ['bar', 'baz', 'foo'] stable([10, 1, 5]) // => [1, 10, 5] ``` Unlike `Array#sort`, the default sort is **NOT** in-place. To do an in-place sort, use `stable.inplace`, which otherwise works the same: ```js const arr = [10, 1, 5] stable(arr) === arr // => false stable.inplace(arr) === arr // => true ``` A comparator function can be specified: ```js // Regular sort() compatible comparator, that returns a number. // This demonstrates the default behavior. const lexCmp = (a, b) => String(a).localeCompare(b) stable(['foo', 'bar', 'baz'], lexCmp) // => ['bar', 'baz', 'foo'] // Boolean comparator. Sorts `b` before `a` if true. // This demonstrates a simple way to sort numerically. const greaterThan = (a, b) => a > b stable([10, 1, 5], greaterThan) // => [1, 5, 10] ``` #### License Copyright (C) 2018 Angry Bytes and 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. # 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._ # call-me-maybe [![Build Status](https://travis-ci.org/limulus/call-me-maybe.svg?branch=master)](https://travis-ci.org/limulus/call-me-maybe) Let your JS API users either give you a callback or receive a promise. ## Usage ```javascript var maybe = require("call-me-maybe") module.exports = function asyncFunc (cb) { return maybe(cb, new Promise(function(resolve, reject) { // ... })) } ``` ## API ### maybe(cb, promise) If the callback `cb` is truthy, returns `undefined` and will call `cb` when `promise` is settled. The parameters passed to `cb` are standard error-first: - If `promise` is fulfilled, then it is called with the result of the promise: `cb(null, result)` - If `promise` is rejected, then it is called with the rejection error: `cb(err)` If `cb` is falsey, then `promise` is retuned. # 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. # 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 # 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) - [treport](http://npm.im/tap) - [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 noode-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++) { let parsed try { super.write(parsed) } catch (er) { this.emit('error', er) continue } } if (cb) cb() } } ``` # 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._ <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 # 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._ # 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._ 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>. # UnCSS [![NPM version](https://img.shields.io/npm/v/uncss.svg)](https://www.npmjs.com/package/uncss) [![Linux Build Status](https://img.shields.io/travis/uncss/uncss/master.svg?label=Linux%20build)](https://travis-ci.org/uncss/uncss) [![Windows Build status](https://img.shields.io/appveyor/ci/uncss/uncss/master.svg?label=Windows%20build)](https://ci.appveyor.com/project/uncss/uncss/branch/master) [![Coverage Status](https://img.shields.io/coveralls/uncss/uncss.svg)](https://coveralls.io/r/uncss/uncss?branch=master) [![dependencies Status](https://img.shields.io/david/uncss/uncss.svg)](https://david-dm.org/uncss/uncss) [![devDependencies Status](https://img.shields.io/david/dev/uncss/uncss.svg)](https://david-dm.org/uncss/uncss?type=dev) UnCSS is a tool that removes unused CSS from your stylesheets. It works across multiple files and supports Javascript-injected CSS. ## How The process by which UnCSS removes the unused rules is as follows: 1. The HTML files are loaded by [jsdom](https://github.com/tmpvar/jsdom) and JavaScript is executed. 2. All the stylesheets are parsed by [PostCSS](https://github.com/postcss/postcss). 3. `document.querySelector` filters out selectors that are not found in the HTML files. 4. The remaining rules are converted back to CSS. **Please note:** - UnCSS cannot be run on non-HTML pages, such as templates or PHP files. If you need to run UnCSS against your templates, you should probably generate example HTML pages from your templates, and run uncss on those generated files; or run a live local dev server, and point uncss at that. - UnCSS only runs the Javascript that is run on page load. It does not (and cannot) handle Javascript that runs on user interactions like button clicks. You must use the `ignore` option to preserve classes that are added by Javascript on user interaction. ## Installation ```shell npm install -g uncss ``` ## Usage ### Online Server - [https://uncss-online.com/](https://uncss-online.com/) - Unofficial server, very convenient for testing or one-off usage! ### Within Node.js ```js var uncss = require('uncss'); var files = ['my', 'array', 'of', 'HTML', 'files', 'or', 'http://urls.com'], options = { banner : false, csspath : '../public/css/', htmlroot : 'public', ignore : ['#added_at_runtime', /test\-[0-9]+/], ignoreSheets : [/fonts.googleapis/], inject : function(window) { window.document.querySelector('html').classList.add('no-csscalc', 'csscalc'); }, jsdom : { userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X)', }, media : ['(min-width: 700px) handheld and (orientation: landscape)'], raw : 'h1 { color: green }', report : false, strictSSL : true, stylesheets : ['lib/bootstrap/dist/css/bootstrap.css', 'src/public/css/main.css'], timeout : 1000, uncssrc : '.uncssrc', userAgent : 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X)', }; uncss(files, options, function (error, output) { console.log(output); }); /* Look Ma, no options! */ uncss(files, function (error, output) { console.log(output); }); /* Specifying raw HTML */ var rawHtml = '...'; uncss(rawHtml, options, function (error, output) { console.log(output); }); ``` ### At build-time UnCSS can also be used in conjunction with other JavaScript build systems, such as [Grunt](https://github.com/gruntjs/grunt), [Broccoli](https://github.com/broccolijs/broccoli#readme) or [Gulp](https://github.com/gulpjs/gulp)! - [grunt-uncss](https://github.com/uncss/grunt-uncss) – Thanks to [@addyosmani](https://github.com/addyosmani) - [gulp-uncss](https://github.com/ben-eb/gulp-uncss) – Thanks to [@ben-eb](https://github.com/ben-eb) - [broccoli-uncss](https://github.com/sindresorhus/broccoli-uncss) - Thanks to [@sindresorhus](https://github.com/sindresorhus) ### From the command line ```txt Usage: uncss [options] <file or URL, ...> e.g. uncss https://getbootstrap.com/docs/3.3/examples/jumbotron/ > stylesheet.css Options: -h, --help output usage information -V, --version output the version number -i, --ignore <selector, ...> Do not remove given selectors -m, --media <media_query, ...> Process additional media queries -C, --csspath <path> Relative path where the CSS files are located -s, --stylesheets <file, ...> Specify additional stylesheets to process -S, --ignoreSheets <selector, ...> Do not include specified stylesheets -r, --raw <string> Pass in a raw string of CSS -t, --timeout <milliseconds> Wait for JS evaluation -H, --htmlroot <folder> Absolute paths' root location -u, --uncssrc <file> Load these options from <file> -n, --noBanner Disable banner -a, --userAgent <string> Use a custom user agent string -I, --inject <file> Path to javascript file to be executed before uncss runs -o, --output <file> Path to write resulting CSS to ``` **Note that you can pass both local file paths (which are processed by [glob](https://github.com/isaacs/node-glob)) and URLs to the program.** - **banner** (boolean, default: `true`): Whether a banner should be prepended before each file block in the processed CSS. - **csspath** (string): Path where the CSS files are related to the HTML files. By default, UnCSS uses the path specified in the `<link rel="stylesheet" href="path/to/file.css"/>`. - **htmlroot** (string): Where the project root is. Useful for example if you have HTML that references _local_ files with root-relative URLs, i.e. `href="/css/style.css"`. - **ignore** (string[]): provide a list of selectors that should not be removed by UnCSS. For example, styles added by user interaction with the page (hover, click), since those are not detectable by UnCSS yet. Both literal names and regex patterns are recognized. Otherwise, you can add a comment before specific selectors: ```css /* uncss:ignore */ .selector1 { /* this rule will be ignored */ } .selector2 { /* this will NOT be ignored */ } /* uncss:ignore start */ /* all rules in here will be ignored */ /* uncss:ignore end */ ``` - **ignoreSheets** (string[] | RegExp[]): Do not process these stylesheets, e.g. Google fonts. Accepts strings or regex patterns. - **inject** (string / function(window)): Path to a local javascript file which is executed before uncss runs. A function can also be passed directly in. Example inject.js file ```js 'use strict'; module.exports = function(window) { window.document.querySelector('html').classList.add('no-csscalc', 'csscalc'); }; ``` Example of passing inject as a function ```js { inject: function(window){ window.document.querySelector('html').classList.add('no-csscalc', 'csscalc'); } } ``` - **jsdom** (object) (Supported only by API): Supply the options used to create the JSDOM pages ([https://github.com/jsdom/jsdom](https://github.com/jsdom/jsdom)). At the moment, `config.resources` is not yet supported. - **media** (string[]): By default UnCSS processes only stylesheets with media query `_all_`, `_screen_`, and those without one. Specify here which others to include. - **raw** (string): Give the task a raw string of CSS in addition to the existing stylesheet options; useful in scripting when your CSS hasn't yet been written to disk. - **report** (boolean, default: `true`): Return the report object in callback. - **strictSSL** (boolean, default: `true`): Disable SSL verification when retrieving html source - **stylesheets** (string[]): Use these stylesheets instead of those extracted from the HTML files. Prepend paths with the `file://` protocol to force use of local stylesheets, otherwise paths will be resolved as a browser would for an anchor tag `href` on the HTML page. - **timeout** (number): Specify how long to wait for the JS to be loaded. - **uncssrc** (string): Load all options from a JSON file. Regular expressions for the `ignore` and `ignoreSheets` options should be wrapped in quotation marks. Example uncssrc file: ```json { "ignore": [ ".unused", "/^#js/" ], "stylesheets": [ "css/override.css" ] } ``` - **userAgent** (String, default: `'uncss'`): The user agent string that jsdom should send when requesting pages. May be useful when loading markup from services which use user agent based device detection to serve custom markup to mobile devices. Defaults to `uncss`. ### As a PostCSS Plugin UnCSS can be used as a [PostCSS](https://github.com/postcss/postcss) Plugin. ```js postcss([ require('uncss').postcssPlugin ]); ``` See [PostCSS docs](https://github.com/postcss/postcss) for examples for your environment. **Note:** Depending on your environment, you might not be able to use uncss as a PostCSS plugin since the plugin is not directly exported. In such cases, use the wrapper library [postcss-uncss](https://github.com/RyanZim/postcss-uncss). #### Options - **html** (string[]): provide a list of html files to parse for selectors and elements. Usage of [globs](https://github.com/isaacs/node-glob) is allowed. - **ignore** (string[] | RegExp[]): provide a list of selectors that should not be removed by UnCSS. For example, styles added by user interaction with the page (hover, click), since those are not detectable by UnCSS yet. Both literal names and regex patterns are recognized. Otherwise, you can add a comment before specific selectors in your CSS: ```css /* uncss:ignore */ .selector1 { /* this rule will be ignored */ } .selector2 { /* this will NOT be ignored */ } ``` ##### Example Configuration ```js { html: ['index.html', 'about.html', 'team/*.html'], ignore: ['.fade'] } ``` ## License Copyright (c) 2019 Giacomo Martino. See the [LICENSE](/LICENSE.md) file for license rights and limitations (MIT). # levenary [![npm-version](https://img.shields.io/npm/v/levenary.svg)](https://www.npmjs.com/package/levenary) [![github-actions](https://github.com/tanhauhau/levenary/workflows/CI/badge.svg)](https://github.com/tanhauhau/levenary/actions) > Given a string, A and an array of strings XS, return the string X from XS whose Levenshtein distance from A is minimal. ## Install ``` $ npm install levenary ``` ## Usage ```js import levenary from 'levenary'; levenary('cat', ['cow', 'dog', 'pig']); //=> 'cow' ``` ## Why `levenary`? 1. Based on [leven](https://github.com/sindresorhus/leven), the fastest JS implementation of the [Levenshtein distance algorithm](https://en.wikipedia.org/wiki/Levenshtein_distance) 1. Only 1 API. Simple and clean. If you want more, please use [didyoumean2](https://www.npmjs.com/package/didyoumean2). 1. [Flow](http://flow.org/) and [TypeScript](http://typescriptlang.org/) support. ## Benchmark ``` $ npm run bench ``` ``` 311,915 op/s » levenary 74,030 op/s » didyoumean 141,423 op/s » didyoumean2 ``` # 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/master.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. # BSER Binary Serialization BSER is a binary serialization scheme that can be used as an alternative to JSON. BSER uses a framed encoding that makes it simpler to use to stream a sequence of encoded values. It is intended to be used for local-IPC only and strings are represented as binary with no specific encoding; this matches the convention employed by most operating system filename storage. For more details about the serialization scheme see [Watchman's docs](https://facebook.github.io/watchman/docs/bser.html). ## API ```js var bser = require('bser'); ``` ### bser.loadFromBuffer The is the synchronous decoder; given an input string or buffer, decodes a single value and returns it. Throws an error if the input is invalid. ```js var obj = bser.loadFromBuffer(buf); ``` ### bser.dumpToBuffer Synchronously encodes a value as BSER. ```js var encoded = bser.dumpToBuffer(['hello']); console.log(bser.loadFromBuffer(encoded)); // ['hello'] ``` ### BunserBuf The asynchronous decoder API is implemented in the BunserBuf object. You may incrementally append data to this object and it will emit the decoded values via its `value` event. ```js var bunser = new bser.BunserBuf(); bunser.on('value', function(obj) { console.log(obj); }); ``` Then in your socket `data` event: ```js bunser.append(buf); ``` ## Example Read BSER from socket: ```js var bunser = new bser.BunserBuf(); bunser.on('value', function(obj) { console.log('data from socket', obj); }); var socket = net.connect('/socket'); socket.on('data', function(buf) { bunser.append(buf); }); ``` Write BSER to socket: ```js socket.write(bser.dumpToBuffer(obj)); ``` # 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) aws-sign ======== AWS signing. Originally pulled from LearnBoost/knox, maintained as vendor in request, now a standalone module. # jest-docblock `jest-docblock` is a package that can extract and parse a specially-formatted comment called a "docblock" at the top of a file. A docblock looks like this: ```js /** * Stuff goes here! */ ``` Docblocks can contain pragmas, which are words prefixed by `@`: ```js /** * Pragma incoming! * * @flow */ ``` Pragmas can also take arguments: ```js /** * Check this out: * * @myPragma it is so cool */ ``` `jest-docblock` can: - extract the docblock from some code as a string - parse a docblock string's pragmas into an object - print an object and some comments back to a string ## Installation ```sh # with yarn $ yarn add jest-docblock # with npm $ npm install jest-docblock ``` ## Usage ```js const code = ` /** * Everything is awesome! * * @everything is:awesome * @flow */ export const everything = Object.create(null); export default function isAwesome(something) { return something === everything; } `; const { extract, strip, parse, parseWithComments, print, } = require('jest-docblock'); const docblock = extract(code); console.log(docblock); // "/**\n * Everything is awesome!\n * \n * @everything is:awesome\n * @flow\n */" const stripped = strip(code); console.log(stripped); // "export const everything = Object.create(null);\n export default function isAwesome(something) {\n return something === everything;\n }" const pragmas = parse(docblock); console.log(pragmas); // { everything: "is:awesome", flow: "" } const parsed = parseWithComments(docblock); console.log(parsed); // { comments: "Everything is awesome!", pragmas: { everything: "is:awesome", flow: "" } } console.log(print({pragmas, comments: 'hi!'})); // /**\n * hi!\n *\n * @everything is:awesome\n * @flow\n */; ``` ## API Documentation ### `extract(contents: string): string` Extracts a docblock from some file contents. Returns the docblock contained in `contents`. If `contents` did not contain a docblock, it will return the empty string (`""`). ### `strip(contents: string): string` Strips the top docblock from a file and return the result. If a file does not have a docblock at the top, then return the file unchanged. ### `parse(docblock: string): {[key: string]: string | string[] }` Parses the pragmas in a docblock string into an object whose keys are the pragma tags and whose values are the arguments to those pragmas. ### `parseWithComments(docblock: string): { comments: string, pragmas: {[key: string]: string | string[]} }` Similar to `parse` except this method also returns the comments from the docblock. Useful when used with `print()`. ### `print({ comments?: string, pragmas?: {[key: string]: string | string[]} }): string` Prints an object of key-value pairs back into a docblock. If `comments` are provided, they will be positioned on the top of the docblock. # 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 # 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;christopher.s.dickinson@gmail.com&gt; - Release GPG key: 9554F04D7259F04124DE6B476D5A82AC7E37093B * **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) &lt;calvin.metcalf@gmail.com&gt; - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 * **Rod Vagg** ([@rvagg](https://github.com/rvagg)) &lt;rod@vagg.org&gt; - Release GPG key: DD8F2338BAE7501E3DD5AC78C273792F7D83545D * **Sam Newman** ([@sonewman](https://github.com/sonewman)) &lt;newmansam@outlook.com&gt; * **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) &lt;mathiasbuus@gmail.com&gt; * **Domenic Denicola** ([@domenic](https://github.com/domenic)) &lt;d@domenic.me&gt; * **Matteo Collina** ([@mcollina](https://github.com/mcollina)) &lt;matteo.collina@gmail.com&gt; - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E * **Irina Shestak** ([@lrlna](https://github.com/lrlna)) &lt;shestak.irina@gmail.com&gt; email-addresses.js ================== An RFC 5322 email address parser. v 3.1.0 What? ----- Want to see if something could be an email address? Want to grab the display name or just the address out of a string? Put your regexes down and use this parser! This library does not validate email addresses - we can't really do that without sending an email. However, it attempts to parse addresses using the (fairly liberal) grammar specified in RFC 5322. You can use this to check if user input looks like an email address. Note carefully though - this parser supports all features of RFC 5322, which means that `"Bob Example" <bob@example.com>` is a valid email address. If you just want to validate the `bob@example.com` part, that is RFC 5321, for which you want to use something like node-address-rfc2821. Why use this? ------------- Use this library because you can be sure it really respects the RFC: - The functions in the recursive decent parser match up with the productions in the RFC - The productions from the RFC are written above each function for easy verification - Tests include all of the test cases from the [is_email](https://github.com/dominicsayers/isemail) project, which are extensive Installation ------------ npm install email-addresses Example ------- ``` $ node > addrs = require("email-addresses") { [Function: parse5322] parseOneAddress: [Function: parseOneAddressSimple], parseAddressList: [Function: parseAddressListSimple] } > addrs.parseOneAddress('"Jack Bowman" <jack@fogcreek.com>') { parts: { name: [Object], address: [Object], local: [Object], domain: [Object] }, name: 'Jack Bowman', address: 'jack@fogcreek.com', local: 'jack', domain: 'fogcreek.com' } > addrs.parseAddressList('jack@fogcreek.com, Bob <bob@example.com>') [ { parts: { name: null, address: [Object], local: [Object], domain: [Object] }, name: null, address: 'jack@fogcreek.com', local: 'jack', domain: 'fogcreek.com' }, { parts: { name: [Object], address: [Object], local: [Object], domain: [Object] }, name: 'Bob', address: 'bob@example.com', local: 'bob', domain: 'example.com' } ] > addrs("jack@fogcreek.com") { ast: { name: 'address-list', tokens: 'jack@fogcreek.com', semantic: 'jack@fogcreek.com', children: [ [Object] ] }, addresses: [ { node: [Object], parts: [Object], name: null, address: 'jack@fogcreek.com', local: 'jack', domain: 'fogcreek.com' } ] } > addrs("bogus") null ``` API --- `obj = addrs(opts)` =================== Call the module directly as a function to get access to the AST. Returns null for a failed parse (an invalid address). Options: * `string` - An email address to parse. Parses as `address-list`, a list of email addresses separated by commas. * `object` with the following keys: * `input` - An email address to parse. Required. * `rfc6532` - Enable rfc6532 support (unicode in email addresses). Default: `false`. * `partial` - Allow a failed parse to return the AST it managed to produce so far. Default: `false`. * `simple` - Return just the address or addresses parsed. Default: `false`. * `strict` - Turn off features of RFC 5322 marked "Obsolete". Default: `false`. * `rejectTLD` - Require at least one `.` in domain names. Default: `false`. * `startAt` - Start the parser at one of `address-list`, `from`, `sender`, `reply-to`. Default: `address-list`. Returns an object with the following properties: * `ast` - the full AST of the parse. * `addresses` - array of addresses found. Each has the following properties: * `parts` - components of the AST that make up the address. * `type` - The type of the node, e.g. `mailbox`, `address`, `group`. * `name` - The extracted name from the email. e.g. parsing `"Bob" <bob@example.com>` will give `Bob` for the `name`. * `address` - The full email address. e.g. parsing the above will give `bob@example.com` for the `address`. * `local` - The local part. e.g. parsing the above will give `bob` for `local`. * `domain` - The domain part. e.g. parsing the above will give `example.com` for `domain`. Note if `simple` is set, the return will be an array of addresses rather than the object above. Note that addresses can contain a `group` address, which in contrast to the `address` objects will simply contain two properties: a `name` and `addresses` which is an array of the addresses in the group. You can identify groups because they will have a `type` of `group`. A group looks something like this: `Managing Partners:ben@example.com,carol@example.com;` `obj = addrs.parseOneAddress(opts)` =================================== Parse a single email address. Operates similarly to `addrs(opts)`, with the exception that `rfc6532` and `simple` default to `true`. Returns a single address object as described above. If you set `simple: false` the returned object includes a `node` object that contains the AST for the address. `obj = addrs.parseAddressList(opts)` ==================================== Parse a list of email addresses separated by comma. Operates similarly to `addrs(opts)`, with the exception that `rfc6532` and `simple` default to `true`. Returns a list of address objects as described above. If you set `simple: false` each address will include a `node` object that containst the AST for the address. `obj = addrs.parseFrom(opts)` ============================= Parse an email header "From:" address (specified as mailbox-list or address-list). Operates similarly to `addrs(opts)`, with the exception that `rfc6532` and `simple` default to `true`. Returns a list of address objects as described above. If you set `simple: false` each address will include a `node` object that containst the AST for the address. `obj = addrs.parseSender(opts)` =============================== Parse an email header "Sender:" address (specified as mailbox or address). Operates similarly to `addrs(opts)`, with the exception that `rfc6532` and `simple` default to `true`. Returns a single address object as described above. If you set `simple: false` the returned object includes a `node` object that contains the AST for the address. `obj = addrs.parseReplyTo(opts)` ================================ Parse an email header "Reply-To:" address (specified as address-list). Operates identically to `addrs.parseAddressList(opts)`. Usage ----- If you want to simply check whether an address or address list parses, you'll want to call the following functions and check whether the results are null or not: ```parseOneAddress``` for a single address and ```parseAddressList``` for multiple addresses. If you want to examine the parsed address, for example to extract a name or address, you have some options. The object returned by ```parseOneAddress``` has four helper values on it: ```name```, ```address```, ```local```, and ```domain```. See the example above to understand is actually returned. (These are equivalent to ```parts.name.semantic```, ```parts.address.semantic```, etc.) These values try to be smart about collapsing whitespace, quotations, and excluding RFC 5322 comments. If you desire, you can also obtain the raw parsed tokens or semantic tokens for those fields. The ```parts``` value is an object referencing nodes in the AST generated. Nodes in the AST have two values of interest here, ```tokens``` and ```semantic```. ``` > a = addrs.parseOneAddress('Jack Bowman <jack@fogcreek.com >') > a.parts.name.tokens 'Jack Bowman ' > a.name 'Jack Bowman' > a.parts.name.semantic 'Jack Bowman ' > a.parts.address.tokens 'jack@fogcreek.com ' > a.address 'jack@fogcreek.com' > a.parts.address.semantic 'jack@fogcreek.com' ``` If you need to, you can inspect the AST directly. The entire AST is returned when calling the module's function. References ---------- - http://tools.ietf.org/html/rfc5322 - https://tools.ietf.org/html/rfc6532 - https://tools.ietf.org/html/rfc6854 - http://code.google.com/p/isemail/ Props ----- Many thanks to [Dominic Sayers](https://github.com/dominicsayers) and his documentation and tests for the [is_email](https://github.com/dominicsayers/isemail) function which helped greatly in writing this parser. License ------- Licensed under the MIT License. See the LICENSE file. # 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._ # 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 = require('setprototypeof') ``` # fastparse A very simple and stupid parser, based on a statemachine and regular expressions. It's not intended for complex languages. It's intended to easily write a simple parser for a simple language. ## Usage Pass a description of statemachine to the constructor. The description must be in this form: ``` javascript new Parser(description) description is { // The key is the name of the state // The value is an object containing possible transitions "state-name": { // The key is a regular expression // If the regular expression matches the transition is executed // The value can be "true", a other state name or a function "a": true, // true will make the parser stay in the current state "b": "other-state-name", // a string will make the parser transit to a new state "[cde]": function(match, index, matchLength) { // "match" will be the matched string // "index" will be the position in the complete string // "matchLength" will be "match.length" // "this" will be the "context" passed to the "parse" method" // A new state name (string) can be returned return "other-state-name"; }, "([0-9]+)(\\.[0-9]+)?": function(match, first, second, index, matchLength) { // groups can be used in the regular expression // they will match to arguments "first", "second" }, // the parser stops when it cannot match the string anymore // order of keys is the order in which regular expressions are matched // if the javascript runtime preserves the order of keys in an object // (this is not standardized, but it's a de-facto standard) } } ``` The statemachine is compiled down to a single regular expression per state. So basically the parsing work is delegated to the (native) regular expression logic of the javascript runtime. ``` javascript Parser.prototype.parse(initialState: String, parsedString: String, context: Object) ``` `initialState`: state where the parser starts to parse. `parsedString`: the string which should be parsed. `context`: an object which can be used to save state and results. Available as `this` in transition functions. returns `context` ## Example ``` javascript var Parser = require("fastparse"); // A simple parser that extracts @licence ... from comments in a JS file var parser = new Parser({ // The "source" state "source": { // matches comment start "/\\*": "comment", "//": "linecomment", // this would be necessary for a complex language like JS // but omitted here for simplicity // "\"": "string1", // "\'": "string2", // "\/": "regexp" }, // The "comment" state "comment": { "\\*/": "source", "@licen[cs]e\\s((?:[^*\n]|\\*+[^*/\n])*)": function(match, licenseText) { this.licences.push(licenseText.trim()); } }, // The "linecomment" state "linecomment": { "\n": "source", "@licen[cs]e\\s(.*)": function(match, licenseText) { this.licences.push(licenseText.trim()); } } }); var licences = parser.parse("source", sourceCode, { licences: [] }).licences; console.log(licences); ``` ## License MIT (http://www.opensource.org/licenses/mit-license.php) # 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;calvin.metcalf@gmail.com&gt; - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 * **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) &lt;mathiasbuus@gmail.com&gt; * **Matteo Collina** ([@mcollina](https://github.com/mcollina)) &lt;matteo.collina@gmail.com&gt; - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E * **Irina Shestak** ([@lrlna](https://github.com/lrlna)) &lt;shestak.irina@gmail.com&gt; * **Yoshua Wyuts** ([@yoshuawuyts](https://github.com/yoshuawuyts)) &lt;yoshuawuyts@gmail.com&gt; [sauce]: https://saucelabs.com # CSSStyleDeclaration [![NpmVersion](https://img.shields.io/npm/v/cssstyle.svg)](https://www.npmjs.com/package/cssstyle) [![Build Status](https://travis-ci.org/jsakas/CSSStyleDeclaration.svg?branch=master)](https://travis-ci.org/jsakas/CSSStyleDeclaration) CSSStyleDeclaration is a work-a-like to the CSSStyleDeclaration class in Nikita Vasilyev's [CSSOM](https://github.com/NV/CSSOM). I made it so that when using [jQuery in node](https://github.com/tmtk75/node-jquery) setting css attributes via $.fn.css() would work. node-jquery uses [jsdom](https://github.com/tmpvar/jsdom) to create a DOM to use in node. jsdom uses CSSOM for styling, and CSSOM's implementation of the [CSSStyleDeclaration](http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration) doesn't support [CSS2Properties](http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSS2Properties), which is how jQuery's [$.fn.css()](http://api.jquery.com/css/) operates. ### Why not just issue a pull request? Well, NV wants to keep CSSOM fast (which I can appreciate) and CSS2Properties aren't required by the standard (though every browser has the interface). So I figured the path of least resistance would be to just modify this one class, publish it as a node module (that requires CSSOM) and then make a pull request of jsdom to use it. ### How do I test this code? `npm test` should do the trick, assuming you have the dev dependencies installed: ``` $ npm test tests ✔ Verify Has Properties ✔ Verify Has Functions ✔ Verify Has Special Properties ✔ Test From Style String ✔ Test From Properties ✔ Test Shorthand Properties ✔ Test width and height Properties and null and empty strings ✔ Test Implicit Properties ``` # 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) # 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 (emn178@gmail.com) # 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._ [![NPM][npm]][npm-url] [![Deps][deps]][deps-url] [![Tests][build]][build-url] [![Coverage][cover]][cover-url] [![Standard Code Style][code-style]][code-style-url] [![Chat][chat]][chat-url] # PostHTML <img align="right" width="220" height="200" title="PostHTML" src="http://posthtml.github.io/posthtml/logo.svg"> PostHTML is a tool for transforming HTML/XML with JS plugins. PostHTML itself is very small. It includes only a HTML parser, a HTML node tree API and a node tree stringifier. All HTML transformations are made by plugins. And these plugins are just small plain JS functions, which receive a HTML node tree, transform it, and return a modified tree. For more detailed information about PostHTML in general take a look at the [docs][docs]. ### Dependencies | Name | Status | Description | |:----:|:------:|:-----------:| |[posthtml-parser][parser]|[![npm][parser-badge]][parser-npm]| Parser HTML/XML to PostHTMLTree | |[posthtml-render][render]|[![npm][render-badge]][render-npm]| Render PostHTMLTree to HTML/XML | [docs]: https://github.com/posthtml/posthtml/blob/master/docs [parser]: https://github.com/posthtml/posthtml-parser [parser-badge]: https://img.shields.io/npm/v/posthtml-parser.svg [parser-npm]: https://npmjs.com/package/posthtml-parser [render]: https://github.com/posthtml/posthtml-render [render-badge]: https://img.shields.io/npm/v/posthtml-render.svg [render-npm]: https://npmjs.com/package/posthtml-render ## Install ```bash npm i -D posthtml ``` ## Usage ### API **Sync** ```js import posthtml from 'posthtml' const html = ` <component> <title>Super Title</title> <text>Awesome Text</text> </component> ` const result = posthtml() .use(require('posthtml-custom-elements')()) .process(html, { sync: true }) .html console.log(result) ``` ```html <div class="component"> <div class="title">Super Title</div> <div class="text">Awesome Text</div> </div> ``` > :warning: Async Plugins can't be used in sync mode and will throw an Error. It's recommended to use PostHTML asynchronously whenever possible. **Async** ```js import posthtml from 'posthtml' const html = ` <html> <body> <p class="wow">OMG</p> </body> </html> ` posthtml( [ require('posthtml-to-svg-tags')(), require('posthtml-extend-attrs')({ attrsTree: { '.wow' : { id: 'wow_id', fill: '#4A83B4', 'fill-rule': 'evenodd', 'font-family': 'Verdana' } } }) ]) .process(html/*, options */) .then((result) => console.log(result.html)) ``` ```html <svg xmlns="http://www.w3.org/2000/svg"> <text class="wow" id="wow_id" fill="#4A83B4" fill-rule="evenodd" font-family="Verdana"> OMG </text> </svg> ``` **Directives** ```js import posthtml from 'posthtml' const php = ` <component> <title><?php echo $title; ?></title> <text><?php echo $article; ?></text> </component> ` const result = posthtml() .use(require('posthtml-custom-elements')()) .process(html, { directives: [ { name: '?php', start: '<', end: '>' } ] }) .html console.log(result) ``` ```html <div class="component"> <div class="title"><?php echo $title; ?></div> <div class="text"><?php echo $article; ?></div> </div> ``` ### [CLI](https://npmjs.com/package/posthtml-cli) ```bash npm i posthtml-cli ``` ```json "scripts": { "posthtml": "posthtml -o output.html -i input.html -c config.json" } ``` ```bash npm run posthtml ``` ### [Gulp](https://gulpjs.com) ```bash npm i -D gulp-posthtml ``` ```js import tap from 'gulp-tap' import posthtml from 'gulp-posthtml' import { task, src, dest } from 'gulp' task('html', () => { let path const plugins = [ require('posthtml-include')({ root: `${path}` }) ] const options = {} src('src/**/*.html') .pipe(tap((file) => path = file.path)) .pipe(posthtml(plugins, options)) .pipe(dest('build/')) }) ``` Check [project-stub](https://github.com/posthtml/project-stub) for an example with Gulp ### [Grunt](https://gruntjs.com) ```bash npm i -D grunt-posthtml ``` ```js posthtml: { options: { use: [ require('posthtml-doctype')({ doctype: 'HTML 5' }), require('posthtml-include')({ root: './', encoding: 'utf-8' }) ] }, build: { files: [ { dot: true, cwd: 'html/', src: ['*.html'], dest: 'tmp/', expand: true, } ] } } ``` ### [Webpack](https://webpack.js.org) ```bash npm i -D html-loader posthtml-loader ``` #### v1.x **webpack.config.js** ```js const config = { module: { loaders: [ { test: /\.html$/, loader: 'html!posthtml' } ] }, posthtml: (ctx) => ({ parser: require('posthtml-pug'), plugins: [ require('posthtml-bem')() ] }) } export default config ``` #### v2.x **webpack.config.js** ```js import { LoaderOptionsPlugin } from 'webpack' const config = { module: { rules: [ { test: /\.html$/, use: [ { loader: 'html-loader', options: { minimize: true } }, { loader: 'posthtml-loader' } ] } ] }, plugins: [ new LoaderOptionsPlugin({ options: { posthtml(ctx) { return { parser: require('posthtml-pug'), plugins: [ require('posthtml-bem')() ] } } } }) ] } export default config ``` ### [Rollup](https://rollupjs.org/) ```bash $ npm i rollup-plugin-posthtml -D # or $ npm i rollup-plugin-posthtml-template -D ``` ```js import { join } from 'path'; import posthtml from 'rollup-plugin-posthtml-template'; // or // import posthtml from 'rollup-plugin-posthtml'; import sugarml from 'posthtml-sugarml'; // npm i posthtml-sugarml -D import include from 'posthtml-include'; // npm i posthtml-include -D export default { entry: join(__dirname, 'main.js'), dest: join(__dirname, 'bundle.js'), format: 'iife', plugins: [    posthtml({      parser: sugarml(),      plugins: [include()], template: true // only rollup-plugin-posthtml-template }) ] }; ``` ## Parser ```js import pug from 'posthtml-pug' posthtml().process(html, { parser: pug(options) }).then((result) => result.html) ``` | Name |Status|Description| |:-----|:-----|:----------| |[posthtml-pug][pug]|[![npm][pug-badge]][pug-npm]|Pug Parser| |[sugarml][sugar]|[![npm][sugar-badge]][sugar-npm]|SugarML Parser| [pug]: https://github.com/posthtml/posthtml-pug [pug-badge]: https://img.shields.io/npm/v/posthtml-pug.svg [pug-npm]: https://npmjs.com/package/posthtml-pug [sugar]: https://github.com/posthtml/sugarml [sugar-badge]: https://img.shields.io/npm/v/sugarml.svg [sugar-npm]: https://npmjs.com/package/sugarml ## [Plugins](http://maltsev.github.io/posthtml-plugins) In case you want to develop your own plugin, we recommend using [posthtml-plugin-boilerplate][plugin] for getting started. [plugin]: https://github.com/posthtml/posthtml-plugin-boilerplate #### TEXT | Name |Status|Description| |:-----|:-----|:----------| |[posthtml-md][md]|[![npm][md-badge]][md-npm]|Easily use context-sensitive markdown within HTML| |[posthtml-lorem][lorem]|[![npm][lorem-badge]][lorem-npm]|Add lorem ipsum placeholder text to any document| |[posthtml-retext][text]|[![npm][text-badge]][text-npm]|Extensible system for analysing and manipulating natural language| |[prevent-widows][prevent-widows]|[![npm][prevent-widows-badge]][prevent-widows-npm]|Prevent widows from appearing at the end of paragraphs| [md]: https://github.com/jonathantneal/posthtml-md [md-badge]: https://img.shields.io/npm/v/posthtml-md.svg [md-npm]: https://npmjs.com/package/posthtml-md [text]: https://github.com/voischev/posthtml-retext [text-badge]: https://img.shields.io/npm/v/posthtml-retext.svg [text-npm]: https://npmjs.com/package/posthtml-retext [lorem]: https://github.com/jonathantneal/posthtml-lorem [lorem-badge]: https://img.shields.io/npm/v/posthtml-lorem.svg [lorem-npm]: https://npmjs.com/package/posthtml-lorem [prevent-widows]: https://github.com/bashaus/prevent-widows [prevent-widows-badge]: https://img.shields.io/npm/v/prevent-widows.svg [prevent-widows-npm]: https://npmjs.com/package/prevent-widows #### HTML |Name|Status|Description| |:---|:----:|:----------| |[posthtml-doctype][doctype]|[![npm][doctype-badge]][doctype-npm]|Set !DOCTYPE| |[posthtml-head-elements][head]|[![npm][head-badge]][head-npm]|Include head elements from JSON file| |[posthtml-include][include]|[![npm][include-badge]][include-npm]|Include HTML| |[posthtml-modules][modules]|[![npm][modules-badge]][modules-npm]|Include and process HTML| |[posthtml-extend][extend]|[![npm][extend-badge]][extend-npm]|Extend Layout (Pug-like)| |[posthtml-extend-attrs][attrs]|[![npm][attrs-badge]][attrs-npm]|Extend Attrs| |[posthtml-expressions][exp]|[![npm][exp-badge]][exp-npm]|Template Expressions| |[posthtml-inline-assets][assets]|[![npm][assets-badge]][assets-npm]|Inline external scripts, styles, and images| |[posthtml-static-react][react]|[![npm][react-badge]][react-npm]| Render custom elements as static React components| |[posthtml-custom-elements][elem]|[![npm][elem-badge]][elem-npm]|Use custom elements| |[posthtml-web-component][web]|[![npm][web-badge]][web-npm]|Web Component server-side rendering, Component as a Service (CaaS)| |[posthtml-spaceless][spaceless]|[![npm][spaceless-badge]][spaceless-npm]|Remove whitespace between HTML tags| |[posthtml-cache][cache]|[![npm][cache-badge]][cache-npm]|Add a nanoid to links in you tags| |[posthtml-highlight][highlight]|[![npm][highlight-badge]][highlight-npm]|Syntax highlight code elements| |[posthtml-pseudo][pseudo]|[![npm][pseudo-badge]][pseudo-npm]|Add pseudo selector class names to elements| [cache]: https://github.com/posthtml/posthtml-cache [cache-badge]: https://img.shields.io/npm/v/posthtml-cache.svg [cache-npm]: https://npmjs.com/package/posthtml-cache [spaceless]: https://github.com/posthtml/posthtml-spaceless [spaceless-badge]: https://img.shields.io/npm/v/posthtml-spaceless.svg [spaceless-npm]: https://npmjs.com/package/posthtml-spaceless [doctype]: https://github.com/posthtml/posthtml-doctype [doctype-badge]: https://img.shields.io/npm/v/posthtml-doctype.svg [doctype-npm]: https://npmjs.com/package/posthtml-doctype [head]: https://github.com/TCotton/posthtml-head-elements [head-badge]: https://img.shields.io/npm/v/posthtml-head-elements.svg [head-npm]: https://npmjs.com/package/posthtml-head-elements [include]: https://github.com/posthtml/posthtml-include [include-badge]: https://img.shields.io/npm/v/posthtml-include.svg [include-npm]: https://npmjs.com/package/posthtml-include [modules]: https://github.com/posthtml/posthtml-modules [modules-badge]: https://img.shields.io/npm/v/posthtml-modules.svg [modules-npm]: https://npmjs.com/package/posthtml-modules [content]: https://github.com/posthtml/posthtml-content [content-badge]: https://img.shields.io/npm/v/posthtml-content.svg [content-npm]: https://npmjs.com/package/posthtml-content [exp]: https://github.com/posthtml/posthtml-exp [exp-badge]: https://img.shields.io/npm/v/posthtml-exp.svg [exp-npm]: https://npmjs.com/package/posthtml-exp [extend]: https://github.com/posthtml/posthtml-extend [extend-badge]: https://img.shields.io/npm/v/posthtml-extend.svg [extend-npm]: https://npmjs.com/package/posthtml-extend [attrs]: https://github.com/theprotein/posthtml-extend-attrs [attrs-badge]: https://img.shields.io/npm/v/posthtml-extend-attrs.svg [attrs-npm]: https://npmjs.com/package/posthtml-extend-attrs [assets]: https://github.com/jonathantneal/posthtml-inline-assets [assets-badge]: https://img.shields.io/npm/v/posthtml-inline-assets.svg [assets-npm]: https://npmjs.com/package/posthtml-inline-assets [elem]: https://github.com/posthtml/posthtml-custom-elements [elem-badge]: https://img.shields.io/npm/v/posthtml-custom-elements.svg [elem-npm]: https://npmjs.com/package/posthtml-custom-elements [web]: https://github.com/island205/posthtml-web-component [web-badge]: https://img.shields.io/npm/v/posthtml-web-component.svg [web-npm]: https://npmjs.com/package/posthtml-web-components [prefix]: https://github.com/stevenbenisek/posthtml-prefix-class [prefix-badge]: https://img.shields.io/npm/v/posthtml-prefix-class.svg [prefix-npm]: https://npmjs.com/package/posthtml-prefix-class [react]: https://github.com/rasmusfl0e/posthtml-static-react [react-badge]: https://img.shields.io/npm/v/posthtml-static-react.svg [react-npm]: https://npmjs.com/package/posthtml-static-react [highlight]: https://github.com/caseyWebb/posthtml-highlight [highlight-badge]: https://img.shields.io/npm/v/posthtml-highlight.svg [highlight-npm]: https://npmjs.com/package/posthtml-highlight [pseudo]: https://github.com/kevinkace/posthtml-pseudo [pseudo-badge]: https://img.shields.io/npm/v/posthtml-pseudo.svg [pseudo-npm]: https://npmjs.com/package/posthtml-pseudo #### CSS |Name|Status|Description| |:---|:-----|:----------| |[posthtml-bem][bem]|[![npm][bem-badge]][bem-npm]|Support BEM naming in html structure| |[posthtml-postcss][css]|[![npm][css-badge]][css-npm]|Use [PostCSS][css-gh] in HTML document| |[posthtml-px2rem][px2rem]|[![npm][px2rem-badge]][px2rem-npm]|Change px to rem in Inline CSS| |[posthtml-css-modules][css-modules]|[![npm][css-modules-badge]][css-modules-npm]|Use CSS modules in HTML| |[posthtml-postcss-modules][postcss-modules]|[![npm][postcss-modules-badge]][postcss-modules-npm]|CSS Modules in html| |[posthtml-classes][classes]|[![npm][classes-badge]][classes-npm]|Get a list of classes from HTML| |[posthtml-prefix-class][prefix]|[![npm][prefix-badge]][prefix-npm]|Prefix class names |[posthtml-modular-css][modular]|[![npm][modular-badge]][modular-npm]|Make CSS modular| |[posthtml-inline-css][in]|[![npm][in-badge]][in-npm]|CSS Inliner| |[posthtml-collect-styles][collect-styles]|[![npm][collect-styles-badge]][collect-styles-npm]|Collect styles from html and put it in the head| |[posthtml-collect-inline-styles][collect]|[![npm][collect-badge]][collect-npm]|Collect inline styles and insert to head tag| |[posthtml-style-to-file][style]|[![npm][style-badge]][style-npm]| Save HTML style nodes and attributes to CSS file| |[posthtml-color-shorthand-hex-to-six-digit][hex]|[![npm][hex-badge]][hex-npm]|Enforce all hex color codes to be 6-char long| |[posthtml-minify-classnames][minify]|[![npm][minify-badge]][minify-npm]|Rewrites classnames and ids inside of html and css files to reduce file size.| [bem]: https://github.com/rajdee/posthtml-bem [bem-badge]: https://img.shields.io/npm/v/posthtml-bem.svg [bem-npm]: https://npmjs.com/package/posthtml-bem [css]: https://github.com/posthtml/posthtml-postcss [css-badge]: https://img.shields.io/npm/v/posthtml-postcss.svg [css-npm]: https://npmjs.com/package/posthtml-postcss [css-gh]: https://github.com/postcss/postcss [postcss-modules]: https://github.com/posthtml/posthtml-postcss-modules [postcss-modules-badge]: https://img.shields.io/npm/v/posthtml-postcss-modules.svg [postcss-modules-npm]: https://npmjs.com/package/posthtml-postcss-modules [css-modules]: https://github.com/posthtml/posthtml-css-modules [css-modules-badge]: https://img.shields.io/npm/v/posthtml-css-modules.svg [css-modules-npm]: https://npmjs.com/package/posthtml-css-modules [collect-styles]: https://github.com/posthtml/posthtml-collect-styles [collect-styles-badge]: https://img.shields.io/npm/v/posthtml-collect-styles.svg [collect-styles-npm]: https://npmjs.com/package/posthtml-collect-styles [collect]: https://github.com/totora0155/posthtml-collect-inline-styles [collect-badge]: https://img.shields.io/npm/v/posthtml-collect-inline-styles.svg [collect-npm]: https://npmjs.com/package/posthtml-collect-inline-styles [px2rem]: https://github.com/weixin/posthtml-px2rem [px2rem-badge]: https://img.shields.io/npm/v/posthtml-px2rem.svg [px2rem-npm]: https://npmjs.com/package/posthtml-px2rem [classes]: https://github.com/rajdee/posthtml-classes [classes-badge]: https://img.shields.io/npm/v/posthtml-classes.svg [classes-npm]: https://npmjs.com/package/posthtml-classes [prefix]: https://github.com/stevenbenisek/posthtml-prefix-class [prefix-badge]: https://img.shields.io/npm/v/posthtml-prefix-class.svg [prefix-npm]: https://npmjs.com/package/posthtml-prefix-class [modular]: https://github.com/admdh/posthtml-modular-css [modular-badge]: https://img.shields.io/npm/v/posthtml-modular-css.svg [modular-npm]: https://npmjs.com/package/posthtml-modular-css [in]: https://github.com/posthtml/posthtml-inline-css [in-badge]: https://img.shields.io/npm/v/posthtml-inline-css.svg [in-npm]: https://npmjs.com/package/posthtml-inline-css [style]: https://github.com/posthtml/posthtml-style-to-file [style-badge]: https://img.shields.io/npm/v/posthtml-style-to-file.svg [style-npm]: https://npmjs.com/package/posthtml-style-to-file [hex]: https://github.com/posthtml/posthtml-color-shorthand-hex-to-six-digit [hex-badge]: https://img.shields.io/npm/v/posthtml-color-shorthand-hex-to-six-digit.svg [hex-npm]: https://npmjs.com/package/posthtml-color-shorthand-hex-to-six-digit [minify]: https://github.com/simonlc/posthtml-minify-classnames [minify-badge]: https://img.shields.io/npm/v/posthtml-minify-classnames.svg [minify-npm]: https://npmjs.com/package/posthtml-minify-classnames #### IMG & SVG |Name|Status|Description| |:---|:-----|:----------| |[posthtml-img-autosize][img]|[![npm][img-badge]][img-npm]|Auto setting the width and height of \<img\>| |[posthtml-to-svg-tags][svg]|[![npm][svg-badge]][svg-npm]|Convert html tags to svg equals| |[posthtml-webp][webp]|[![npm][webp-badge]][webp-npm]|Add WebP support for images| |[posthtml-favicons][favicons]|[![npm][favicons-badge]][favicons-npm]|Generate Favicons and add related tags| [img]: https://github.com/posthtml/posthtml-img-autosize [img-badge]: https://img.shields.io/npm/v/posthtml-img-autosize.svg [img-npm]: https://npmjs.com/package/posthtml-img-autosize [svg]: https://github.com/theprotein/posthtml-to-svg-tags [svg-badge]: https://img.shields.io/npm/v/posthtml-to-svg-tags.svg [svg-npm]: https://npmjs.com/package/posthtml-to-svg-tags [webp]: https://github.com/posthtml/posthtml-webp [webp-badge]: https://img.shields.io/npm/v/posthtml-webp.svg [webp-npm]: https://npmjs.com/package/posthtml-webp [favicons]: https://github.com/mohsen1/posthtml-favicons [favicons-badge]: https://img.shields.io/npm/v/posthtml-favicons.svg [favicons-npm]: https://www.npmjs.com/package/posthtml-favicons #### Accessibility |Name|Status|Description| |:---|:-----|:----------| |[posthtml-aria-tabs][aria]|[![npm][aria-badge]][aria-npm]|Write accessible tabs with minimal markup| |[posthtml-alt-always][alt]|[![npm][alt-badge]][alt-npm]|Always add alt attribute for images that don't have it| |[posthtml-schemas][schemas]|[![npm][schemas-badge]][schemas-npm]| Add microdata to your HTML| [alt]: https://github.com/ismamz/posthtml-alt-always [alt-badge]: https://img.shields.io/npm/v/posthtml-alt-always.svg [alt-npm]: https://npmjs.com/package/posthtml-alt-always [aria]: https://github.com/jonathantneal/posthtml-aria-tabs [aria-badge]: https://img.shields.io/npm/v/posthtml-aria-tabs.svg [aria-npm]: https://npmjs.com/package/posthtml-aria-tabs [schemas]: https://github.com/jonathantneal/posthtml-schemas [schemas-badge]: https://img.shields.io/npm/v/posthtml-schemas.svg [schemas-npm]: https://npmjs.com/package/posthtml-schemas #### Optimization |Name|Status|Description| |:---|:-----|:----------| |[posthtml-shorten][shorten]|[![npm][shorten-badge]][shorten-npm]|Shorten URLs in HTML| |[posthtml-uglify][uglify]|[![npm][uglify-badge]][uglify-npm]|Shorten CSS in HTML| |[posthtml-minifier][minifier]|[![npm][minifier-badge]][minifier-npm]|Minify HTML| |[posthtml-remove-attributes][remove]|[![npm][remove-badge]][remove-npm]|Remove attributes unconditionally or with content match| |[posthtml-remove-tags][remove-tags]|[![npm][remove-tags-badge]][remove-tags-npm]|Remove tags with content match| |[posthtml-remove-duplicates][remove-duplicates]|[![npm][remove-duplicates-badge]][remove-duplicates-npm]|Remove duplicate elements from your html| |[posthtml-transformer][transform]|[![npm][transform-badge]][transform-npm]|Process HTML by directives in node attrs, such as inline scripts and styles, remove useless tags, concat scripts and styles etc.| |[htmlnano][nano]|[![npm][nano-badge]][nano-npm]|HTML Minifier| |[posthtml-link-noreferrer][noreferrer]|[![npm][noreferrer-badge]][noreferrer-npm]|Add `rel="noopener"` and `rel="noreferrer"` to all links that contain the attribute `target="_blank"` | |[posthtml-lazyload][lazyload]|[![npm][lazyload-badge]][lazyload-npm]|Add native lazyload attribute| [remove]: https://github.com/princed/posthtml-remove-attributes [remove-badge]: https://img.shields.io/npm/v/posthtml-remove-attributes.svg [remove-npm]: https://npmjs.com/package/posthtml-remove-attributes [remove-tags]: https://github.com/posthtml/posthtml-remove-tags [remove-tags-badge]: https://img.shields.io/npm/v/posthtml-remove-tags.svg [remove-tags-npm]: https://npmjs.com/package/posthtml-remove-tags [remove-duplicates]: https://github.com/canvaskisa/posthtml-remove-duplicates [remove-duplicates-badge]: https://img.shields.io/npm/v/posthtml-remove-duplicates.svg [remove-duplicates-npm]: https://npmjs.com/package/posthtml-remove-duplicates [minifier]: https://github.com/Rebelmail/posthtml-minifier [minifier-badge]: https://img.shields.io/npm/v/posthtml-minifier.svg [minifier-npm]: https://npmjs.com/package/posthtml-minifier [shorten]: https://github.com/Rebelmail/posthtml-shorten [shorten-badge]: https://img.shields.io/npm/v/posthtml-shorten.svg [shorten-npm]: https://npmjs.com/package/posthtml-shorten [uglify]: https://github.com/Rebelmail/posthtml-uglify [uglify-badge]: https://img.shields.io/npm/v/posthtml-uglify.svg [uglify-npm]: https://npmjs.com/package/posthtml-uglify [nano]: https://github.com/maltsev/htmlnano [nano-badge]: https://img.shields.io/npm/v/htmlnano.svg [nano-npm]: https://npmjs.com/package/htmlnano [transform]: https://github.com/flashlizi/posthtml-transformer [transform-badge]: https://img.shields.io/npm/v/posthtml-transformer.svg [transform-npm]: https://npmjs.com/package/posthtml-transformer [noreferrer]: https://github.com/webistomin/posthtml-link-noreferrer [noreferrer-badge]: https://img.shields.io/npm/v/posthtml-link-noreferrer.svg [noreferrer-npm]: https://www.npmjs.com/package/posthtml-link-noreferrer [lazyload]: https://github.com/webistomin/posthtml-lazyload [lazyload-badge]: https://img.shields.io/npm/v/posthtml-link-noreferrer.svg [lazyload-npm]: https://www.npmjs.com/package/posthtml-lazyload #### Workflow |Name|Status|Description| |:---|:-----|:----------| |[posthtml-load-plugins][plugins]|[![npm][plugins-badge]][plugins-npm]|Autoload Plugins |[posthtml-load-options][options]|[![npm][options-badge]][options-npm]|Autoload Options (Parser && Render)| |[posthtml-load-config][config]|[![npm][config-badge]][config-npm]|Autoload Config (Plugins && Options)| |[posthtml-w3c][w3c]|[![npm][w3c-badge]][w3c-npm]|Validate HTML with W3C Validation| |[posthtml-hint][hint]|[![npm][hint-badge]][hint-npm]|Lint HTML with HTML Hint| |[posthtml-tidy][tidy]|[![npm][tidy-badge]][tidy-npm]|Sanitize HTML with HTML Tidy| [options]: https://github.com/posthtml/posthtml-load-options [options-badge]: https://img.shields.io/npm/v/posthtml-load-options.svg [options-npm]: https://npmjs.com/package/posthtml-load-options [plugins]: https://github.com/posthtml/posthtml-load-plugins [plugins-badge]: https://img.shields.io/npm/v/posthtml-load-plugins.svg [plugins-npm]: https://npmjs.com/package/posthtml-load-plugins [config]: https://github.com/posthtml/posthtml-load-config [config-badge]: https://img.shields.io/npm/v/posthtml-load-config.svg [config-npm]: https://npmjs.com/package/posthtml-load-config [tidy]: https://github.com/michael-ciniawsky/posthtml-tidy [tidy-badge]: https://img.shields.io/npm/v/posthtml-tidy.svg [tidy-npm]: https://npmjs.com/package/posthtml-tidy [hint]: https://github.com/posthtml/posthtml-hint [hint-badge]: https://img.shields.io/npm/v/posthtml-hint.svg [hint-npm]: https://npmjs.com/package/posthtml-hint [w3c]: https://github.com/posthtml/posthtml-w3c [w3c-badge]: https://img.shields.io/npm/v/posthtml-w3c.svg [w3c-npm]: https://npmjs.com/package/posthtml-w3c ## Middleware |Name|Status|Description| |:---|:-----|:----------| |[koa-posthtml][koa]|[![npm][koa-badge]][koa-npm]|Koa Middleware| |[hapi-posthtml][hapi]|[![npm][hapi-badge]][hapi-npm]|Hapi Plugin| |[express-posthtml][express]|[![npm][express-badge]][express-npm]|Express Middleware| |[electron-posthtml][electron]|[![npm][electron-badge]][electron-npm]|Electron Plugin| |[metalsmith-posthtml][metalsmith]|[![npm][metalsmith-badge]][metalsmith-npm]|Metalsmith Plugin| [koa]: https://github.com/posthtml/koa-posthtml [koa-badge]: https://img.shields.io/npm/v/koa-posthtml.svg [koa-npm]: https://npmjs.com/package/koa-posthtml [hapi]: https://github.com/posthtml/hapi-posthtml [hapi-badge]: https://img.shields.io/npm/v/hapi-posthtml.svg [hapi-npm]: https://npmjs.com/package/hapi-posthtml [express]: https://github.com/posthtml/express-posthtml [express-badge]: https://img.shields.io/npm/v/express-posthtml.svg [express-npm]: https://npmjs.com/package/express-posthtml [electron]: https://github.com/posthtml/electron-posthtml [electron-badge]: https://img.shields.io/npm/v/electron-posthtml.svg [electron-npm]: https://npmjs.com/package/electron-posthtml [metalsmith]: https://github.com/posthtml/metalsmith-posthtml [metalsmith-badge]: https://img.shields.io/npm/v/metalsmith-posthtml.svg [metalsmith-npm]: https://npmjs.com/package/metalsmith-posthtml ## Maintainers <table> <tbody> <tr> <td align="center"> <img width="150 height="150" src="https://avatars0.githubusercontent.com/u/2789192?s=460&v=4"> <br /> <a href="https://github.com/scrum">Ivan Demidov</a> </td> <td align="center"> <img width="150 height="150" src="https://avatars.githubusercontent.com/u/1510217?v=3&s=150"> <br /> <a href="https://github.com/voischev">Ivan Voischev</a> </td> <td align="center"> <img width="150 height="150" src="https://avatars.githubusercontent.com/u/982072?v=3&s=150"> <br /> <a href="https://github.com/awinogradov">Anton Winogradov</a> </td> <td align="center"> <img width="150 height="150" src="https://avatars.githubusercontent.com/u/677518?v=3&s=150"> <br /> <a href="https://github.com/zxqfox">Alexej Yaroshevich</a> </td> <td align="center"> <img width="150 height="150" src="https://avatars.githubusercontent.com/u/1813468?v=3&s=150"> <br /> <a href="https://github.com/Yeti-or">Vasiliy</a> </td> </tr> <tbody> </table> ## Contributing See [PostHTML Guidelines](https://github.com/posthtml/posthtml/tree/master/docs) and [CONTRIBUTING](CONTRIBUTING.md). ## LICENSE [MIT](LICENSE) [npm]: https://img.shields.io/npm/v/posthtml.svg [npm-url]: https://npmjs.com/package/posthtml [deps]: https://david-dm.org/posthtml/posthtml.svg [deps-url]: https://david-dm.org/posthtml/posthtml [build]: https://travis-ci.org/posthtml/posthtml.svg?branch=master [build-url]: https://travis-ci.org/posthtml/posthtml?branch=master [cover]: https://coveralls.io/repos/posthtml/posthtml/badge.svg?branch=master [cover-url]: https://coveralls.io/r/posthtml/posthtml?branch=master [code-style]: https://img.shields.io/badge/code%20style-standard-yellow.svg [code-style-url]: http://standardjs.com/ [chat]: https://badges.gitter.im/posthtml/posthtml.svg [chat-url]: https://gitter.im/posthtml/posthtml?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge" # 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. # 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;tj@vision-media.ca&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. # Glob To Regular Expression [![Build Status](https://travis-ci.org/fitzgen/glob-to-regexp.png?branch=master)](https://travis-ci.org/fitzgen/glob-to-regexp) Turn a \*-wildcard style glob (`"*.min.js"`) into a regular expression (`/^.*\.min\.js$/`)! To match bash-like globs, eg. `?` for any single-character match, `[a-z]` for character ranges, and `{*.html, *.js}` for multiple alternatives, call with `{ extended: true }`. To obey [globstars `**`](https://github.com/isaacs/node-glob#glob-primer) rules set option `{globstar: true}`. NOTE: This changes the behavior of `*` when `globstar` is `true` as shown below: When `{globstar: true}`: `/foo/**` will match any string that starts with `/foo/` like `/foo/index.htm`, `/foo/bar/baz.txt`, etc. Also, `/foo/**/*.txt` will match any string that starts with `/foo/` and ends with `.txt` like `/foo/bar.txt`, `/foo/bar/baz.txt`, etc. Whereas `/foo/*` (single `*`, not a globstar) will match strings that start with `/foo/` like `/foo/index.htm`, `/foo/baz.txt` but will not match strings that contain a `/` to the right like `/foo/bar/baz.txt`, `/foo/bar/baz/qux.dat`, etc. Set flags on the resulting `RegExp` object by adding the `flags` property to the option object, eg `{ flags: "i" }` for ignoring case. ## Install npm install glob-to-regexp ## Usage ```js var globToRegExp = require('glob-to-regexp'); var re = globToRegExp("p*uck"); re.test("pot luck"); // true re.test("pluck"); // true re.test("puck"); // true re = globToRegExp("*.min.js"); re.test("http://example.com/jquery.min.js"); // true re.test("http://example.com/jquery.min.js.map"); // false re = globToRegExp("*/www/*.js"); re.test("http://example.com/www/app.js"); // true re.test("http://example.com/www/lib/factory-proxy-model-observer.js"); // true // Extended globs re = globToRegExp("*/www/{*.js,*.html}", { extended: true }); re.test("http://example.com/www/app.js"); // true re.test("http://example.com/www/index.html"); // true ``` ## License Copyright (c) 2013, Nick Fitzgerald 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. 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. <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 # 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._ # 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 # caniuse-api [![Build Status](https://travis-ci.org/Nyalab/caniuse-api.svg?branch=master)](https://travis-ci.org/Nyalab/caniuse-api) [![Build status](https://ci.appveyor.com/api/projects/status/6j3na522bv3bxfa5/branch/master?svg=true)](https://ci.appveyor.com/project/MoOx/caniuse-api/branch/master) request the caniuse data to check browsers compatibilities ## Installation ```console $ yarn add caniuse-api ``` ## Usage ```js const caniuse = require('caniuse-api') caniuse.getSupport('border-radius') caniuse.isSupported('border-radius', 'ie 8, ie 9') caniuse.setBrowserScope('> 5%, last 1 version') caniuse.getSupport('border-radius') // ... ``` ## API #### `caniuse.getSupport(feature)` _ask since which browsers versions a feature is available_ * `y`: Since which browser version the feature is available * `n`: Up to which browser version the feature is unavailable * `a`: Up to which browser version the feature is partially supported * `x`: Up to which browser version the feature is prefixed ```js caniuse.getSupport('border-radius', true) /* { and_chr: { y: 67 }, and_ff: { y: 60 }, and_qq: { y: 1.2 }, and_uc: { y: 11.8 }, android: { y: 2.1, x: 2.1 }, baidu: { y: 7.12 }, chrome: { y: 4, x: 4 }, edge: { y: 12 }, firefox: { a: 2, x: 3.6, y: 3 }, ie: { n: 8, y: 9 }, ie_mob: { y: 10 }, ios_saf: { y: 3.2, x: 3.2 }, op_mini: {}, op_mob: { n: 10, y: 11 }, opera: { n: 10, y: 10.5 }, safari: { y: 3.1, x: 4 }, samsung: { y: 4 } } */ ``` #### `caniuse.isSupported(feature, browsers)` _ask if a feature is supported by some browsers_ ```js caniuse.isSupported('border-radius', 'ie 8, ie 9') // false caniuse.isSupported('border-radius', 'ie 9') // true ``` #### `caniuse.find(query)` _search for a caniuse feature name_ Ex: ```js caniuse.find('radius') // ['border-radius'] caniuse.find('nothingness') // [] caniuse.find('css3') /* [ 'css3-attr', 'css3-boxsizing', 'css3-colors', 'css3-cursors-grab', 'css3-cursors-newer', 'css3-cursors', 'css3-tabsize' ] */ ``` #### `caniuse.getLatestStableBrowsers()` _get the current version for each browser_ ```js caniuse.getLatestStableBrowsers() /* [ 'and_chr 67', 'and_ff 60', 'and_qq 1.2', 'and_uc 11.8', 'android 67', 'baidu 7.12', 'bb 10', 'chrome 67', 'edge 17', 'firefox 61', 'ie 11', 'ie_mob 11', 'ios_saf 11.3-11.4', 'op_mini all', 'op_mob 46', 'opera 53', 'safari 11.1', 'samsung 7.2' ] */ ``` #### `caniuse.getBrowserScope()` _returns a list of browsers currently used for the scope of operations_ ```js caniuse.getBrowserScope() /* [ 'and_chr', 'and_ff', 'and_qq', 'and_uc', 'android', 'baidu', 'chrome', 'edge', 'firefox', 'ie', 'ie_mob', 'ios_saf', 'op_mini', 'op_mob', 'opera', 'safari', 'samsung' ] */ ``` #### `caniuse.setBrowserScope(browserscope)` _if you do not like the default browser scope, you can set it globally by using this method_ * browserscope should be a 'autoprefixer' formatted string ```js caniuse.setBrowserScope('> 5%, last 2 versions, Firefox ESR, Opera 12.1') ``` --- ## [Changelog](CHANGELOG.md) ## [License](LICENSE) # 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 <!-- eslint-disable no-unused-vars --> ```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. 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. [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 # 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) { 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 <div align="center"> <h1>jest-each</h1> Jest Parameterised Testing </div> <hr /> [![version](https://img.shields.io/npm/v/jest-each.svg?style=flat-square)](https://www.npmjs.com/package/jest-each) [![downloads](https://img.shields.io/npm/dm/jest-each.svg?style=flat-square)](http://npm-stat.com/charts.html?package=jest-each&from=2017-03-21) [![MIT License](https://img.shields.io/npm/l/jest-each.svg?style=flat-square)](https://github.com/facebook/jest/blob/master/LICENSE) A parameterised testing library for [Jest](https://jestjs.io/) inspired by [mocha-each](https://github.com/ryym/mocha-each). jest-each allows you to provide multiple arguments to your `test`/`describe` which results in the test/suite being run once per row of parameters. ## Features - `.test` to runs multiple tests with parameterised data - Also under the alias: `.it` - `.test.only` to only run the parameterised tests - Also under the aliases: `.it.only` or `.fit` - `.test.skip` to skip the parameterised tests - Also under the aliases: `.it.skip` or `.xit` or `.xtest` - `.test.concurrent` - Also under the alias: `.it.concurrent` - `.test.concurrent.only` - Also under the alias: `.it.concurrent.only` - `.test.concurrent.skip` - Also under the alias: `.it.concurrent.skip` - `.describe` to runs test suites with parameterised data - `.describe.only` to only run the parameterised suite of tests - Also under the aliases: `.fdescribe` - `.describe.skip` to skip the parameterised suite of tests - Also under the aliases: `.xdescribe` - Asynchronous tests with `done` - Unique test titles with [`printf` formatting](https://nodejs.org/api/util.html#util_util_format_format_args): - `%p` - [pretty-format](https://www.npmjs.com/package/pretty-format). - `%s`- String. - `%d`- Number. - `%i` - Integer. - `%f` - Floating point value. - `%j` - JSON. - `%o` - Object. - `%#` - Index of the test case. - `%%` - single percent sign ('%'). This does not consume an argument. - 🖖 Spock like data tables with [Tagged Template Literals](#tagged-template-literal-of-rows) --- - [Demo](#demo) - [Installation](#installation) - [Importing](#importing) - APIs - [Array of Rows](#array-of-rows) - [Usage](#usage) - [Tagged Template Literal of rows](#tagged-template-literal-of-rows) - [Usage](#usage-1) ## Demo #### Tests without jest-each ![Current jest tests](assets/default-demo.gif) #### Tests can be re-written with jest-each to: **`.test`** ![Current jest tests](assets/test-demo.gif) **`.test` with Tagged Template Literals** ![Current jest tests](assets/tagged-template-literal.gif) **`.describe`** ![Current jest tests](assets/describe-demo.gif) ## Installation `npm i --save-dev jest-each` `yarn add -D jest-each` ## Importing jest-each is a default export so it can be imported with whatever name you like. ```js // es6 import each from 'jest-each'; ``` ```js // es5 const each = require('jest-each').default; ``` ## Array of rows ### API #### `each([parameters]).test(name, testFn)` ##### `each`: - parameters: `Array` of Arrays with the arguments that are passed into the `testFn` for each row - _Note_ If you pass in a 1D array of primitives, internally it will be mapped to a table i.e. `[1, 2, 3] -> [[1], [2], [3]]` ##### `.test`: - name: `String` the title of the `test`. - Generate unique test titles by positionally injecting parameters with [`printf` formatting](https://nodejs.org/api/util.html#util_util_format_format_args): - `%p` - [pretty-format](https://www.npmjs.com/package/pretty-format). - `%s`- String. - `%d`- Number. - `%i` - Integer. - `%f` - Floating point value. - `%j` - JSON. - `%o` - Object. - `%#` - Index of the test case. - `%%` - single percent sign ('%'). This does not consume an argument. - testFn: `Function` the test logic, this is the function that will receive the parameters of each row as function arguments #### `each([parameters]).describe(name, suiteFn)` ##### `each`: - parameters: `Array` of Arrays with the arguments that are passed into the `suiteFn` for each row - _Note_ If you pass in a 1D array of primitives, internally it will be mapped to a table i.e. `[1, 2, 3] -> [[1], [2], [3]]` ##### `.describe`: - name: `String` the title of the `describe` - Generate unique test titles by positionally injecting parameters with [`printf` formatting](https://nodejs.org/api/util.html#util_util_format_format_args): - `%p` - [pretty-format](https://www.npmjs.com/package/pretty-format). - `%s`- String. - `%d`- Number. - `%i` - Integer. - `%f` - Floating point value. - `%j` - JSON. - `%o` - Object. - `%#` - Index of the test case. - `%%` - single percent sign ('%'). This does not consume an argument. - suiteFn: `Function` the suite of `test`/`it`s to be ran, this is the function that will receive the parameters in each row as function arguments ### Usage #### `.test(name, fn)` Alias: `.it(name, fn)` ```js each([ [1, 1, 2], [1, 2, 3], [2, 1, 3], ]).test('returns the result of adding %d to %d', (a, b, expected) => { expect(a + b).toBe(expected); }); ``` #### `.test.only(name, fn)` Aliases: `.it.only(name, fn)` or `.fit(name, fn)` ```js each([ [1, 1, 2], [1, 2, 3], [2, 1, 3], ]).test.only('returns the result of adding %d to %d', (a, b, expected) => { expect(a + b).toBe(expected); }); ``` #### `.test.skip(name, fn)` Aliases: `.it.skip(name, fn)` or `.xit(name, fn)` or `.xtest(name, fn)` ```js each([ [1, 1, 2], [1, 2, 3], [2, 1, 3], ]).test.skip('returns the result of adding %d to %d', (a, b, expected) => { expect(a + b).toBe(expected); }); ``` #### `.test.concurrent(name, fn)` Aliases: `.it.concurrent(name, fn)` ```js each([ [1, 1, 2], [1, 2, 3], [2, 1, 3], ]).test.concurrent( 'returns the result of adding %d to %d', (a, b, expected) => { expect(a + b).toBe(expected); }, ); ``` #### `.test.concurrent.only(name, fn)` Aliases: `.it.concurrent.only(name, fn)` ```js each([ [1, 1, 2], [1, 2, 3], [2, 1, 3], ]).test.concurrent.only( 'returns the result of adding %d to %d', (a, b, expected) => { expect(a + b).toBe(expected); }, ); ``` #### `.test.concurrent.skip(name, fn)` Aliases: `.it.concurrent.skip(name, fn)` ```js each([ [1, 1, 2], [1, 2, 3], [2, 1, 3], ]).test.concurrent.skip( 'returns the result of adding %d to %d', (a, b, expected) => { expect(a + b).toBe(expected); }, ); ``` #### Asynchronous `.test(name, fn(done))` Alias: `.it(name, fn(done))` ```js each([['hello'], ['mr'], ['spy']]).test( 'gives 007 secret message: %s', (str, done) => { const asynchronousSpy = message => { expect(message).toBe(str); done(); }; callSomeAsynchronousFunction(asynchronousSpy)(str); }, ); ``` #### `.describe(name, fn)` ```js each([ [1, 1, 2], [1, 2, 3], [2, 1, 3], ]).describe('.add(%d, %d)', (a, b, expected) => { test(`returns ${expected}`, () => { expect(a + b).toBe(expected); }); test('does not mutate first arg', () => { a + b; expect(a).toBe(a); }); test('does not mutate second arg', () => { a + b; expect(b).toBe(b); }); }); ``` #### `.describe.only(name, fn)` Aliases: `.fdescribe(name, fn)` ```js each([ [1, 1, 2], [1, 2, 3], [2, 1, 3], ]).describe.only('.add(%d, %d)', (a, b, expected) => { test(`returns ${expected}`, () => { expect(a + b).toBe(expected); }); }); ``` #### `.describe.skip(name, fn)` Aliases: `.xdescribe(name, fn)` ```js each([ [1, 1, 2], [1, 2, 3], [2, 1, 3], ]).describe.skip('.add(%d, %d)', (a, b, expected) => { test(`returns ${expected}`, () => { expect(a + b).toBe(expected); }); }); ``` --- ## Tagged Template Literal of rows ### API #### `each[tagged template].test(name, suiteFn)` ```js each` a | b | expected ${1} | ${1} | ${2} ${1} | ${2} | ${3} ${2} | ${1} | ${3} `.test('returns $expected when adding $a to $b', ({a, b, expected}) => { expect(a + b).toBe(expected); }); ``` ##### `each` takes a tagged template string with: - First row of variable name column headings separated with `|` - One or more subsequent rows of data supplied as template literal expressions using `${value}` syntax. ##### `.test`: - name: `String` the title of the `test`, use `$variable` in the name string to inject test values into the test title from the tagged template expressions - To inject nested object values use you can supply a keyPath i.e. `$variable.path.to.value` - testFn: `Function` the test logic, this is the function that will receive the parameters of each row as function arguments #### `each[tagged template].describe(name, suiteFn)` ```js each` a | b | expected ${1} | ${1} | ${2} ${1} | ${2} | ${3} ${2} | ${1} | ${3} `.describe('$a + $b', ({a, b, expected}) => { test(`returns ${expected}`, () => { expect(a + b).toBe(expected); }); test('does not mutate first arg', () => { a + b; expect(a).toBe(a); }); test('does not mutate second arg', () => { a + b; expect(b).toBe(b); }); }); ``` ##### `each` takes a tagged template string with: - First row of variable name column headings separated with `|` - One or more subsequent rows of data supplied as template literal expressions using `${value}` syntax. ##### `.describe`: - name: `String` the title of the `test`, use `$variable` in the name string to inject test values into the test title from the tagged template expressions - To inject nested object values use you can supply a keyPath i.e. `$variable.path.to.value` - suiteFn: `Function` the suite of `test`/`it`s to be ran, this is the function that will receive the parameters in each row as function arguments ### Usage #### `.test(name, fn)` Alias: `.it(name, fn)` ```js each` a | b | expected ${1} | ${1} | ${2} ${1} | ${2} | ${3} ${2} | ${1} | ${3} `.test('returns $expected when adding $a to $b', ({a, b, expected}) => { expect(a + b).toBe(expected); }); ``` #### `.test.only(name, fn)` Aliases: `.it.only(name, fn)` or `.fit(name, fn)` ```js each` a | b | expected ${1} | ${1} | ${2} ${1} | ${2} | ${3} ${2} | ${1} | ${3} `.test.only('returns $expected when adding $a to $b', ({a, b, expected}) => { expect(a + b).toBe(expected); }); ``` #### `.test.skip(name, fn)` Aliases: `.it.skip(name, fn)` or `.xit(name, fn)` or `.xtest(name, fn)` ```js each` a | b | expected ${1} | ${1} | ${2} ${1} | ${2} | ${3} ${2} | ${1} | ${3} `.test.skip('returns $expected when adding $a to $b', ({a, b, expected}) => { expect(a + b).toBe(expected); }); ``` #### Asynchronous `.test(name, fn(done))` Alias: `.it(name, fn(done))` ```js each` str ${'hello'} ${'mr'} ${'spy'} `.test('gives 007 secret message: $str', ({str}, done) => { const asynchronousSpy = message => { expect(message).toBe(str); done(); }; callSomeAsynchronousFunction(asynchronousSpy)(str); }); ``` #### `.describe(name, fn)` ```js each` a | b | expected ${1} | ${1} | ${2} ${1} | ${2} | ${3} ${2} | ${1} | ${3} `.describe('$a + $b', ({a, b, expected}) => { test(`returns ${expected}`, () => { expect(a + b).toBe(expected); }); test('does not mutate first arg', () => { a + b; expect(a).toBe(a); }); test('does not mutate second arg', () => { a + b; expect(b).toBe(b); }); }); ``` #### `.describe.only(name, fn)` Aliases: `.fdescribe(name, fn)` ```js each` a | b | expected ${1} | ${1} | ${2} ${1} | ${2} | ${3} ${2} | ${1} | ${3} `.describe.only('$a + $b', ({a, b, expected}) => { test(`returns ${expected}`, () => { expect(a + b).toBe(expected); }); }); ``` #### `.describe.skip(name, fn)` Aliases: `.xdescribe(name, fn)` ```js each` a | b | expected ${1} | ${1} | ${2} ${1} | ${2} | ${3} ${2} | ${1} | ${3} `.describe.skip('$a + $b', ({a, b, expected}) => { test(`returns ${expected}`, () => { expect(a + b).toBe(expected); }); }); ``` ## License MIT # 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). # Determine the Encoding of a HTML Byte Stream This package implements the HTML Standard's [encoding sniffing algorithm](https://html.spec.whatwg.org/multipage/syntax.html#encoding-sniffing-algorithm) in all its glory. The most interesting part of this is how it pre-scans the first 1024 bytes in order to search for certain `<meta charset>`-related patterns. ```js const htmlEncodingSniffer = require("html-encoding-sniffer"); const fs = require("fs"); const htmlBuffer = fs.readFileSync("./html-page.html"); const sniffedEncoding = htmlEncodingSniffer(htmlBuffer); ``` The returned value will be a canonical [encoding name](https://encoding.spec.whatwg.org/#names-and-labels) (not a label). You might then combine this with the [whatwg-encoding](https://github.com/jsdom/whatwg-encoding) package to decode the result: ```js const whatwgEncoding = require("whatwg-encoding"); const htmlString = whatwgEncoding.decode(htmlBuffer, sniffedEncoding); ``` ## Options You can pass two potential options to `htmlEncodingSniffer`: ```js const sniffedEncoding = htmlEncodingSniffer(htmlBuffer, { transportLayerEncodingLabel, defaultEncoding }); ``` These represent two possible inputs into the [encoding sniffing algorithm](https://html.spec.whatwg.org/multipage/syntax.html#encoding-sniffing-algorithm): - `transportLayerEncodingLabel` is an encoding label that is obtained from the "transport layer" (probably a HTTP `Content-Type` header), which overrides everything but a BOM. - `defaultEncoding` is the ultimate fallback encoding used if no valid encoding is supplied by the transport layer, and no encoding is sniffed from the bytes. It defaults to `"windows-1252"`, as recommended by the algorithm's table of suggested defaults for "All other locales" (including the `en` locale). ## Credits This package was originally based on the excellent work of [@nicolashenry](https://github.com/nicolashenry), [in jsdom](https://github.com/tmpvar/jsdom/blob/16fd85618f2705d181232f6552125872a37164bc/lib/jsdom/living/helpers/encoding.js). It has since been pulled out into this separate package. # 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._ # 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) # 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). # node-touch For all your node touching needs. ## Installing ```bash npm install touch ``` ## CLI Usage: See `man touch` This package exports a binary called `nodetouch` that works mostly like the unix builtin `touch(1)`. ## API Usage: ```javascript var touch = require("touch") ``` Gives you the following functions: * `touch(filename, options, cb)` * `touch.sync(filename, options)` * `touch.ftouch(fd, options, cb)` * `touch.ftouchSync(fd, options)` All the `options` objects are optional. All the async functions return a Promise. If a callback function is provided, then it's attached to the Promise. ## Options * `force` like `touch -f` Boolean * `time` like `touch -t <date>` Can be a Date object, or any parseable Date string, or epoch ms number. * `atime` like `touch -a` Can be either a Boolean, or a Date. * `mtime` like `touch -m` Can be either a Boolean, or a Date. * `ref` like `touch -r <file>` Must be path to a file. * `nocreate` like `touch -c` Boolean If neither `atime` nor `mtime` are set, then both values are set. If one of them is set, then the other is not. ## cli This package creates a `nodetouch` command line executable that works very much like the unix builtin `touch(1)` 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. # 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. # 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] } ``` # 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._ # 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. # Determine the Encoding of a HTML Byte Stream This package implements the HTML Standard's [encoding sniffing algorithm](https://html.spec.whatwg.org/multipage/syntax.html#encoding-sniffing-algorithm) in all its glory. The most interesting part of this is how it pre-scans the first 1024 bytes in order to search for certain `<meta charset>`-related patterns. ```js const htmlEncodingSniffer = require("html-encoding-sniffer"); const fs = require("fs"); const htmlBuffer = fs.readFileSync("./html-page.html"); const sniffedEncoding = htmlEncodingSniffer(htmlBuffer); ``` The returned value will be a canonical [encoding name](https://encoding.spec.whatwg.org/#names-and-labels) (not a label). You might then combine this with the [whatwg-encoding](https://github.com/jsdom/whatwg-encoding) package to decode the result: ```js const whatwgEncoding = require("whatwg-encoding"); const htmlString = whatwgEncoding.decode(htmlBuffer, sniffedEncoding); ``` ## Options You can pass two potential options to `htmlEncodingSniffer`: ```js const sniffedEncoding = htmlEncodingSniffer(htmlBuffer, { transportLayerEncodingLabel, defaultEncoding }); ``` These represent two possible inputs into the [encoding sniffing algorithm](https://html.spec.whatwg.org/multipage/syntax.html#encoding-sniffing-algorithm): - `transportLayerEncodingLabel` is an encoding label that is obtained from the "transport layer" (probably a HTTP `Content-Type` header), which overrides everything but a BOM. - `defaultEncoding` is the ultimate fallback encoding used if no valid encoding is supplied by the transport layer, and no encoding is sniffed from the bytes. It defaults to `"windows-1252"`, as recommended by the algorithm's table of suggested defaults for "All other locales" (including the `en` locale). ## Credits This package was originally based on the excellent work of [@nicolashenry](https://github.com/nicolashenry), [in jsdom](https://github.com/tmpvar/jsdom/blob/16fd85618f2705d181232f6552125872a37164bc/lib/jsdom/living/helpers/encoding.js). It has since been pulled out into this separate package. ## istanbul-lib-coverage [![Greenkeeper badge](https://badges.greenkeeper.io/istanbuljs/istanbul-lib-coverage.svg)](https://greenkeeper.io/) [![Build Status](https://travis-ci.org/istanbuljs/istanbul-lib-coverage.svg?branch=master)](https://travis-ci.org/istanbuljs/istanbul-lib-coverage) An API that provides a read-only view of coverage information with the ability to merge and summarize coverage info. Supersedes `object-utils` and `collector` from the v0 istanbul API. See the docs for the full API. ```js var libCoverage = require('istanbul-lib-coverage'); var map = libCoverage.createCoverageMap(globalCoverageVar); var summary = libCoverage.createCoverageSummary(); // merge another coverage map into the one we created map.merge(otherCoverageMap); // inspect and summarize all file coverage objects in the map map.files().forEach(function(f) { var fc = map.fileCoverageFor(f), s = fc.toSummary(); summary.merge(s); }); console.log('Global summary', summary); ``` The AssemblyScript Runtime ========================== The runtime provides the functionality necessary to dynamically allocate and deallocate memory of objects, arrays and buffers, as well as keep track of references that are no longer used. Interface --------- * **__alloc**(size: `usize`, id: `u32` = 0): `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**(ref: `usize`, size: `usize`): `usize`<br /> Dynamically changes the size of a chunk of memory, possibly moving it to a new address. * **__free**(ref: `usize`): `void`<br /> Frees a dynamically allocated chunk of memory by its address. * **__retain**(ref: `usize`): `usize`<br /> Retains a reference to an object. The object doesn't become collected as long as there's at least one retained reference. Returns the retained reference. * **__release**(ref: `usize`): `void`<br /> Releases a reference to an object. The object is considered for collection once all references to it have been released. * **__collect**(): `void`<br /> Forces a full garbage collection cycle. By default this means that reference cycles are resolved and possibly collected. ### Internals * **__visit**(ref: `usize`, cookie: `u32`): `void`<br /> Concrete visitor implementation called during traversal. Cookie can be used to indicate one of multiple operations. ### Built-ins * **__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 reference type is managed, an array or similar, and what the relevant alignments when creating an instance externally are etc. * **__instanceof** * **__visit_globals**(cookie: `u32`): `void`<br /> Calls `__visit` on each global that is of a reference type. Not used anymore (originally provided to support tracing GCs) but still here for possible future use. * **__visit_members**(ref: `usize`, cookie: `u32`): `void`<br /> Calls `__visit` on each member of the object pointed to by `ref`. ### Related * **idof**<`T`>(): `u32`<br /> Obtains the unique internal class id of a reference type. Full/half --------- The [full](./index-full.ts) runtime is based on [the TLSF memory manager](./tlsf.ts) and [a pure reference counting garbage collector](./pure.ts) and provides all the functionality necessary. The [half](./index-half.ts) alias is essentially the same, but doesn't expose the runtime API so unused runtime code can be DCE'ed. Stub/none --------- The [stub](./index-stub.ts) runtime, though fully functional, provides minimal dynamic memory allocation but no deallocation. Useful for prototyping or very short-lived programs with hardly any memory footprint. The [none](./index-none.ts) alias is the same, but doesn't expose the runtime API so unused runtime code can be DCE'ed. Integration notes ----------------- The underlying reference counting implementation works very similar to other implementations. When an object is stored in a local, global or field, its reference becomes retained (reference count is incremented by 1), respectively when it becomes deleted, it is released (reference count is decremented by 1). Once the reference count reaches zero, the object is considered for collection and the reference count of all contained objects (fields, array elements etc.) is decremented by 1. Now, if an object is inherently acyclic (most objects are), it is free'd right away, while otherwise it is added to a cycle pool and considered for cycle collection on the next `__collect`. Differences to other implementations include: * A new object from `__alloc` doesn't start with a reference count of 1, but 0. * When an object is returned from a function, it remains at RC + 1 and the caller is expected to release it. * Functions with reference type arguments retain each such argument when called, and release it again when exited. This can't be counted on, however, because the compiler may decide to eliminate these where unnecessary. * Getters, setters, operator overloads and constructors are function calls and behave like one. Even though the rules are simple, working with the runtime internals within standard library code can be tricky and requires knowledge of where the compiler will insert runtime calls automatically. For instance * `changetype`ing a pointer to a reference type or vice-versa has no side-effects. For example in a `changetype<Ref>(ptr)` the pointer is untracked before, and the reference becomes tracked afterwards, but there's nothing inserted in between. * `load`, `store` and similar built-ins aren't functions but intrinsics and as such have no side-effects. For example a `load<Ref>(...)` is equivalent to a `changetype<Ref>(load<usize>(...))` and a `store<Ref>(..., ref)` equivalent to a `store<usize>(..., changetype<usize>(ref))`. **GOOD:** In case of doubt, the following pattern is universal: ```ts var ref = changetype<Ref>(__alloc(SIZE, idof<Ref>())); // assignment retains, RC=1 // ... safe ... return ref; // knows `ref` is already retained and simply returns it ``` **BAD:** A pattern one shouldn't use is: ```ts var ptr = __alloc(SIZE, idof<Ref>()); // RC=0 // ... not safe while RC=0 ... e.g.: someFunc(changetype<Ref>(ptr)); // might, or might not, free the object! ``` **BONUS:** Beware of runtime calls in conditional expressions like a ternary IF, logical AND or OR. Each arm can be in either of two states: Either in-flight if immediately retained/returned or not if the expression or the target doesn't support it. Don't fight the compiler there. # 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 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`. # w3c-xmlserializer An XML serializer that follows the [W3C specification](https://w3c.github.io/DOM-Parsing/). This package can be used in Node.js, as long as you feed it a DOM node, e.g. one produced by [jsdom](https://github.com/jsdom/jsdom). ## Basic usage Assume you have a DOM tree rooted at a node `node`. In Node.js, you could create this using [jsdom](https://github.com/jsdom/jsdom) as follows: ```js const { JSDOM } = require("jsdom"); const { document } = new JSDOM().window; const node = document.createElement("akomaNtoso"); ``` Then, you use this package as follows: ```js const serialize = require("w3c-xmlserializer"); console.log(serialize(node)); // => '<akomantoso xmlns="http://www.w3.org/1999/xhtml"></akomantoso>' ``` ## `requireWellFormed` option By default the input DOM tree is not required to be "well-formed"; any given input will serialize to some output string. You can instead require well-formedness via ```js serialize(node, { requireWellFormed: true }); ``` which will cause `Error`s to be thrown when non-well-formed constructs are encountered. [Per the spec](https://w3c.github.io/DOM-Parsing/#dfn-require-well-formed), this largely is about imposing constraints on the names of elements, attributes, etc. As a point of reference, on the web platform: * The [`innerHTML` getter](https://w3c.github.io/DOM-Parsing/#dom-innerhtml-innerhtml) uses the require-well-formed mode, i.e. trying to get the `innerHTML` of non-well-formed subtrees will throw. * The [`xhr.send()` method](https://xhr.spec.whatwg.org/#the-send()-method) does not require well-formedness, i.e. sending non-well-formed `Document`s will serialize and send them anyway. # 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 # 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] All tools will find target browsers automatically, when you add the following to `package.json`: ```json "browserslist": [ "defaults", "not IE 11", "not IE_Mob 11", "maintained node versions" ] ``` Or in `.browserslistrc` config: ```yaml # Browsers that we support defaults not IE 11 not IE_Mob 11 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. Browserslist will take queries from tool option, `browserslist` config, `.browserslistrc` config, `browserslist` section in `package.json` or environment variables. [Browserslist Example] shows how every tool uses Browserslist. [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 [`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 [obsolete-webpack-plugin]: https://github.com/ElemeFE/obsolete-webpack-plugin ## Table of Contents * [Tools](#tools) * [Best Practices](#best-practices) * [Browsers Data Updating](#browsers-data-updating) * [Queries](#queries) * [Query Composition](#query-composition) * [Full List](#full-list) * [Debug](#debug) * [Browsers](#browsers) * [Config File](#config-file) * [`package.json`](#packagejson) * [`.browserslistrc`](#browserslistrc) * [Shareable Configs](#shareable-configs) * [Configuring for Different Environments](#configuring-for-different-environments) * [Custom Usage Data](#custom-usage-data) * [JS API](#js-api) * [Environment Variables](#environment-variables) * [Cache](#cache) * [Security Contact](#security-contact) * [For Enterprise](#for-enterprise) ## Tools * [`browserl.ist`](https://browserl.ist/) is an online tool to check what browsers will be selected by some query. * [`browserslist-ga`] and [`browserslist-ga-export`] download your website browsers statistics to use it in `> 0.5% in my stats` query. * [`browserslist-useragent-regexp`] compiles Browserslist query to a RegExp to test browser useragent. * [`browserslist-useragent-ruby`] is a Ruby library to checks browser by user agent string to match Browserslist. * [`browserslist-browserstack`] runs BrowserStack tests for all browsers in Browserslist config. * [`browserslist-adobe-analytics`] use Adobe Analytics data to target browsers. * [`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-regexp`]: https://github.com/browserslist/browserslist-useragent-regexp [`browserslist-adobe-analytics`]: https://github.com/xeroxinteractive/browserslist-adobe-analytics [`browserslist-useragent-ruby`]: https://github.com/browserslist/browserslist-useragent-ruby [`browserslist-browserstack`]: https://github.com/xeroxinteractive/browserslist-browserstack [`browserslist-ga-export`]: https://github.com/browserslist/browserslist-ga-export [`browserslist-useragent`]: https://github.com/pastelsky/browserslist-useragent [`browserslist-ga`]: https://github.com/browserslist/browserslist-ga [`caniuse-api`]: https://github.com/Nyalab/caniuse-api ## Best Practices * There is a `defaults` query, which gives a reasonable configuration for most users: ```json "browserslist": [ "defaults" ] ``` * If you want to change the default set of browsers, we recommend combining `last 2 versions`, `not dead` with a usage number like `> 0.2%`. This is because `last n versions` on its own does not add popular old versions, while only using 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. * 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. * 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 combined. ## Browsers Data Updating `npx browserslist@latest --update-db` updates `caniuse-lite` version in your npm, yarn or pnpm lock file. You need to do it regularly for two reasons: 1. To use the latest browser’s versions and statistics in queries like `last 2 versions` or `>1%`. For example, if you created your project 2 years ago and did not update your dependencies, `last 1 version` will return 2 year old browsers. 2. `caiuse-lite` deduplication: to synchronize version in different tools. > What is deduplication? Due to how npm architecture is setup, you may have a situation where you have multiple versions of a single dependency required. Imagine you begin a project, and you add `autoprefixer` as a dependency. npm looks for the latest `caniuse-lite` version (1.0.30000700) and adds it to `package-lock.json` under `autoprefixer` dependencies. A year later, you decide to add Babel. At this moment, we have a new version of `canuse-lite` (1.0.30000900). npm took the latest version and added it to your lock file under `@babel/preset-env` dependencies. Now your lock file looks like this: ```ocaml autoprefixer 7.1.4 browserslist 3.1.1 caniuse-lite 1.0.30000700 @babel/preset-env 7.10.0 browserslist 4.13.0 caniuse-lite 1.0.30000900 ``` As you can see, we now have two versions of `caniuse-lite` installed. ## Queries Browserslist will use browsers and Node.js versions query from one of these sources: 1. `browserslist` key in `package.json` file in current or parent directories. **We recommend this way.** 2. `.browserslistrc` config file in current or parent directories. 3. `browserslist` config file in current or parent directories. 4. `BROWSERSLIST` environment variable. 5. 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 all the previous queries: `last 1 version or chrome > 75 and > 1%` will select (`browser last version` or `Chrome since 76`) and `more than 1% marketshare`. 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 there is no left-hand side query to combine it with. The left-hand is always resolved as `and` combiner even if `or` is used (this is an API implementation specificity). | 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) | All those three are equivalent to the first one <br> `> .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._ ### Full List You can specify the browser and Node.js versions by queries (case insensitive): * `defaults`: Browserslist’s default browsers (`> 0.5%, last 2 versions, Firefox ESR, not dead`). * `> 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]. * `> 5% in browserslist-config-mycompany stats`: uses [custom usage data] from `browserslist-config-mycompany/browserslist-stats.json`. * `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]. * `dead`: browsers without official support or updates for 24 months. Right now it is `IE 10`, `IE_Mob 11`, `BlackBerry 10`, `BlackBerry 7`, `Samsung 4` 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. * `last 2 major versions` or `last 2 iOS major versions`: all minor/patch releases of last 2 major versions. * `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. * `maintained node versions`: all Node.js versions, which are [still maintained] by Node.js Foundation. * `iOS 7`: the iOS browser version 7 directly. * `Firefox > 20`: versions of Firefox newer than 20. `>=`, `<` and `<=` work too. It also works with Node.js. * `ie 6-8`: selects an inclusive range of versions. * `Firefox ESR`: the latest [Firefox ESR] version. * `PhantomJS 2.1` and `PhantomJS 1.9`: selects Safari versions similar to PhantomJS runtime. * `extends browserslist-config-mycompany`: take queries from `browserslist-config-mycompany` npm package. * `supports es6-module`: browsers with support for specific features. `es6-module` here is the `feat` parameter at the URL of the [Can I Use] page. A list of all available features can be found at [`caniuse-lite/data/features`]. * `since 2015` or `last 2 years`: all versions released since year 2015 (also `since 2015-03` and `since 2015-03-10`). * `unreleased versions` or `unreleased Chrome versions`: alpha and beta versions. * `not ie <= 8`: exclude browsers selected by previous queries. You can add `not ` to any query. [`caniuse-lite/data/regions`]: https://github.com/ben-eb/caniuse-lite/tree/master/data/regions [`caniuse-lite/data/features`]: https://github.com/ben-eb/caniuse-lite/tree/master/data/features [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/ ### 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 ``` ### 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. * `kaios` for KaiOS Browser. ## Config File ### `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" ] } ``` ### `.browserslistrc` Separated Browserslist config should be named `.browserslistrc` and have browsers queries split by a new line. Each line is combined with the `or` combiner. 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 or `BROWSERSLIST_DANGEROUS_EXTEND` environment variable or `dangerousExtend` option. ```sh BROWSERSLIST_DANGEROUS_EXTEND=1 npx webpack ``` 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' ] ``` You can also include a `browserslist-stats.json` file as part of your shareable config at the root and query it using `> 5% in browserslist-config-mycompany stats`. It uses the same format as `extends` and the `dangerousExtend` property as above. You can export configs for different environments and select environment by `BROWSERSLIST_ENV` or `env` option in your tool: ```js module.exports = { development: [ 'last 1 version' ], production: [ 'last 1 version', '> 1%', 'ie 10' ] } ``` ## Configuring for Different 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" ], "modern": [ "last 1 chrome version", "last 1 firefox version" ], "ssr": [ "node 12" ] } ``` In `.browserslistrc` config: ```ini [production] > 1% ie 10 [modern] last 1 chrome version last 1 firefox version [ssr] node 12 ``` ## 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 ``` Or you can use [`browserslist-ga-export`] to convert Google Analytics data without giving a password for Google account. 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-export`]: https://github.com/browserslist/browserslist-ga-export [`browserslist-ga`]: https://github.com/browserslist/browserslist-ga [Can I Use]: https://caniuse.com/ ## JS API ```js const browserslist = require('browserslist') // Your CSS/JS build tool code function process (source, opts) { const browsers = browserslist(opts.overrideBrowserslist, { 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.` * `mobileToDesktop`: Use desktop browsers if Can I Use doesn’t have data about this mobile version. For instance, Browserslist will return `chrome 20` on `and_chr 20` query (Can I Use has only data only about latest versions of mobile browsers). Default is `false`. For non-JS environment and debug purpose you can use CLI tool: ```sh browserslist "> 1%, IE 10" ``` 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 ``` ## Environment Variables If a tool uses Browserslist inside, you can change the Browserslist settings with [environment variables]: * `BROWSERSLIST` with browsers queries. ```sh BROWSERSLIST="> 5%" npx webpack ``` * `BROWSERSLIST_CONFIG` with path to config file. ```sh BROWSERSLIST_CONFIG=./config/browserslist npx webpack ``` * `BROWSERSLIST_ENV` with environments string. ```sh BROWSERSLIST_ENV="development" npx webpack ``` * `BROWSERSLIST_STATS` with path to the custom usage data for `> 1% in my stats` query. ```sh BROWSERSLIST_STATS=./config/usage_data.json npx webpack ``` * `BROWSERSLIST_DISABLE_CACHE` if you want to disable config reading cache. ```sh BROWSERSLIST_DISABLE_CACHE=1 npx webpack ``` * `BROWSERSLIST_DANGEROUS_EXTEND` to disable security shareable config name check. ```sh BROWSERSLIST_DANGEROUS_EXTEND=1 npx webpack ``` [environment variables]: https://en.wikipedia.org/wiki/Environment_variable ## 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 ## For Enterprise Available as part of the Tidelift Subscription. The maintainers of `browserslist` 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-browserslist?utm_source=npm-browserslist&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) # 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. 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 `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value components are invalid (`9999999999999999.4.7.4` is likely invalid). 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 `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value components are invalid (`9999999999999999.4.7.4` is likely invalid). # 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 # ws: a Node.js WebSocket library [![Version npm](https://img.shields.io/npm/v/ws.svg)](https://www.npmjs.com/package/ws) [![Linux Build](https://img.shields.io/travis/websockets/ws/master.svg)](https://travis-ci.org/websockets/ws) [![Windows Build](https://ci.appveyor.com/api/projects/status/github/websockets/ws?branch=master&svg=true)](https://ci.appveyor.com/project/lpinca/ws) [![Coverage Status](https://img.shields.io/coveralls/websockets/ws/master.svg)](https://coveralls.io/r/websockets/ws?branch=master) ws is a simple to use, blazing fast, and thoroughly tested WebSocket client and server implementation. Passes the quite extensive Autobahn test suite: [server][server-report], [client][client-report]. **Note**: This module does not work in the browser. The client in the docs is a reference to a back end with the role of a client in the WebSocket communication. Browser clients must use the native [`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) object. To make the same code work seamlessly on Node.js and the browser, you can use one of the many wrappers available on npm, like [isomorphic-ws](https://github.com/heineiuo/isomorphic-ws). ## Table of Contents * [Protocol support](#protocol-support) * [Installing](#installing) + [Opt-in for performance and spec compliance](#opt-in-for-performance-and-spec-compliance) * [API docs](#api-docs) * [WebSocket compression](#websocket-compression) * [Usage examples](#usage-examples) + [Sending and receiving text data](#sending-and-receiving-text-data) + [Sending binary data](#sending-binary-data) + [Simple server](#simple-server) + [External HTTP/S server](#external-https-server) + [Multiple servers sharing a single HTTP/S server](#multiple-servers-sharing-a-single-https-server) + [Server broadcast](#server-broadcast) + [echo.websocket.org demo](#echowebsocketorg-demo) + [Other examples](#other-examples) * [Error handling best practices](#error-handling-best-practices) * [FAQ](#faq) + [How to get the IP address of the client?](#how-to-get-the-ip-address-of-the-client) + [How to detect and close broken connections?](#how-to-detect-and-close-broken-connections) + [How to connect via a proxy?](#how-to-connect-via-a-proxy) * [Changelog](#changelog) * [License](#license) ## Protocol support * **HyBi drafts 07-12** (Use the option `protocolVersion: 8`) * **HyBi drafts 13-17** (Current default, alternatively option `protocolVersion: 13`) ## Installing ``` npm install --save ws ``` ### Opt-in for performance and spec compliance There are 2 optional modules that can be installed along side with the ws module. These modules are binary addons which improve certain operations. Prebuilt binaries are available for the most popular platforms so you don't necessarily need to have a C++ compiler installed on your machine. - `npm install --save-optional bufferutil`: Allows to efficiently perform operations such as masking and unmasking the data payload of the WebSocket frames. - `npm install --save-optional utf-8-validate`: Allows to efficiently check if a message contains valid UTF-8 as required by the spec. ## API docs See [`/doc/ws.md`](./doc/ws.md) for Node.js-like docs for the ws classes. ## WebSocket compression ws supports the [permessage-deflate extension][permessage-deflate] which enables the client and server to negotiate a compression algorithm and its parameters, and then selectively apply it to the data payloads of each WebSocket message. The extension is disabled by default on the server and enabled by default on the client. It adds a significant overhead in terms of performance and memory consumption so we suggest to enable it only if it is really needed. Note that Node.js has a variety of issues with high-performance compression, where increased concurrency, especially on Linux, can lead to [catastrophic memory fragmentation][node-zlib-bug] and slow performance. If you intend to use permessage-deflate in production, it is worthwhile to set up a test representative of your workload and ensure Node.js/zlib will handle it with acceptable performance and memory usage. Tuning of permessage-deflate can be done via the options defined below. You can also use `zlibDeflateOptions` and `zlibInflateOptions`, which is passed directly into the creation of [raw deflate/inflate streams][node-zlib-deflaterawdocs]. See [the docs][ws-server-options] for more options. ```js const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080, perMessageDeflate: { zlibDeflateOptions: { // See zlib defaults. chunkSize: 1024, memLevel: 7, level: 3, }, zlibInflateOptions: { chunkSize: 10 * 1024 }, // Other options settable: clientNoContextTakeover: true, // Defaults to negotiated value. serverNoContextTakeover: true, // Defaults to negotiated value. clientMaxWindowBits: 10, // Defaults to negotiated value. serverMaxWindowBits: 10, // Defaults to negotiated value. // Below options specified as default values. concurrencyLimit: 10, // Limits zlib concurrency for perf. threshold: 1024, // Size (in bytes) below which messages // should not be compressed. } }); ``` The client will only use the extension if it is supported and enabled on the server. To always disable the extension on the client set the `perMessageDeflate` option to `false`. ```js const WebSocket = require('ws'); const ws = new WebSocket('ws://www.host.com/path', { perMessageDeflate: false }); ``` ## Usage examples ### Sending and receiving text data ```js const WebSocket = require('ws'); const ws = new WebSocket('ws://www.host.com/path'); ws.on('open', function open() { ws.send('something'); }); ws.on('message', function incoming(data) { console.log(data); }); ``` ### Sending binary data ```js const WebSocket = require('ws'); const ws = new WebSocket('ws://www.host.com/path'); ws.on('open', function open() { const array = new Float32Array(5); for (var i = 0; i < array.length; ++i) { array[i] = i / 2; } ws.send(array); }); ``` ### Simple server ```js const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', function connection(ws) { ws.on('message', function incoming(message) { console.log('received: %s', message); }); ws.send('something'); }); ``` ### External HTTP/S server ```js const fs = require('fs'); const https = require('https'); const WebSocket = require('ws'); const server = new https.createServer({ cert: fs.readFileSync('/path/to/cert.pem'), key: fs.readFileSync('/path/to/key.pem') }); const wss = new WebSocket.Server({ server }); wss.on('connection', function connection(ws) { ws.on('message', function incoming(message) { console.log('received: %s', message); }); ws.send('something'); }); server.listen(8080); ``` ### Multiple servers sharing a single HTTP/S server ```js const http = require('http'); const WebSocket = require('ws'); const server = http.createServer(); const wss1 = new WebSocket.Server({ noServer: true }); const wss2 = new WebSocket.Server({ noServer: true }); wss1.on('connection', function connection(ws) { // ... }); wss2.on('connection', function connection(ws) { // ... }); server.on('upgrade', function upgrade(request, socket, head) { const pathname = url.parse(request.url).pathname; if (pathname === '/foo') { wss1.handleUpgrade(request, socket, head, function done(ws) { wss1.emit('connection', ws, request); }); } else if (pathname === '/bar') { wss2.handleUpgrade(request, socket, head, function done(ws) { wss2.emit('connection', ws, request); }); } else { socket.destroy(); } }); server.listen(8080); ``` ### Server broadcast ```js const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); // Broadcast to all. wss.broadcast = function broadcast(data) { wss.clients.forEach(function each(client) { if (client.readyState === WebSocket.OPEN) { client.send(data); } }); }; wss.on('connection', function connection(ws) { ws.on('message', function incoming(data) { // Broadcast to everyone else. wss.clients.forEach(function each(client) { if (client !== ws && client.readyState === WebSocket.OPEN) { client.send(data); } }); }); }); ``` ### echo.websocket.org demo ```js const WebSocket = require('ws'); const ws = new WebSocket('wss://echo.websocket.org/', { origin: 'https://websocket.org' }); ws.on('open', function open() { console.log('connected'); ws.send(Date.now()); }); ws.on('close', function close() { console.log('disconnected'); }); ws.on('message', function incoming(data) { console.log(`Roundtrip time: ${Date.now() - data} ms`); setTimeout(function timeout() { ws.send(Date.now()); }, 500); }); ``` ### Other examples For a full example with a browser client communicating with a ws server, see the examples folder. Otherwise, see the test cases. ## Error handling best practices ```js // If the WebSocket is closed before the following send is attempted ws.send('something'); // Errors (both immediate and async write errors) can be detected in an optional // callback. The callback is also the only way of being notified that data has // actually been sent. ws.send('something', function ack(error) { // If error is not defined, the send has been completed, otherwise the error // object will indicate what failed. }); // Immediate errors can also be handled with `try...catch`, but **note** that // since sends are inherently asynchronous, socket write failures will *not* be // captured when this technique is used. try { ws.send('something'); } catch (e) { /* handle error */ } ``` ## FAQ ### How to get the IP address of the client? The remote IP address can be obtained from the raw socket. ```js const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', function connection(ws, req) { const ip = req.connection.remoteAddress; }); ``` When the server runs behind a proxy like NGINX, the de-facto standard is to use the `X-Forwarded-For` header. ```js wss.on('connection', function connection(ws, req) { const ip = req.headers['x-forwarded-for'].split(/\s*,\s*/)[0]; }); ``` ### How to detect and close broken connections? Sometimes the link between the server and the client can be interrupted in a way that keeps both the server and the client unaware of the broken state of the connection (e.g. when pulling the cord). In these cases ping messages can be used as a means to verify that the remote endpoint is still responsive. ```js const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); function noop() {} function heartbeat() { this.isAlive = true; } wss.on('connection', function connection(ws) { ws.isAlive = true; ws.on('pong', heartbeat); }); const interval = setInterval(function ping() { wss.clients.forEach(function each(ws) { if (ws.isAlive === false) return ws.terminate(); ws.isAlive = false; ws.ping(noop); }); }, 30000); ``` Pong messages are automatically sent in response to ping messages as required by the spec. ### How to connect via a proxy? Use a custom `http.Agent` implementation like [https-proxy-agent][] or [socks-proxy-agent][]. ## Changelog We're using the GitHub [releases][changelog] for changelog entries. ## License [MIT](LICENSE) [https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent [socks-proxy-agent]: https://github.com/TooTallNate/node-socks-proxy-agent [client-report]: http://websockets.github.io/ws/autobahn/clients/ [server-report]: http://websockets.github.io/ws/autobahn/servers/ [permessage-deflate]: https://tools.ietf.org/html/rfc7692 [changelog]: https://github.com/websockets/ws/releases [node-zlib-bug]: https://github.com/nodejs/node/issues/8871 [node-zlib-deflaterawdocs]: https://nodejs.org/api/zlib.html#zlib_zlib_createdeflateraw_options [ws-server-options]: https://github.com/websockets/ws/blob/master/doc/ws.md#new-websocketserveroptions-callback # 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 # 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 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. ![Logo](./www/assets/img/logo.png) Almost There is a crowdfunding platform based on [NEAR](https://near.org/) and hosted on [Sia](https://siasky.net/). Users can both create new Almost There "campaigns", or donate to one. Each campaign is also created as their own webpage (also hosted on Sia), that the users can link and promote on their own. The campaigns have a date of closing and donations goal. When the date is reached, if the goal was achieved or surpassed, the donations are sent to the campaign owner; if not, the donations are returned to the donors. Check the [demo!](https://siasky.net/hns/lunafromthemoon/) and the [video on how to use it!](https://siasky.net/AACjNkdbHx6SJ_L3MLT8otJ1moEEqiaGZQXrtWa4RJC0ig) # How does it work? Almost There is a web application, and as with most web apps, it has a frontend and a backend. The frontend is a traditional HTML5 page, hosted on Sia. The backend is a smart contract hosted in the NEAR Network (currently only testnet). While the frontend takes care of the look and feel and templating of the campaigns, the backend handles the account management and donations. # 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. # 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._ 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;nathan@tootallnate.net&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._ [![NPM version](https://img.shields.io/npm/v/csso.svg)](https://www.npmjs.com/package/csso) [![Build Status](https://travis-ci.org/css/csso.svg?branch=master)](https://travis-ci.org/css/csso) [![Coverage Status](https://coveralls.io/repos/github/css/csso/badge.svg?branch=master)](https://coveralls.io/github/css/csso?branch=master) [![NPM Downloads](https://img.shields.io/npm/dm/csso.svg)](https://www.npmjs.com/package/csso) [![Twitter](https://img.shields.io/badge/Twitter-@cssoptimizer-blue.svg)](https://twitter.com/cssoptimizer) CSSO (CSS Optimizer) is a CSS minifier. It performs three sort of transformations: cleaning (removing redundant), compression (replacement for shorter form) and restructuring (merge of declarations, rulesets and so on). As a result your CSS becomes much smaller. [![Originated by Yandex](https://cdn.rawgit.com/css/csso/8d1b89211ac425909f735e7d5df87ee16c2feec6/docs/yandex.svg)](https://www.yandex.com/) [![Sponsored by Avito](https://cdn.rawgit.com/css/csso/8d1b89211ac425909f735e7d5df87ee16c2feec6/docs/avito.svg)](https://www.avito.ru/) ## Ready to use - [Web interface](http://css.github.io/csso/csso.html) - [csso-cli](https://github.com/css/csso-cli) – command line interface - [gulp-csso](https://github.com/ben-eb/gulp-csso) – `Gulp` plugin - [grunt-csso](https://github.com/t32k/grunt-csso) – `Grunt` plugin - [broccoli-csso](https://github.com/sindresorhus/broccoli-csso) – `Broccoli` plugin - [postcss-csso](https://github.com/lahmatiy/postcss-csso) – `PostCSS` plugin - [csso-loader](https://github.com/sandark7/csso-loader) – `webpack` loader - [csso-webpack-plugin](https://github.com/zoobestik/csso-webpack-plugin) – `webpack` plugin - [CSSO Visual Studio Code plugin](https://marketplace.visualstudio.com/items?itemName=Aneryu.csso) ## Install ``` npm install csso ``` ## API <!-- TOC depthfrom:3 --> - [minify(source[, options])](#minifysource-options) - [minifyBlock(source[, options])](#minifyblocksource-options) - [syntax.compress(ast[, options])](#syntaxcompressast-options) - [Source maps](#source-maps) - [Usage data](#usage-data) - [White list filtering](#white-list-filtering) - [Black list filtering](#black-list-filtering) - [Scopes](#scopes) <!-- /TOC --> Basic usage: ```js var csso = require('csso'); var minifiedCss = csso.minify('.test { color: #ff0000; }').css; console.log(minifiedCss); // .test{color:red} ``` CSSO is based on [CSSTree](https://github.com/csstree/csstree) to parse CSS into AST, AST traversal and to generate AST back to CSS. All `CSSTree` API is available behind `syntax` field. You may minify CSS step by step: ```js var csso = require('csso'); var ast = csso.syntax.parse('.test { color: #ff0000; }'); var compressedAst = csso.syntax.compress(ast).ast; var minifiedCss = csso.syntax.generate(compressedAst); console.log(minifiedCss); // .test{color:red} ``` > Warning: CSSO uses early versions of CSSTree that still in active development. CSSO doesn't guarantee API behind `syntax` field or AST format will not change in future releases of CSSO, since it's subject to change in CSSTree. Be careful with CSSO updates if you use `syntax` API until this warning removal. ### minify(source[, options]) Minify `source` CSS passed as `String`. ```js var result = csso.minify('.test { color: #ff0000; }', { restructure: false, // don't change CSS structure, i.e. don't merge declarations, rulesets etc debug: true // show additional debug information: // true or number from 1 to 3 (greater number - more details) }); console.log(result.css); // > .test{color:red} ``` Returns an object with properties: - css `String` – resulting CSS - map `Object` – instance of [`SourceMapGenerator`](https://github.com/mozilla/source-map#sourcemapgenerator) or `null` Options: - sourceMap Type: `Boolean` Default: `false` Generate a source map when `true`. - filename Type: `String` Default: `'<unknown>'` Filename of input CSS, uses for source map generation. - debug Type: `Boolean` Default: `false` Output debug information to `stderr`. - beforeCompress Type: `function(ast, options)` or `Array<function(ast, options)>` or `null` Default: `null` Called right after parse is run. - afterCompress Type: `function(compressResult, options)` or `Array<function(compressResult, options)>` or `null` Default: `null` Called right after [`syntax.compress()`](#syntaxcompressast-options) is run. - Other options are the same as for [`syntax.compress()`](#syntaxcompressast-options) function. ### minifyBlock(source[, options]) The same as `minify()` but for list of declarations. Usually it's a `style` attribute value. ```js var result = csso.minifyBlock('color: rgba(255, 0, 0, 1); color: #ff0000'); console.log(result.css); // > color:red ``` ### syntax.compress(ast[, options]) Does the main task – compress an AST. This is CSSO's extension in CSSTree syntax API. > NOTE: `syntax.compress()` performs AST compression by transforming input AST by default (since AST cloning is expensive and needed in rare cases). Use `clone` option with truthy value in case you want to keep input AST untouched. Returns an object with properties: - ast `Object` – resulting AST Options: - restructure Type: `Boolean` Default: `true` Disable or enable a structure optimisations. - forceMediaMerge Type: `Boolean` Default: `false` Enables merging of `@media` rules with the same media query by splitted by other rules. The optimisation is unsafe in general, but should work fine in most cases. Use it on your own risk. - clone Type: `Boolean` Default: `false` Transform a copy of input AST if `true`. Useful in case of AST reuse. - comments Type: `String` or `Boolean` Default: `true` Specify what comments to leave: - `'exclamation'` or `true` – leave all exclamation comments (i.e. `/*! .. */`) - `'first-exclamation'` – remove every comment except first one - `false` – remove all comments - usage Type: `Object` or `null` Default: `null` Usage data for advanced optimisations (see [Usage data](#usage-data) for details) - logger Type: `Function` or `null` Default: `null` Function to track every step of transformation. ### Source maps To get a source map set `true` for `sourceMap` option. Additianaly `filename` option can be passed to specify source file. When `sourceMap` option is `true`, `map` field of result object will contain a [`SourceMapGenerator`](https://github.com/mozilla/source-map#sourcemapgenerator) instance. This object can be mixed with another source map or translated to string. ```js var csso = require('csso'); var css = fs.readFileSync('path/to/my.css', 'utf8'); var result = csso.minify(css, { filename: 'path/to/my.css', // will be added to source map as reference to source file sourceMap: true // generate source map }); console.log(result); // { css: '...minified...', map: SourceMapGenerator {} } console.log(result.map.toString()); // '{ .. source map content .. }' ``` Example of generating source map with respect of source map from input CSS: ```js var require('source-map'); var csso = require('csso'); var inputFile = 'path/to/my.css'; var input = fs.readFileSync(inputFile, 'utf8'); var inputMap = input.match(/\/\*# sourceMappingURL=(\S+)\s*\*\/\s*$/); var output = csso.minify(input, { filename: inputFile, sourceMap: true }); // apply input source map to output if (inputMap) { output.map.applySourceMap( new SourceMapConsumer(inputMap[1]), inputFile ) } // result CSS with source map console.log( output.css + '/*# sourceMappingURL=data:application/json;base64,' + new Buffer(output.map.toString()).toString('base64') + ' */' ); ``` ### Usage data `CSSO` can use data about how `CSS` is used in a markup for better compression. File with this data (`JSON`) can be set using `usage` option. Usage data may contain following sections: - `blacklist` – a set of black lists (see [Black list filtering](#black-list-filtering)) - `tags` – white list of tags - `ids` – white list of ids - `classes` – white list of classes - `scopes` – groups of classes which never used with classes from other groups on the same element All sections are optional. Value of `tags`, `ids` and `classes` should be an array of a string, value of `scopes` should be an array of arrays of strings. Other values are ignoring. #### White list filtering `tags`, `ids` and `classes` are using on clean stage to filter selectors that contain something not in the lists. Selectors are filtering only by those kind of simple selector which white list is specified. For example, if only `tags` list is specified then type selectors are checking, and if all type selectors in selector present in list or selector has no any type selector it isn't filter. > `ids` and `classes` are case sensitive, `tags` – is not. Input CSS: ```css * { color: green; } ul, ol, li { color: blue; } UL.foo, span.bar { color: red; } ``` Usage data: ```json { "tags": ["ul", "LI"] } ``` Resulting CSS: ```css *{color:green}ul,li{color:blue}ul.foo{color:red} ``` Filtering performs for nested selectors too. `:not()` pseudos content is ignoring since the result of matching is unpredictable. Example for the same usage data as above: ```css :nth-child(2n of ul, ol) { color: red } :nth-child(3n + 1 of img) { color: yellow } :not(div, ol, ul) { color: green } :has(:matches(ul, ol), ul, ol) { color: blue } ``` Turns into: ```css :nth-child(2n of ul){color:red}:not(div,ol,ul){color:green}:has(:matches(ul),ul){color:blue} ``` #### Black list filtering Black list filtering performs the same as white list filtering, but filters things that mentioned in the lists. `blacklist` can contain the lists `tags`, `ids` and `classes`. Black list has a higher priority, so when something mentioned in the white list and in the black list then white list occurrence is ignoring. The `:not()` pseudos content ignoring as well. ```css * { color: green; } ul, ol, li { color: blue; } UL.foo, li.bar { color: red; } ``` Usage data: ```json { "blacklist": { "tags": ["ul"] }, "tags": ["ul", "LI"] } ``` Resulting CSS: ```css *{color:green}li{color:blue}li.bar{color:red} ``` #### Scopes Scopes is designed for CSS scope isolation solutions such as [css-modules](https://github.com/css-modules/css-modules). Scopes are similar to namespaces and define lists of class names that exclusively used on some markup. This information allows the optimizer to move rules more agressive. Since it assumes selectors from different scopes don't match for the same element. This can improve rule merging. Suppose we have a file: ```css .module1-foo { color: red; } .module1-bar { font-size: 1.5em; background: yellow; } .module2-baz { color: red; } .module2-qux { font-size: 1.5em; background: yellow; width: 50px; } ``` It can be assumed that first two rules are never used with the second two on the same markup. But we can't say that for sure without a markup review. The optimizer doesn't know it either and will perform safe transformations only. The result will be the same as input but with no spaces and some semicolons: ```css .module1-foo{color:red}.module1-bar{font-size:1.5em;background:#ff0}.module2-baz{color:red}.module2-qux{font-size:1.5em;background:#ff0;width:50px} ``` With usage data `CSSO` can produce better output. If follow usage data is provided: ```json { "scopes": [ ["module1-foo", "module1-bar"], ["module2-baz", "module2-qux"] ] } ``` The result will be (29 bytes extra saving): ```css .module1-foo,.module2-baz{color:red}.module1-bar,.module2-qux{font-size:1.5em;background:#ff0}.module2-qux{width:50px} ``` If class name isn't mentioned in the `scopes` it belongs to default scope. `scopes` data doesn't affect `classes` whitelist. If class name mentioned in `scopes` but missed in `classes` (both sections are specified) it will be filtered. Note that class name can't be set for several scopes. Also a selector can't have class names from different scopes. In both cases an exception will thrown. Currently the optimizer doesn't care about changing order safety for out-of-bounds selectors (i.e. selectors that match to elements without class name, e.g. `.scope div` or `.scope ~ :last-child`). It assumes that scoped CSS modules doesn't relay on it's order. It may be fix in future if to be an issue. # merge-stream Merge (interleave) a bunch of streams. [![build status](https://secure.travis-ci.org/grncdr/merge-stream.svg?branch=master)](http://travis-ci.org/grncdr/merge-stream) ## Synopsis ```javascript var stream1 = new Stream(); var stream2 = new Stream(); var merged = mergeStream(stream1, stream2); var stream3 = new Stream(); merged.add(stream3); merged.isEmpty(); //=> false ``` ## Description This is adapted from [event-stream](https://github.com/dominictarr/event-stream) separated into a new module, using Streams3. ## API ### `mergeStream` Type: `function` Merges an arbitrary number of streams. Returns a merged stream. #### `merged.add` A method to dynamically add more sources to the stream. The argument supplied to `add` can be either a source or an array of sources. #### `merged.isEmpty` A method that tells you if the merged stream is empty. When a stream is "empty" (aka. no sources were added), it could not be returned to a gulp task. So, we could do something like this: ```js stream = require('merge-stream')(); // Something like a loop to add some streams to the merge stream // stream.add(streamA); // stream.add(streamB); return stream.isEmpty() ? null : stream; ``` ## Gulp example An example use case for **merge-stream** is to combine parts of a task in a project's **gulpfile.js** like this: ```js const gulp = require('gulp'); const htmlValidator = require('gulp-w3c-html-validator'); const jsHint = require('gulp-jshint'); const mergeStream = require('merge-stream'); function lint() { return mergeStream( gulp.src('src/*.html') .pipe(htmlValidator()) .pipe(htmlValidator.reporter()), gulp.src('src/*.js') .pipe(jsHint()) .pipe(jsHint.reporter()) ); } gulp.task('lint', lint); ``` ## License MIT # 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._ # 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._ # ES6-Promise (subset of [rsvp.js](https://github.com/tildeio/rsvp.js)) [![Build Status](https://travis-ci.org/stefanpenner/es6-promise.svg?branch=master)](https://travis-ci.org/stefanpenner/es6-promise) This is a polyfill of the [ES6 Promise](http://www.ecma-international.org/ecma-262/6.0/#sec-promise-constructor). The implementation is a subset of [rsvp.js](https://github.com/tildeio/rsvp.js) extracted by @jakearchibald, if you're wanting extra features and more debugging options, check out the [full library](https://github.com/tildeio/rsvp.js). For API details and how to use promises, see the <a href="http://www.html5rocks.com/en/tutorials/es6/promises/">JavaScript Promises HTML5Rocks article</a>. ## Downloads * [es6-promise 27.86 KB (7.33 KB gzipped)](https://cdn.jsdelivr.net/npm/es6-promise/dist/es6-promise.js) * [es6-promise-auto 27.78 KB (7.3 KB gzipped)](https://cdn.jsdelivr.net/npm/es6-promise/dist/es6-promise.auto.js) - Automatically provides/replaces `Promise` if missing or broken. * [es6-promise-min 6.17 KB (2.4 KB gzipped)](https://cdn.jsdelivr.net/npm/es6-promise/dist/es6-promise.min.js) * [es6-promise-auto-min 6.19 KB (2.4 KB gzipped)](https://cdn.jsdelivr.net/npm/es6-promise/dist/es6-promise.auto.min.js) - Minified version of `es6-promise-auto` above. ## CDN To use via a CDN include this in your html: ```html <!-- Automatically provides/replaces `Promise` if missing or broken. --> <script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.js"></script> <script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.js"></script> <!-- Minified version of `es6-promise-auto` below. --> <script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.min.js"></script> ``` ## Node.js To install: ```sh yarn add es6-promise ``` or ```sh npm install es6-promise ``` To use: ```js var Promise = require('es6-promise').Promise; ``` ## Usage in IE<9 `catch` and `finally` are reserved keywords in IE<9, meaning `promise.catch(func)` or `promise.finally(func)` throw a syntax error. To work around this, you can use a string to access the property as shown in the following example. However most minifiers will automatically fix this for you, making the resulting code safe for old browsers and production: ```js promise['catch'](function(err) { // ... }); ``` ```js promise['finally'](function() { // ... }); ``` ## Auto-polyfill To polyfill the global environment (either in Node or in the browser via CommonJS) use the following code snippet: ```js require('es6-promise').polyfill(); ``` Alternatively ```js require('es6-promise/auto'); ``` Notice that we don't assign the result of `polyfill()` to any variable. The `polyfill()` method will patch the global environment (in this case to the `Promise` name) when called. ## Building & Testing You will need to have PhantomJS installed globally in order to run the tests. `npm install -g phantomjs` * `npm run build` to build * `npm test` to run tests * `npm start` to run a build watcher, and webserver to test * `npm run test:server` for a testem test runner and watching builder # Growly # Simple zero-dependency Growl notifications using GNTP. ## Installation ## Install growly using `npm`: ``` npm install growly ``` And then require it: ```javascript var growly = require('growly'); ``` This module uses the Growl Network Transport Protocol (GNTP) which was implemented in Growl since version 1.3, so you **must have an appropriate version of Growl installed** for Growly to work. ## Example ## Sending a minimal Growl notification: ```javascript var growly = require('growly'); growly.notify('This is as easy as it gets', { title: 'Hello, World!' }); ``` More examples can be found in the *example/* directory. ## Usage ## The growly module exposes only three methods: `Growly.register()`, `Growly.notify()`, and `Growly.setHost()`. ### Growly.register(appname, [appicon], [notifications], [callback]) ### Registers a new application with Growl. Registration is completely optional since it will be performed automatically for you with sensible defaults. Useful if you want your application, with its own icon and types of notifications, to show up in Growl's prefence panel. - `appname` the name of the application (required.) - `appicon` url, file path, or Buffer instance for an application icon image. - `notifications` a list of defined notification types with the following properties: - `.label` name used to identify the type of notification being used (required.) - `.dispname` name users will see in Growl's preference panel (defaults to `.label`.) - `.enabled` whether or not notifications of this type are enabled (defaults to true.) - `callback` called when the registration completes; if registration fails, the first argument will be an Error object. An example: ```javascript growly.register('My Application', 'path/to/icon.png', [ { label: 'success', dispname: 'Success' }, { label: 'warning', dispname: 'Warning', enabled: false } ], function(err) { console.log(err || 'Registration successful!'); }); ``` ### Growly.notify(text, [opts], [callback]) ### Sends a Growl notification. If an application wasn't registered beforehand with `growly.register()`, a default application will automatically be registered beforesending the notification. - `text` the body of the notification. - `opts` an object with the following properties: - `.title` title of the notification. - `.icon` url, file path, or Buffer instance for the notification's icon. - `.sticky` whether or not to sticky the notification (defaults to false.) - `.label` type of notification to use (defaults to the first registered notification type.) - `.priority` the priority of the notification from lowest (-2) to highest (2). - `.coalescingId` replace/update the matching previous notification. May be ignored. - `callback` called when the user has closed/clicked the notification. The callback is passed an Error object `err` as the first argument when the notification fails; otherwise, the second argument `action` is a string that'll describe which action has been taken by the user (either 'closed' or 'clicked'.) An example: ```javascript /* Assuming an application was registered with a notification type labeled 'warning'. */ growly.notify('Stuffs broken!', { label: 'warning' }, function(err, action) { console.log('Action:', action); }); ``` ### Growly.setHost(host, port) ### Set the host and port that Growl (GNTP) requests will be sent to. Using this method is optional since GNTP defaults to using host 'localhost' and port 23053. ## License ## Copyright (C) 2014 Ibrahim Al-Rajhi <abrahamalrajhi@gmail.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. ```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') ``` # 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;julian@juliangruber.com&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. # 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._ # 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 ``` # [postcss][postcss]-svgo > Optimise inline SVG with PostCSS. ## Install With [npm](https://npmjs.org/package/postcss-svgo) do: ``` npm install postcss-svgo --save ``` ## Example ### Input ```css h1 { background: url('data:image/svg+xml;charset=utf-8,<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve"><circle cx="50" cy="50" r="40" fill="yellow" /></svg>'); } h2 { background: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48IURPQ1RZUEUgc3ZnIFBVQkxJQyAiLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4iICJodHRwOi8vd3d3LnczLm9yZy9HcmFwaGljcy9TVkcvMS4xL0RURC9zdmcxMS5kdGQiPjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iTGF5ZXJfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+PGNpcmNsZSBjeD0iNTAiIGN5PSI1MCIgcj0iNDAiIGZpbGw9InllbGxvdyIgLz48IS0tdGVzdCBjb21tZW50LS0+PC9zdmc+'); } ``` ### Output ```css h1 { background: url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg"><circle cx="50" cy="50" r="40" fill="%23ff0"/></svg>'); } h2 { background: url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxjaXJjbGUgY3g9IjUwIiBjeT0iNTAiIHI9IjQwIiBmaWxsPSIjZmYwIi8+PC9zdmc+'); } ``` ## API ### `svgo([options])` Note that postcss-svgo is an *asynchronous* processor. It cannot be used like this: ```js var result = postcss([ svgo() ]).process(css).css; console.log(result); ``` Instead make sure your PostCSS runner uses the asynchronous API: ```js postcss([ svgo() ]).process(css).then(function (result) { console.log(result.css); }); ``` #### options ##### encode Type: `boolean` Default: `undefined` If `true`, it will encode URL-unsafe characters such as `<`, `>` and `&`; `false` will decode these characters, and `undefined` will neither encode nor decode the original input. Note that regardless of this setting, `#` will always be URL-encoded. ##### plugins Optionally, you can customise the output by specifying the `plugins` option. You will need to provide the config in comma separated objects, like the example below. Note that you can either disable the plugin by setting it to `false`, or pass different options to change the default behaviour. ```js var postcss = require('postcss'); var svgo = require('postcss-svgo'); var opts = { plugins: [{ removeDoctype: false }, { removeComments: false }, { cleanupNumericValues: { floatPrecision: 2 } }, { convertColors: { names2hex: false, rgb2hex: false } }] }; postcss([ svgo(opts) ]).process(css).then(function (result) { console.log(result.css) }); ``` You can view the [full list of plugins here][plugins]. ## Usage See the [PostCSS documentation](https://github.com/postcss/postcss#usage) for examples for your environment. ## Contributors See [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md). ## License MIT © [Ben Briggs](http://beneb.info) [postcss]: https://github.com/postcss/postcss [plugins]: https://github.com/svg/svgo/tree/master/plugins # 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 # 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 # Decode According to the WHATWG Encoding Standard This package provides a thin layer on top of [iconv-lite](https://github.com/ashtuchkin/iconv-lite) which makes it expose some of the same primitives as the [Encoding Standard](https://encoding.spec.whatwg.org/). ```js const whatwgEncoding = require("whatwg-encoding"); console.assert(whatwgEncoding.labelToName("latin1") === "windows-1252"); console.assert(whatwgEncoding.labelToName(" CYRILLic ") === "ISO-8859-5"); console.assert(whatwgEncoding.isSupported("IBM866") === true); // Not supported by the Encoding Standard console.assert(whatwgEncoding.isSupported("UTF-32") === false); // In the Encoding Standard, but this package can't decode it console.assert(whatwgEncoding.isSupported("x-mac-cyrillic") === false); console.assert(whatwgEncoding.getBOMEncoding(new Buffer([0xFE, 0xFF])) === "UTF-16BE"); console.assert(whatwgEncoding.getBOMEncoding(new Buffer([0x48, 0x69])) === null); console.assert(whatwgEncoding.decode(new Buffer([0x48, 0x69]), "UTF-8") === "Hi"); ``` ## API - `decode(buffer, fallbackEncodingName)`: performs the [decode](https://encoding.spec.whatwg.org/#decode) algorithm (in which any BOM will override the passed fallback encoding), and returns the resulting string - `labelToName(label)`: performs the [get an encoding](https://encoding.spec.whatwg.org/#concept-encoding-get) algorithm and returns the resulting encoding's name, or `null` for failure - `isSupported(name)`: returns whether the encoding is one of [the encodings](https://encoding.spec.whatwg.org/#names-and-labels) of the Encoding Standard, _and_ is an encoding that this package can decode (via iconv-lite) - `getBOMEncoding(buffer)`: sniffs the first 2–3 bytes of the supplied `Buffer`, returning one of the encoding names `"UTF-8"`, `"UTF-16LE"`, or `"UTF-16BE"` if the appropriate BOM is present, or `null` if no BOM is present ## Unsupported encodings Since we rely on iconv-lite, we are limited to support only the encodings that they support. Currently we are missing support for: - ISO-2022-JP - ISO-8859-8-I - replacement - x-mac-cyrillic - x-user-defined Passing these encoding names will return `false` when calling `isSupported`, and passing any of the possible labels for these encodings to `labelToName` will return `null`. ## Credits This package was originally based on the excellent work of [@nicolashenry](https://github.com/nicolashenry), [in jsdom](https://github.com/tmpvar/jsdom/blob/7ce11776ce161e8d5921a7a183585327400f786b/lib/jsdom/living/helpers/encoding.js). It has since been pulled out into this separate package. ## Alternatives If you are looking for a JavaScript implementation of the Encoding Standard's `TextEncoder` and `TextDecoder` APIs, you'll want [@inexorabletash](https://github.com/inexorabletash)'s [text-encoding](https://github.com/inexorabletash/text-encoding) package. # <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 # 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. ![](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. ## 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) # 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' ``` # 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. # Validate XML Names and Qualified Names This package simply tells you whether or not a string matches the [`Name`](http://www.w3.org/TR/xml/#NT-Name) or [`QName`](http://www.w3.org/TR/xml-names/#NT-QName) productions in the XML Namespaces specification. We use it for implementing the [validate](https://dom.spec.whatwg.org/#validate) algorithm in jsdom, but you can use it for whatever you want. ## Usage This package's main module's default export takes a string and will return an object of the form `{ success, error }`, where `success` is a boolean and if it is `false`, then `error` is a string containing some hint as to where the match went wrong. ```js "use strict": var xnv = require("xml-name-validator"); var assert = require("assert"); // Will return { success: true, error: undefined } xnv.name("x"); xnv.name(":"); xnv.name("a:0"); xnv.name("a:b:c"); // Will return { success: false, error: <an explanatory string> } xnv.name("\\"); xnv.name("'"); xnv.name("0"); xnv.name("a!"); // Will return { success: true, error: undefined } xnv.qname("x"); xnv.qname("a0"); xnv.qname("a:b"); // Will return { success: false, error: <an explanatory string> } xnv.qname(":a"); xnv.qname(":b"); xnv.qname("a:b:c"); xnv.qname("a:0"); ``` # 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) # 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._ 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:dmitry@codingrobots.com).** 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/) [![npm][npm]][npm-url] [![node]]() [![deps][deps]][deps-url] [![tests][tests]][tests-url] [![coverage][cover]][cover-url] [![chat][chat]][chat-url] <div align="center"> <a href="https://github.com/posthtml/posthtml"> <img width="200" height="200" alt="PostHTML" src="http://posthtml.github.io/posthtml/logo.svg"> </a> <h1>PostHTML Render</h1> <p>Renders a PostHTML Tree to HTML/XML</p> </div> <h2 align="center">Install</h2> ```bash npm i -D posthtml-render ``` > ℹ️ This module is also available for [bower](http://bower.io) and as an AMD, CommonJS and IIFE (global) module, uncompressed and compressed <h2 align="center">Usage</h2> ### `NodeJS` ```js const render = require('posthtml-render') const tree = [] const node = {} node.tag = 'ul' node.attrs = { class: 'list' } node.content = [ 'one', 'two', 'three' ].map((content) => ({ tag: 'li', content })) tree.push(node) const html = render(tree, options) ``` ```html <ul class="list"> <li>one</li> <li>two</li> <li>three</li> </ul> ``` ### `🌐 Browser` ```html <!DOCTYPE html> <html> <head> <title>Title</title> <script src="./node_modules/posthtml-render/lib/browser.min.js"></script> <script > const tree = { tag: 'h1', attrs: { style: 'color: red;' }, content: [ 'Title' ] } window.onload = function () { document.body.innerHTML = render(tree) } </script> </head> <body></body> </html> ``` <h2 align="center">Options</h2> |Name|Type|Default|Description| |:--:|:--:|:-----:|:----------| |**[`singleTags`](#singletags)**|`{Array<String\|RegExp>}`|`[]`|Specify custom single tags (self closing)| |**[`closingSingleTag`](#closingSingleTag)**|`{String}`|[`>`](#default)|Specify the single tag closing format| |**[`quoteAllAttributes`](#quoteAllAttributes)**|`{Boolean}`|[`true`](#default)|Put double quotes around all tags, even when not necessary.| ### `singleTags` Specify custom single tags (self closing) ### `{String}` ```js const render = require('posthtml-render') const tree = [ { tag: 'name' } ] const options = { singleTags: [ 'name' ] } const html = render(tree, options) ``` **result.html** ```html <name> ``` #### `{RegExp}` ```js const render = require('posthtml-render') const tree = [ { tag: '%=title%' } ] const options = { singleTags: [ '/^%.*%$/' ] } const html = render(tree, options) ``` **result.html** ```html <%=title%> ``` ### `closingSingleTag` Specify the single tag closing format #### `Formats` ```js const render = require('posthtml-render') const tree = [ { tag: 'img' } ] ``` ##### `'tag'` ```js const html = render(tree, { closingSingleTag: 'tag' }) ``` ```html <custom></custom> ``` ##### `'slash'` ```js const html = render(tree, { closingSingleTag: 'slash' }) ``` ```html <custom /> ``` ##### `'default' (Default)` ```js const html = render(tree) ``` ```html <img></img> ``` ### `quoteAllAttributes` Specify if all attributes should be quoted. ##### `true (Default)` ```html <script src="index.js"></script> ``` ##### `false` ```html <script src=index.js></script> ``` [npm]: https://img.shields.io/npm/v/posthtml-render.svg [npm-url]: https://npmjs.com/package/posthtml-render [node]: https://img.shields.io/node/v/posthtml-render.svg [node-url]: https://img.shields.io/node/v/posthtml-render.svg [deps]: https://david-dm.org/posthtml/posthtml-render.svg [deps-url]: https://david-dm.org/posthtml/posthtml-render [tests]: http://img.shields.io/travis/posthtml/posthtml-render.svg [tests-url]: https://travis-ci.org/posthtml/posthtml-render [cover]: https://coveralls.io/repos/github/posthtml/posthtml-render/badge.svg [cover-url]: https://coveralls.io/github/posthtml/posthtml-render [chat]: https://badges.gitter.im/posthtml/posthtml.svg [chat-url]: https://gitter.im/posthtml/posthtml # 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] } ``` # 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). # v8-to-istanbul [![Build Status](https://travis-ci.org/istanbuljs/v8-to-istanbul.svg?branch=master)](https://travis-ci.org/istanbuljs/v8-to-istanbul) [![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/istanbuljs/v8-to-istanbul) converts from v8 coverage format to [istanbul's coverage format](https://github.com/gotwarlost/istanbul/blob/master/coverage.json.md). ## Usage ```js const v8toIstanbul = require('v8-to-istanbul') // the path to the original source-file is required, as its contents are // used during the conversion algorithm. const converter = v8toIstanbul('./path-to-instrumented-file.js') await converter.load() // this is required due to the async source-map dependency. // provide an array of coverage information in v8 format. converter.applyCoverage([ { "functionName": "", "ranges": [ { "startOffset": 0, "endOffset": 520, "count": 1 } ], "isBlockCoverage": true }, // ... ]) // output coverage information in a form that can // be consumed by Istanbul. console.info(JSON.stringify(converter.toIstanbul())) ``` ## Ignoring Uncovered Lines Sometimes you might find yourself wanting to ignore uncovered lines in your application (for example, perhaps you run your tests in Linux, but there's code that only executes on Windows). To ignore lines, use the special comment `/* c8 ignore next */`. ### ignoring the next line ```js const myVariable = 99 /* c8 ignore next */ if (process.platform === 'win32') console.info('hello world') ``` ### ignoring the next N lines ```js const myVariable = 99 /* c8 ignore next 3 */ if (process.platform === 'win32') { console.info('hello world') } ``` ### ignoring the same line as the comment ```js const myVariable = 99 const os = process.platform === 'darwin' ? 'OSXy' /* c8 ignore next */ : 'Windowsy' ``` ## Testing To execute tests, simply run: ```bash npm test ``` # capture-exit [![Build status](https://ci.appveyor.com/api/projects/status/8044m918rwic8b9n/branch/master?svg=true)](https://ci.appveyor.com/project/embercli/capture-exit/branch/master) [![Build Status](https://travis-ci.org/ember-cli/capture-exit.svg?branch=master)](https://travis-ci.org/ember-cli/capture-exit) Allow cooprative async exit handlers, we unfortunately must hijack process.exit. It allows a handler to ensure exit, without that exit handler impeding other similar handlers for example, see: [sindresorhus/ora#27](https://github.com/sindresorhus/ora/issues/27) Differences between `process.on('exit')` and `captureExit.onExit(...)` => https://github.com/ember-cli/capture-exit/issues/12 ### Installation ```sh yarn add capture-exit // or npm install --save capture-exit ``` ### Usage ```js // as early in startup as possible require('capture-exit').captureExit(); // when you want to schedule some work on exit: function onExit() { return something.processWillExit(); // you can return promises, which will pause exit until fulfilled } require('capture-exit').onExit(onExit); // add an exit handler require('capture-exit').offExit(onExit); // allows one to remove an exit handle if it is not longer required ``` 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 => foo@foo.com 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` 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 # 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) - [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/jsdom/jsdom) project. [![Build Status](https://secure.travis-ci.org/kriskowal/q.svg?branch=master)](http://travis-ci.org/kriskowal/q) [![CDNJS](https://img.shields.io/cdnjs/v/q.js.svg)](https://cdnjs.com/libraries/q.js) <a href="http://promises-aplus.github.com/promises-spec"> <img src="http://kriskowal.github.io/q/q.png" align="right" alt="Q logo" /> </a> If a function cannot return a value or throw an exception without blocking, it can return a promise instead. A promise is an object that represents the return value or the thrown exception that the function may eventually provide. A promise can also be used as a proxy for a [remote object][Q-Connection] to overcome latency. [Q-Connection]: https://github.com/kriskowal/q-connection On the first pass, promises can mitigate the “[Pyramid of Doom][POD]”: the situation where code marches to the right faster than it marches forward. [POD]: http://calculist.org/blog/2011/12/14/why-coroutines-wont-work-on-the-web/ ```javascript step1(function (value1) { step2(value1, function(value2) { step3(value2, function(value3) { step4(value3, function(value4) { // Do something with value4 }); }); }); }); ``` With a promise library, you can flatten the pyramid. ```javascript Q.fcall(promisedStep1) .then(promisedStep2) .then(promisedStep3) .then(promisedStep4) .then(function (value4) { // Do something with value4 }) .catch(function (error) { // Handle any error from all above steps }) .done(); ``` With this approach, you also get implicit error propagation, just like `try`, `catch`, and `finally`. An error in `promisedStep1` will flow all the way to the `catch` function, where it’s caught and handled. (Here `promisedStepN` is a version of `stepN` that returns a promise.) The callback approach is called an “inversion of control”. A function that accepts a callback instead of a return value is saying, “Don’t call me, I’ll call you.”. Promises [un-invert][IOC] the inversion, cleanly separating the input arguments from control flow arguments. This simplifies the use and creation of API’s, particularly variadic, rest and spread arguments. [IOC]: http://www.slideshare.net/domenicdenicola/callbacks-promises-and-coroutines-oh-my-the-evolution-of-asynchronicity-in-javascript ## Getting Started The Q module can be loaded as: - A ``<script>`` tag (creating a ``Q`` global variable): ~2.5 KB minified and gzipped. - A Node.js and CommonJS module, available in [npm](https://npmjs.org/) as the [q](https://npmjs.org/package/q) package - An AMD module - A [component](https://github.com/component/component) as ``microjs/q`` - Using [bower](http://bower.io/) as `q#^1.4.1` - Using [NuGet](http://nuget.org/) as [Q](https://nuget.org/packages/q) Q can exchange promises with jQuery, Dojo, When.js, WinJS, and more. ## Resources Our [wiki][] contains a number of useful resources, including: - A method-by-method [Q API reference][reference]. - A growing [examples gallery][examples], showing how Q can be used to make everything better. From XHR to database access to accessing the Flickr API, Q is there for you. - There are many libraries that produce and consume Q promises for everything from file system/database access or RPC to templating. For a list of some of the more popular ones, see [Libraries][]. - If you want materials that introduce the promise concept generally, and the below tutorial isn't doing it for you, check out our collection of [presentations, blog posts, and podcasts][resources]. - A guide for those [coming from jQuery's `$.Deferred`][jquery]. We'd also love to have you join the Q-Continuum [mailing list][]. [wiki]: https://github.com/kriskowal/q/wiki [reference]: https://github.com/kriskowal/q/wiki/API-Reference [examples]: https://github.com/kriskowal/q/wiki/Examples-Gallery [Libraries]: https://github.com/kriskowal/q/wiki/Libraries [resources]: https://github.com/kriskowal/q/wiki/General-Promise-Resources [jquery]: https://github.com/kriskowal/q/wiki/Coming-from-jQuery [mailing list]: https://groups.google.com/forum/#!forum/q-continuum ## Tutorial Promises have a ``then`` method, which you can use to get the eventual return value (fulfillment) or thrown exception (rejection). ```javascript promiseMeSomething() .then(function (value) { }, function (reason) { }); ``` If ``promiseMeSomething`` returns a promise that gets fulfilled later with a return value, the first function (the fulfillment handler) will be called with the value. However, if the ``promiseMeSomething`` function gets rejected later by a thrown exception, the second function (the rejection handler) will be called with the exception. Note that resolution of a promise is always asynchronous: that is, the fulfillment or rejection handler will always be called in the next turn of the event loop (i.e. `process.nextTick` in Node). This gives you a nice guarantee when mentally tracing the flow of your code, namely that ``then`` will always return before either handler is executed. In this tutorial, we begin with how to consume and work with promises. We'll talk about how to create them, and thus create functions like `promiseMeSomething` that return promises, [below](#the-beginning). ### Propagation The ``then`` method returns a promise, which in this example, I’m assigning to ``outputPromise``. ```javascript var outputPromise = getInputPromise() .then(function (input) { }, function (reason) { }); ``` The ``outputPromise`` variable becomes a new promise for the return value of either handler. Since a function can only either return a value or throw an exception, only one handler will ever be called and it will be responsible for resolving ``outputPromise``. - If you return a value in a handler, ``outputPromise`` will get fulfilled. - If you throw an exception in a handler, ``outputPromise`` will get rejected. - If you return a **promise** in a handler, ``outputPromise`` will “become” that promise. Being able to become a new promise is useful for managing delays, combining results, or recovering from errors. If the ``getInputPromise()`` promise gets rejected and you omit the rejection handler, the **error** will go to ``outputPromise``: ```javascript var outputPromise = getInputPromise() .then(function (value) { }); ``` If the input promise gets fulfilled and you omit the fulfillment handler, the **value** will go to ``outputPromise``: ```javascript var outputPromise = getInputPromise() .then(null, function (error) { }); ``` Q promises provide a ``fail`` shorthand for ``then`` when you are only interested in handling the error: ```javascript var outputPromise = getInputPromise() .fail(function (error) { }); ``` If you are writing JavaScript for modern engines only or using CoffeeScript, you may use `catch` instead of `fail`. Promises also have a ``fin`` function that is like a ``finally`` clause. The final handler gets called, with no arguments, when the promise returned by ``getInputPromise()`` either returns a value or throws an error. The value returned or error thrown by ``getInputPromise()`` passes directly to ``outputPromise`` unless the final handler fails, and may be delayed if the final handler returns a promise. ```javascript var outputPromise = getInputPromise() .fin(function () { // close files, database connections, stop servers, conclude tests }); ``` - If the handler returns a value, the value is ignored - If the handler throws an error, the error passes to ``outputPromise`` - If the handler returns a promise, ``outputPromise`` gets postponed. The eventual value or error has the same effect as an immediate return value or thrown error: a value would be ignored, an error would be forwarded. If you are writing JavaScript for modern engines only or using CoffeeScript, you may use `finally` instead of `fin`. ### Chaining There are two ways to chain promises. You can chain promises either inside or outside handlers. The next two examples are equivalent. ```javascript return getUsername() .then(function (username) { return getUser(username) .then(function (user) { // if we get here without an error, // the value returned here // or the exception thrown here // resolves the promise returned // by the first line }) }); ``` ```javascript return getUsername() .then(function (username) { return getUser(username); }) .then(function (user) { // if we get here without an error, // the value returned here // or the exception thrown here // resolves the promise returned // by the first line }); ``` The only difference is nesting. It’s useful to nest handlers if you need to capture multiple input values in your closure. ```javascript function authenticate() { return getUsername() .then(function (username) { return getUser(username); }) // chained because we will not need the user name in the next event .then(function (user) { return getPassword() // nested because we need both user and password next .then(function (password) { if (user.passwordHash !== hash(password)) { throw new Error("Can't authenticate"); } }); }); } ``` ### Combination You can turn an array of promises into a promise for the whole, fulfilled array using ``all``. ```javascript return Q.all([ eventualAdd(2, 2), eventualAdd(10, 20) ]); ``` If you have a promise for an array, you can use ``spread`` as a replacement for ``then``. The ``spread`` function “spreads” the values over the arguments of the fulfillment handler. The rejection handler will get called at the first sign of failure. That is, whichever of the received promises fails first gets handled by the rejection handler. ```javascript function eventualAdd(a, b) { return Q.spread([a, b], function (a, b) { return a + b; }) } ``` But ``spread`` calls ``all`` initially, so you can skip it in chains. ```javascript return getUsername() .then(function (username) { return [username, getUser(username)]; }) .spread(function (username, user) { }); ``` The ``all`` function returns a promise for an array of values. When this promise is fulfilled, the array contains the fulfillment values of the original promises, in the same order as those promises. If one of the given promises is rejected, the returned promise is immediately rejected, not waiting for the rest of the batch. If you want to wait for all of the promises to either be fulfilled or rejected, you can use ``allSettled``. ```javascript Q.allSettled(promises) .then(function (results) { results.forEach(function (result) { if (result.state === "fulfilled") { var value = result.value; } else { var reason = result.reason; } }); }); ``` The ``any`` function accepts an array of promises and returns a promise that is fulfilled by the first given promise to be fulfilled, or rejected if all of the given promises are rejected. ```javascript Q.any(promises) .then(function (first) { // Any of the promises was fulfilled. }, function (error) { // All of the promises were rejected. }); ``` ### Sequences If you have a number of promise-producing functions that need to be run sequentially, you can of course do so manually: ```javascript return foo(initialVal).then(bar).then(baz).then(qux); ``` However, if you want to run a dynamically constructed sequence of functions, you'll want something like this: ```javascript var funcs = [foo, bar, baz, qux]; var result = Q(initialVal); funcs.forEach(function (f) { result = result.then(f); }); return result; ``` You can make this slightly more compact using `reduce`: ```javascript return funcs.reduce(function (soFar, f) { return soFar.then(f); }, Q(initialVal)); ``` Or, you could use the ultra-compact version: ```javascript return funcs.reduce(Q.when, Q(initialVal)); ``` ### Handling Errors One sometimes-unintuitive aspect of promises is that if you throw an exception in the fulfillment handler, it will not be caught by the error handler. ```javascript return foo() .then(function (value) { throw new Error("Can't bar."); }, function (error) { // We only get here if "foo" fails }); ``` To see why this is, consider the parallel between promises and ``try``/``catch``. We are ``try``-ing to execute ``foo()``: the error handler represents a ``catch`` for ``foo()``, while the fulfillment handler represents code that happens *after* the ``try``/``catch`` block. That code then needs its own ``try``/``catch`` block. In terms of promises, this means chaining your rejection handler: ```javascript return foo() .then(function (value) { throw new Error("Can't bar."); }) .fail(function (error) { // We get here with either foo's error or bar's error }); ``` ### Progress Notification It's possible for promises to report their progress, e.g. for tasks that take a long time like a file upload. Not all promises will implement progress notifications, but for those that do, you can consume the progress values using a third parameter to ``then``: ```javascript return uploadFile() .then(function () { // Success uploading the file }, function (err) { // There was an error, and we get the reason for error }, function (progress) { // We get notified of the upload's progress as it is executed }); ``` Like `fail`, Q also provides a shorthand for progress callbacks called `progress`: ```javascript return uploadFile().progress(function (progress) { // We get notified of the upload's progress }); ``` ### The End When you get to the end of a chain of promises, you should either return the last promise or end the chain. Since handlers catch errors, it’s an unfortunate pattern that the exceptions can go unobserved. So, either return it, ```javascript return foo() .then(function () { return "bar"; }); ``` Or, end it. ```javascript foo() .then(function () { return "bar"; }) .done(); ``` Ending a promise chain makes sure that, if an error doesn’t get handled before the end, it will get rethrown and reported. This is a stopgap. We are exploring ways to make unhandled errors visible without any explicit handling. ### The Beginning Everything above assumes you get a promise from somewhere else. This is the common case. Every once in a while, you will need to create a promise from scratch. #### Using ``Q.fcall`` You can create a promise from a value using ``Q.fcall``. This returns a promise for 10. ```javascript return Q.fcall(function () { return 10; }); ``` You can also use ``fcall`` to get a promise for an exception. ```javascript return Q.fcall(function () { throw new Error("Can't do it"); }); ``` As the name implies, ``fcall`` can call functions, or even promised functions. This uses the ``eventualAdd`` function above to add two numbers. ```javascript return Q.fcall(eventualAdd, 2, 2); ``` #### Using Deferreds If you have to interface with asynchronous functions that are callback-based instead of promise-based, Q provides a few shortcuts (like ``Q.nfcall`` and friends). But much of the time, the solution will be to use *deferreds*. ```javascript var deferred = Q.defer(); FS.readFile("foo.txt", "utf-8", function (error, text) { if (error) { deferred.reject(new Error(error)); } else { deferred.resolve(text); } }); return deferred.promise; ``` Note that a deferred can be resolved with a value or a promise. The ``reject`` function is a shorthand for resolving with a rejected promise. ```javascript // this: deferred.reject(new Error("Can't do it")); // is shorthand for: var rejection = Q.fcall(function () { throw new Error("Can't do it"); }); deferred.resolve(rejection); ``` This is a simplified implementation of ``Q.delay``. ```javascript function delay(ms) { var deferred = Q.defer(); setTimeout(deferred.resolve, ms); return deferred.promise; } ``` This is a simplified implementation of ``Q.timeout`` ```javascript function timeout(promise, ms) { var deferred = Q.defer(); Q.when(promise, deferred.resolve); delay(ms).then(function () { deferred.reject(new Error("Timed out")); }); return deferred.promise; } ``` Finally, you can send a progress notification to the promise with ``deferred.notify``. For illustration, this is a wrapper for XML HTTP requests in the browser. Note that a more [thorough][XHR] implementation would be in order in practice. [XHR]: https://github.com/montagejs/mr/blob/71e8df99bb4f0584985accd6f2801ef3015b9763/browser.js#L29-L73 ```javascript function requestOkText(url) { var request = new XMLHttpRequest(); var deferred = Q.defer(); request.open("GET", url, true); request.onload = onload; request.onerror = onerror; request.onprogress = onprogress; request.send(); function onload() { if (request.status === 200) { deferred.resolve(request.responseText); } else { deferred.reject(new Error("Status code was " + request.status)); } } function onerror() { deferred.reject(new Error("Can't XHR " + JSON.stringify(url))); } function onprogress(event) { deferred.notify(event.loaded / event.total); } return deferred.promise; } ``` Below is an example of how to use this ``requestOkText`` function: ```javascript requestOkText("http://localhost:3000") .then(function (responseText) { // If the HTTP response returns 200 OK, log the response text. console.log(responseText); }, function (error) { // If there's an error or a non-200 status code, log the error. console.error(error); }, function (progress) { // Log the progress as it comes in. console.log("Request progress: " + Math.round(progress * 100) + "%"); }); ``` #### Using `Q.Promise` This is an alternative promise-creation API that has the same power as the deferred concept, but without introducing another conceptual entity. Rewriting the `requestOkText` example above using `Q.Promise`: ```javascript function requestOkText(url) { return Q.Promise(function(resolve, reject, notify) { var request = new XMLHttpRequest(); request.open("GET", url, true); request.onload = onload; request.onerror = onerror; request.onprogress = onprogress; request.send(); function onload() { if (request.status === 200) { resolve(request.responseText); } else { reject(new Error("Status code was " + request.status)); } } function onerror() { reject(new Error("Can't XHR " + JSON.stringify(url))); } function onprogress(event) { notify(event.loaded / event.total); } }); } ``` If `requestOkText` were to throw an exception, the returned promise would be rejected with that thrown exception as the rejection reason. ### The Middle If you are using a function that may return a promise, but just might return a value if it doesn’t need to defer, you can use the “static” methods of the Q library. The ``when`` function is the static equivalent for ``then``. ```javascript return Q.when(valueOrPromise, function (value) { }, function (error) { }); ``` All of the other methods on a promise have static analogs with the same name. The following are equivalent: ```javascript return Q.all([a, b]); ``` ```javascript return Q.fcall(function () { return [a, b]; }) .all(); ``` When working with promises provided by other libraries, you should convert it to a Q promise. Not all promise libraries make the same guarantees as Q and certainly don’t provide all of the same methods. Most libraries only provide a partially functional ``then`` method. This thankfully is all we need to turn them into vibrant Q promises. ```javascript return Q($.ajax(...)) .then(function () { }); ``` If there is any chance that the promise you receive is not a Q promise as provided by your library, you should wrap it using a Q function. You can even use ``Q.invoke`` as a shorthand. ```javascript return Q.invoke($, 'ajax', ...) .then(function () { }); ``` ### Over the Wire A promise can serve as a proxy for another object, even a remote object. There are methods that allow you to optimistically manipulate properties or call functions. All of these interactions return promises, so they can be chained. ``` direct manipulation using a promise as a proxy -------------------------- ------------------------------- value.foo promise.get("foo") value.foo = value promise.put("foo", value) delete value.foo promise.del("foo") value.foo(...args) promise.post("foo", [args]) value.foo(...args) promise.invoke("foo", ...args) value(...args) promise.fapply([args]) value(...args) promise.fcall(...args) ``` If the promise is a proxy for a remote object, you can shave round-trips by using these functions instead of ``then``. To take advantage of promises for remote objects, check out [Q-Connection][]. [Q-Connection]: https://github.com/kriskowal/q-connection Even in the case of non-remote objects, these methods can be used as shorthand for particularly-simple fulfillment handlers. For example, you can replace ```javascript return Q.fcall(function () { return [{ foo: "bar" }, { foo: "baz" }]; }) .then(function (value) { return value[0].foo; }); ``` with ```javascript return Q.fcall(function () { return [{ foo: "bar" }, { foo: "baz" }]; }) .get(0) .get("foo"); ``` ### Adapting Node If you're working with functions that make use of the Node.js callback pattern, where callbacks are in the form of `function(err, result)`, Q provides a few useful utility functions for converting between them. The most straightforward are probably `Q.nfcall` and `Q.nfapply` ("Node function call/apply") for calling Node.js-style functions and getting back a promise: ```javascript return Q.nfcall(FS.readFile, "foo.txt", "utf-8"); return Q.nfapply(FS.readFile, ["foo.txt", "utf-8"]); ``` If you are working with methods, instead of simple functions, you can easily run in to the usual problems where passing a method to another function—like `Q.nfcall`—"un-binds" the method from its owner. To avoid this, you can either use `Function.prototype.bind` or some nice shortcut methods we provide: ```javascript return Q.ninvoke(redisClient, "get", "user:1:id"); return Q.npost(redisClient, "get", ["user:1:id"]); ``` You can also create reusable wrappers with `Q.denodeify` or `Q.nbind`: ```javascript var readFile = Q.denodeify(FS.readFile); return readFile("foo.txt", "utf-8"); var redisClientGet = Q.nbind(redisClient.get, redisClient); return redisClientGet("user:1:id"); ``` Finally, if you're working with raw deferred objects, there is a `makeNodeResolver` method on deferreds that can be handy: ```javascript var deferred = Q.defer(); FS.readFile("foo.txt", "utf-8", deferred.makeNodeResolver()); return deferred.promise; ``` ### Long Stack Traces Q comes with optional support for “long stack traces,” wherein the `stack` property of `Error` rejection reasons is rewritten to be traced along asynchronous jumps instead of stopping at the most recent one. As an example: ```js function theDepthsOfMyProgram() { Q.delay(100).done(function explode() { throw new Error("boo!"); }); } theDepthsOfMyProgram(); ``` usually would give a rather unhelpful stack trace looking something like ``` Error: boo! at explode (/path/to/test.js:3:11) at _fulfilled (/path/to/test.js:q:54) at resolvedValue.promiseDispatch.done (/path/to/q.js:823:30) at makePromise.promise.promiseDispatch (/path/to/q.js:496:13) at pending (/path/to/q.js:397:39) at process.startup.processNextTick.process._tickCallback (node.js:244:9) ``` But, if you turn this feature on by setting ```js Q.longStackSupport = true; ``` then the above code gives a nice stack trace to the tune of ``` Error: boo! at explode (/path/to/test.js:3:11) From previous event: at theDepthsOfMyProgram (/path/to/test.js:2:16) at Object.<anonymous> (/path/to/test.js:7:1) ``` Note how you can see the function that triggered the async operation in the stack trace! This is very helpful for debugging, as otherwise you end up getting only the first line, plus a bunch of Q internals, with no sign of where the operation started. In node.js, this feature can also be enabled through the Q_DEBUG environment variable: ``` Q_DEBUG=1 node server.js ``` This will enable long stack support in every instance of Q. This feature does come with somewhat-serious performance and memory overhead, however. If you're working with lots of promises, or trying to scale a server to many users, you should probably keep it off. But in development, go for it! ## Tests You can view the results of the Q test suite [in your browser][tests]! [tests]: https://rawgithub.com/kriskowal/q/v1/spec/q-spec.html ## License Copyright 2009–2017 Kristopher Michael Kowal and contributors MIT License (enclosed) # CSS Modules: css-selector-tokenizer [![Build Status](https://travis-ci.org/css-modules/css-selector-tokenizer.svg?branch=master)](https://travis-ci.org/css-modules/css-selector-tokenizer) [![coveralls.io](https://coveralls.io/repos/css-modules/css-selector-tokenizer/badge.svg?branch=master)](https://coveralls.io/r/css-modules/css-selector-tokenizer?branch=master) [![codecov.io](https://codecov.io/github/css-modules/css-selector-tokenizer/coverage.svg?branch=master)](https://codecov.io/github/css-modules/css-selector-tokenizer?branch=master) Parses and stringifies CSS selectors. ``` js import Tokenizer from "css-selector-tokenizer"; let input = "a#content.active > div::first-line [data-content], a:not(:visited)"; Tokenizer.parse(input); // === expected let expected = { type: "selectors", nodes: [ { type: "selector", nodes: [ { type: "element", name: "a" }, { type: "id", name: "content" }, { type: "class", name: "active" }, { type: "operator", operator: ">", before: " ", after: " " }, { type: "element", name: "div" }, { type: "pseudo-element", name: "first-line" }, { type: "spacing", value: " " }, { type: "attribute", content: "data-content" }, ] }, { type: "selector", nodes: [ { type: "element", name: "a" }, { type: "nested-pseudo-class", name: "not", nodes: [ { type: "selector", nodes: [ { type: "pseudo-class", name: "visited" } ] } ] } ], before: " " } ] } Tokenizer.stringify(expected) // === input // * => { type: "universal" } // foo|element = { type: "element", name: "element", namespace: "foo" } // *|* = { type: "universal", namespace: "*" } // :has(h1, h2) => { type: "nested-pseudo-class", name: "has", nodes: [ // { // type: "selector", // nodes: [ // { type: "element", name: "h1" } // ] // }, // { // type: "selector", // nodes: [ // { type: "element", name: "h2" } // ], // before: " " // } // ] } ``` ## Building ``` npm install npm test ``` ## Development - `npm test -- -w` will watch `lib` and `test` for changes and retest ## License MIT ## With thanks - Mark Dalgleish - Glen Maddern - Guy Bedford --- Tobias Koppers, 2015. # babel-plugin-dynamic-import-node Babel plugin to transpile `import()` to a deferred `require()`, for node. Matches the [proposed spec](https://github.com/domenic/proposal-import-function). **NOTE:** Babylon >= v6.12.0 is required to correctly parse dynamic imports. ## Installation ```sh npm install babel-plugin-dynamic-import-node --save-dev ``` ## Usage ### Via `.babelrc` (Recommended) **.babelrc** ```json { "plugins": ["dynamic-import-node"] } ``` #### Options - *`noInterop`* - A boolean value, that if true will not interop the require calls. Useful to avoid using `require('module').default` on commonjs modules. ```json { "plugins": [ ["dynamic-import-node", { "noInterop": true }] ] } ``` ### Via CLI ```sh $ babel --plugins dynamic-import-node script.js ``` ### Via Node API ```javascript require('babel-core').transform('code', { plugins: ['dynamic-import-node'] }); ``` ### Code Example ```javascript Promise.all([ import('./lib/import1'), import('./lib/import2') ]).then(([ Import1, Import2 ]) => { console.log(Import1); /* CODE HERE*/ }); ``` # 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. 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)); ``` # 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. 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. 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> # <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 # 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'. # 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 # lodash.memoize v4.1.2 The [lodash](https://lodash.com/) method `_.memoize` exported as a [Node.js](https://nodejs.org/) module. ## Installation Using npm: ```bash $ {sudo -H} npm i -g npm $ npm i --save lodash.memoize ``` In Node.js: ```js var memoize = require('lodash.memoize'); ``` See the [documentation](https://lodash.com/docs#memoize) or [package source](https://github.com/lodash/lodash/blob/4.1.2-npm-packages/lodash.memoize) for more details. 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, 11, 12, 13 and 14.** ***Current version: 2.14.1*** *(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)** * **[Known 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://v8.dev/docs/embed) * [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.16/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. # 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._ # 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._ # MDN data [https://github.com/mdn/data](https://github.com/mdn/data) Maintained by the [MDN team at Mozilla](https://wiki.mozilla.org/MDN). This repository contains general data for Web technologies. This data is used in MDN documentation, to build [information boxes](https://developer.mozilla.org/en-US/docs/Web/CSS/background) or [sidebar navigation](https://developer.mozilla.org/en-US/docs/Web/API/Window). External tools have started to make use of this data as well. For example, the [CSSTree](https://github.com/csstree/csstree/) CSS parser. [![NPM version](https://img.shields.io/npm/v/mdn-data.svg)](https://www.npmjs.com/package/mdn-data) [![Build Status](https://travis-ci.org/mdn/data.svg?branch=master)](https://travis-ci.org/mdn/data) ## Repository contents There's a top-level directory for each broad area covered: for example, "api", "css", "svg". Inside each of these directories is one or more JSON files containing the data. ### api Contains data about Web APIs: * API inheritance (interface inheritance and mixin implementations) ### css Contains data about: * CSS at-rules * CSS properties * CSS selectors * CSS syntaxes * CSS types * CSS units Read more about [CSS data](https://github.com/mdn/data/blob/master/css/readme.md) and the format of the files. ### l10n The l10n folder contains localization strings that are used in the various json files throughout this repository. ## Problems? If you find a problem, please [file an issue](https://github.com/mdn/data/issues/new). ## Contributing We're very happy to accept contributions to this data. Please familiarize yourself with the schema for the data you're editing, and send us a pull request. See also the [Contributing file](https://github.com/mdn/data/blob/master/CONTRIBUTING.md) for more information. ## See also * [https://github.com/mdn/browser-compat-data](https://github.com/mdn/browser-compat-data) for compatibility data for Web technologies. # 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/become_a_patron_button@2x.png" 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._ String.prototype.trimEnd <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 ES2019-spec-compliant `String.prototype.trimEnd` shim. Invoke its "shim" method to shim `String.prototype.trimEnd` if it is unavailable. 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](http://www.ecma-international.org/ecma-262/6.0/#sec-object.assign). In an ES6 environment, it will also work properly with `Symbol`s. Most common usage: ```js var trimEnd = require('string.prototype.trimend'); assert(trimEnd(' \t\na \t\n') === 'a \t\n'); if (!String.prototype.trimEnd) { trimEnd.shim(); } assert(trimEnd(' \t\na \t\n ') === ' \t\na \t\n '.trimEnd()); ``` ## Tests Simply clone the repo, `npm install`, and run `npm test` [package-url]: https://npmjs.com/package/string.prototype.trimend [npm-version-svg]: http://vb.teelaun.ch/es-shims/String.prototype.trimEnd.svg [travis-svg]: https://travis-ci.org/es-shims/String.prototype.trimEnd.svg [travis-url]: https://travis-ci.org/es-shims/String.prototype.trimEnd [deps-svg]: https://david-dm.org/es-shims/String.prototype.trimEnd.svg [deps-url]: https://david-dm.org/es-shims/String.prototype.trimEnd [dev-deps-svg]: https://david-dm.org/es-shims/String.prototype.trimEnd/dev-status.svg [dev-deps-url]: https://david-dm.org/es-shims/String.prototype.trimEnd#info=devDependencies [testling-svg]: https://ci.testling.com/es-shims/String.prototype.trimEnd.png [testling-url]: https://ci.testling.com/es-shims/String.prototype.trimEnd [npm-badge-png]: https://nodei.co/npm/string.prototype.trimend.png?downloads=true&stars=true [license-image]: http://img.shields.io/npm/l/string.prototype.trimend.svg [license-url]: LICENSE [downloads-image]: http://img.shields.io/npm/dm/string.prototype.trimend.svg [downloads-url]: http://npm-stat.com/charts.html?package=string.prototype.trimend # 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) # 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/ # 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;tj@vision-media.ca&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-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) # 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._ [![Travis](https://travis-ci.org/toddbluhm/env-cmd.svg?branch=master)](https://travis-ci.org/toddbluhm/env-cmd) [![Coverage Status](https://coveralls.io/repos/github/toddbluhm/env-cmd/badge.svg?branch=master)](https://coveralls.io/github/toddbluhm/env-cmd?branch=master) [![npm](https://img.shields.io/npm/v/env-cmd.svg?maxAge=86400)](https://www.npmjs.com/package/env-cmd) [![npm](https://img.shields.io/npm/dm/env-cmd.svg?maxAge=86400)](https://www.npmjs.com/package/env-cmd) [![npm](https://img.shields.io/npm/l/env-cmd.svg?maxAge=2592000)](https://www.npmjs.com/package/env-cmd) [![TS-Standard - Typescript Standard Style Guide](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](https://github.com/toddbluhm/ts-standard) [![Greenkeeper badge](https://badges.greenkeeper.io/toddbluhm/env-cmd.svg)](https://greenkeeper.io/) # env-cmd A simple node program for executing commands using an environment from an env file. ## 💾 Install `npm install env-cmd` or `npm install -g env-cmd` ## ⌨️ Basic Usage **Environment file `./.env`** ```text # This is a comment ENV1=THANKS ENV2=FOR ALL ENV3=THE FISH ``` **Package.json** ```json { "scripts": { "test": "env-cmd mocha -R spec" } } ``` **Terminal** ```sh ./node_modules/.bin/env-cmd node index.js ``` ### Using custom env file path To use a custom env filename or path, pass the `-f` flag. This is a major breaking change from prior versions < 9.0.0 **Terminal** ```sh ./node_modules/.bin/env-cmd -f ./custom/path/.env node index.js ``` ## 📜 Help ```text Usage: _ [options] <command> [...args] Options: -v, --version output the version number -e, --environments [env1,env2,...] The rc file environment(s) to use -f, --file [path] Custom env file path (default path: ./.env) --fallback Fallback to default env file path, if custom env file path not found --no-override Do not override existing environment variables -r, --rc-file [path] Custom rc file path (default path: ./.env-cmdrc(|.js|.json) --silent Ignore any env-cmd errors and only fail on executed program failure. --use-shell Execute the command in a new shell with the given environment --verbose Print helpful debugging information -x, --expand-envs Replace $var in args and command with environment variables -h, --help output usage information ``` ## 🔬 Advanced Usage ### `.rc` file usage For more complex projects, a `.env-cmdrc` file can be defined in the root directory and supports as many environments as you want. Simply use the `-e` flag and provide which environments you wish to use from the `.env-cmdrc` file. Using multiple environment names will merge the environment variables together. Later environments overwrite earlier ones in the list if conflicting environment variables are found. **.rc file `./.env-cmdrc`** ```json { "development": { "ENV1": "Thanks", "ENV2": "For All" }, "test": { "ENV1": "No Thanks", "ENV3": "!" }, "production": { "ENV1": "The Fish" } } ``` **Terminal** ```sh ./node_modules/.bin/env-cmd -e production node index.js # Or for multiple environments (where `production` vars override `test` vars, # but both are included) ./node_modules/.bin/env-cmd -e test,production node index.js ``` ### `--no-override` option Prevents overriding of existing environment variables on `process.env` and within the current environment. ### `--fallback` file usage option If the `.env` file does not exist at the provided custom path, then use the default fallback location `./.env` env file instead. ### `--use-shell` Executes the command within a new shell environment. This is useful if you want to string multiple commands together that share the same environment variables. **Terminal** ```sh ./node_modules/.bin/env-cmd -f ./test/.env --use-shell "npm run lint && npm test" ``` ### Asynchronous env file support EnvCmd supports reading from asynchronous `.env` files. Instead of using a `.env` file, pass in a `.js` file that exports either an object or a `Promise` resolving to an object (`{ ENV_VAR_NAME: value, ... }`). Asynchronous `.rc` files are also supported using `.js` file extension and resolving to an object with top level environment names (`{ production: { ENV_VAR_NAME: value, ... } }`). **Terminal** ```sh ./node_modules/.bin/env-cmd -f ./async-file.js node index.js ``` ### `-x` expands vars in arguments EnvCmd supports expanding `$var` values passed in as arguments to the command. The allows a user to provide arguments to a command that are based on environment variable values at runtime. **Terminal** ```sh # $USER will be expanded into the env value it contains at runtime ./node_modules/.bin/env-cmd -x node index.js --user=$USER ``` ### `--silent` suppresses env-cmd errors EnvCmd supports the `--silent` flag the suppresses all errors generated by `env-cmd` while leaving errors generated by the child process and cli signals still usable. This flag is primarily used to allow `env-cmd` to run in environments where the `.env` file might not be present, but still execute the child process without failing due to a missing file. ## 💿 Examples You can find examples of how to use the various options above by visiting the examples repo [env-cmd-examples](https://github.com/toddbluhm/env-cmd-examples). ## 💽️ Environment File Formats These are the currently accepted environment file formats. If any other formats are desired please create an issue. - `.env` as `key=value` - `.env.json` Key/value pairs as JSON - `.env.js` JavaScript file exporting an `object` or a `Promise` that resolves to an `object` - `.env-cmdrc` as valid json or `.env-cmdrc.json` in execution directory with at least one environment `{ "dev": { "key1": "val1" } }` - `.env-cmdrc.js` JavaScript file exporting an `object` or a `Promise` that resolves to an `object` that contains at least one environment ## 🗂 Path Rules This lib attempts to follow standard `bash` path rules. The rules are as followed: Home Directory = `/Users/test` Working Directory = `/Users/test/Development/app` | Type | Input Path | Expanded Path | | -- | -- | ------------- | | Absolute | `/some/absolute/path.env` | `/some/absolute/path.env` | | Home Directory with `~` | `~/starts/on/homedir/path.env` | `/Users/test/starts/on/homedir/path.env` | | Relative | `./some/relative/path.env` or `some/relative/path.env` | `/Users/test/Development/app/some/relative/path.env` | | Relative with parent dir | `../some/relative/path.env` | `/Users/test/Development/some/relative/path.env` | ## 🛠 API Usage ### `EnvCmd` A function that executes a given command in a new child process with the given environment and options - **`options`** { `object` } - **`command`** { `string` }: The command to execute (`node`, `mocha`, ...) - **`commandArgs`** { `string[]` }: List of arguments to pass to the `command` (`['-R', 'Spec']`) - **`envFile`** { `object` } - **`filePath`** { `string` }: Custom path to .env file to read from (defaults to: `./.env`) - **`fallback`** { `boolean` }: Should fall back to default `./.env` file if custom path does not exist - **`rc`** { `object` } - **`environments`** { `string[]` }: List of environment to read from the `.rc` file - **`filePath`** { `string` }: Custom path to the `.rc` file (defaults to: `./.env-cmdrc(|.js|.json)`) - **`options`** { `object` } - **`expandEnvs`** { `boolean` }: Expand `$var` values passed to `commandArgs` (default: `false`) - **`noOverride`** { `boolean` }: Prevent `.env` file vars from overriding existing `process.env` vars (default: `false`) - **`silent`** { `boolean` }: Ignore any errors thrown by env-cmd, used to ignore missing file errors (default: `false`) - **`useShell`** { `boolean` }: Runs command inside a new shell instance (default: `false`) - **`verbose`** { `boolean` }: Prints extra debug logs to `console.info` (default: `false`) - **Returns** { `Promise<object>` }: key is env var name and value is the env var value ### `GetEnvVars` A function that parses environment variables from a `.env` or a `.rc` file - **`options`** { `object` } - **`envFile`** { `object` } - **`filePath`** { `string` }: Custom path to .env file to read from (defaults to: `./.env`) - **`fallback`** { `boolean` }: Should fall back to default `./.env` file if custom path does not exist - **`rc`** { `object` } - **`environments`** { `string[]` }: List of environment to read from the `.rc` file - **`filePath`** { `string` }: Custom path to the `.rc` file (defaults to: `./.env-cmdrc(|.js|.json)`) - **`verbose`** { `boolean` }: Prints extra debug logs to `console.info` (default: `false`) - **Returns** { `Promise<object>` }: key is env var name and value is the env var value ## 🧙 Why Because sometimes it is just too cumbersome passing a lot of environment variables to scripts. It is usually just easier to have a file with all the vars in them, especially for development and testing. 🚨**Do not commit sensitive environment data to a public git repo!** 🚨 ## 🧬 Related Projects [`cross-env`](https://github.com/kentcdodds/cross-env) - Cross platform setting of environment scripts ## 🎊 Special Thanks Special thanks to [`cross-env`](https://github.com/kentcdodds/cross-env) for inspiration (uses the same `cross-spawn` lib underneath too). ## 📋 Contributing Guide I welcome all pull requests. Please make sure you add appropriate test cases for any features added. Before opening a PR please make sure to run the following scripts: - `npm run lint` checks for code errors and format according to [ts-standard](https://github.com/toddbluhm/ts-standard) - `npm test` make sure all tests pass - `npm run test-cover` make sure the coverage has not decreased from current master # 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> # 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). # <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 # 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 # is-resolvable [![npm version](https://img.shields.io/npm/v/is-resolvable.svg)](https://www.npmjs.com/package/is-resolvable) [![Build Status](https://travis-ci.org/shinnn/is-resolvable.svg?branch=master)](https://travis-ci.org/shinnn/is-resolvable) [![Build status](https://ci.appveyor.com/api/projects/status/ww1cdpignehlasbs?svg=true)](https://ci.appveyor.com/project/ShinnosukeWatanabe/is-resolvable) [![Coverage Status](https://img.shields.io/coveralls/shinnn/is-resolvable.svg)](https://coveralls.io/r/shinnn/is-resolvable) A [Node.js](https://nodejs.org/) module to check if a given module ID is resolvable with [`require()`](https://nodejs.org/api/globals.html#globals_require) ```javascript const isResolvable = require('is-resolvable'); isResolvable('fs'); //=> true isResolvable('path'); //=> true // When ./index.js exists isResolvable('./index.js') //=> true isResolvable('./index') //=> true isResolvable('.') //=> true ``` ## Installation [Use](https://docs.npmjs.com/cli/install) [npm](https://docs.npmjs.com/getting-started/what-is-npm). ``` npm install is-resolvable ``` ## API ```javascript const isResolvable = require('is-resolvable'); ``` ### isResolvable(*moduleId* [, *options*]) *moduleId*: `string` (module ID) *options*: `Object` ([`require.resolve`](https://nodejs.org/api/modules.html#modules_require_resolve_request_options) options) Return: `boolean` It returns `true` if `require()` can load a file form a given module ID, otherwise `false`. ```javascript const isResolvable = require('is-resolvable'); // When ./foo.json exists isResolvable('./foo.json'); //=> true isResolvable('./foo'); //=> true isResolvable('./foo.js'); //=> false // When `eslint` module is installed but `jshint` isn't isResolvable('eslint'); //=> true isResolvable('jshint'); //=> false // When `lodash` module is installed isResolvable('lodash/isObject'); //=> true isResolvable('lodash/fp/reject.js'); //=> true ``` The second argument accepts an options object for `require.resolve()`. ```javascript // When ./bar/baz.js exists isResolvable('./baz.js'); //=> false isResolvable('./baz.js', {paths: ['bar']}); //=> true ``` ## License [ISC License](./LICENSE) © 2018 Shinnosuke Watanabe 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> # [postcss][postcss]-reduce-transforms > Reduce transform functions with PostCSS. ## Install With [npm](https://npmjs.org/package/postcss-reduce-transforms) do: ``` npm install postcss-reduce-transforms --save ``` ## Example This module will reduce transform functions where possible. For more examples, see the [tests](src/__tests__/index.js). ### Input ```css h1 { transform: rotate3d(0, 0, 1, 20deg); } ``` ### Output ```css h1 { transform: rotate(20deg); } ``` ## Usage See the [PostCSS documentation](https://github.com/postcss/postcss#usage) for examples for your environment. ## Contributors See [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md). ## License MIT © [Ben Briggs](http://beneb.info) [postcss]: https://github.com/postcss/postcss # 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. 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. # 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._ # PostCSS Calc [<img src="https://postcss.github.io/postcss/logo.svg" alt="PostCSS" width="90" height="90" align="right">][PostCSS] [![NPM Version][npm-img]][npm-url] [![Build Status][cli-img]][cli-url] [![Support Chat][git-img]][git-url] [PostCSS Calc] lets you reduce `calc()` references whenever it's possible. This can be particularly useful with the [PostCSS Custom Properties] plugin. When multiple units are mixed together in the same expression, the `calc()` statement is left as is, to fallback to the [W3C calc() implementation]. ## Installation ```bash npm install postcss-calc ``` ## Usage ```js // dependencies var fs = require("fs") var postcss = require("postcss") var calc = require("postcss-calc") // css to be processed var css = fs.readFileSync("input.css", "utf8") // process css var output = postcss() .use(calc()) .process(css) .css ``` **Example** (with [PostCSS Custom Properties] enabled as well): ```js // dependencies var fs = require("fs") var postcss = require("postcss") var customProperties = require("postcss-custom-properties") var calc = require("postcss-calc") // css to be processed var css = fs.readFileSync("input.css", "utf8") // process css var output = postcss() .use(customProperties()) .use(calc()) .process(css) .css ``` Using this `input.css`: ```css :root { --main-font-size: 16px; } body { font-size: var(--main-font-size); } h1 { font-size: calc(var(--main-font-size) * 2); height: calc(100px - 2em); margin-bottom: calc( var(--main-font-size) * 1.5 ) } ``` you will get: ```css body { font-size: 16px } h1 { font-size: 32px; height: calc(100px - 2em); margin-bottom: 24px } ``` Checkout [tests] for more examples. ### Options #### `precision` (default: `5`) Allow you to define the precision for decimal numbers. ```js var out = postcss() .use(calc({precision: 10})) .process(css) .css ``` #### `preserve` (default: `false`) Allow you to preserve calc() usage in output so browsers will handle decimal precision themselves. ```js var out = postcss() .use(calc({preserve: true})) .process(css) .css ``` #### `warnWhenCannotResolve` (default: `false`) Adds warnings when calc() are not reduced to a single value. ```js var out = postcss() .use(calc({warnWhenCannotResolve: true})) .process(css) .css ``` #### `mediaQueries` (default: `false`) Allows calc() usage as part of media query declarations. ```js var out = postcss() .use(calc({mediaQueries: true})) .process(css) .css ``` #### `selectors` (default: `false`) Allows calc() usage as part of selectors. ```js var out = postcss() .use(calc({selectors: true})) .process(css) .css ``` Example: ```css div[data-size="calc(3*3)"] { width: 100px; } ``` --- ## Contributing Work on a branch, install dev-dependencies, respect coding style & run tests before submitting a bug fix or a feature. ```bash git clone git@github.com:postcss/postcss-calc.git git checkout -b patch-1 npm install npm test ``` ## [Changelog](CHANGELOG.md) ## [License](LICENSE) [cli-img]: https://img.shields.io/travis/postcss/postcss-calc/master.svg [cli-url]: https://travis-ci.org/postcss/postcss-calc [git-img]: https://img.shields.io/badge/support-chat-blue.svg [git-url]: https://gitter.im/postcss/postcss [npm-img]: https://img.shields.io/npm/v/postcss-calc.svg [npm-url]: https://www.npmjs.com/package/postcss-calc [PostCSS]: https://github.com/postcss [PostCSS Calc]: https://github.com/postcss/postcss-calc [PostCSS Custom Properties]: https://github.com/postcss/postcss-custom-properties [tests]: src/__tests__/index.js [W3C calc() implementation]: https://www.w3.org/TR/css3-values/#calc-notation # 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 # 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._ # 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._ # css-select [![NPM version](http://img.shields.io/npm/v/css-select.svg)](https://npmjs.org/package/css-select) [![Build Status](https://travis-ci.org/fb55/css-select.svg?branch=master)](http://travis-ci.org/fb55/css-select) [![Downloads](https://img.shields.io/npm/dm/css-select.svg)](https://npmjs.org/package/css-select) [![Coverage](https://coveralls.io/repos/fb55/css-select/badge.svg?branch=master)](https://coveralls.io/r/fb55/css-select) a CSS selector compiler/engine ## What? css-select turns CSS selectors into functions that tests if elements match them. When searching for elements, testing is executed "from the top", similar to how browsers execute CSS selectors. In its default configuration, css-select queries the DOM structure of the [`domhandler`](https://github.com/fb55/domhandler) module (also known as htmlparser2 DOM). It uses [`domutils`](https://github.com/fb55/domutils) as its default adapter over the DOM structure. See Options below for details on querying alternative DOM structures. __Features:__ - Full implementation of CSS3 selectors - Partial implementation of jQuery/Sizzle extensions - Very high test coverage - Pretty good performance ## Why? The traditional approach of executing CSS selectors, named left-to-right execution, is to execute every component of the selector in order, from left to right _(duh)_. The execution of the selector `a b` for example will first query for `a` elements, then search these for `b` elements. (That's the approach of eg. [`Sizzle`](https://github.com/jquery/sizzle), [`nwmatcher`](https://github.com/dperini/nwmatcher/) and [`qwery`](https://github.com/ded/qwery).) While this works, it has some downsides: Children of `a`s will be checked multiple times; first, to check if they are also `a`s, then, for every superior `a` once, if they are `b`s. Using [Big O notation](http://en.wikipedia.org/wiki/Big_O_notation), that would be `O(n^(k+1))`, where `k` is the number of descendant selectors (that's the space in the example above). The far more efficient approach is to first look for `b` elements, then check if they have superior `a` elements: Using big O notation again, that would be `O(n)`. That's called right-to-left execution. And that's what css-select does – and why it's quite performant. ## How does it work? By building a stack of functions. _Wait, what?_ Okay, so let's suppose we want to compile the selector `a b` again, for right-to-left execution. We start by _parsing_ the selector, which means we turn the selector into an array of the building-blocks of the selector, so we can distinguish them easily. That's what the [`css-what`](https://github.com/fb55/css-what) module is for, if you want to have a look. Anyway, after parsing, we end up with an array like this one: ```js [ { type: 'tag', name: 'a' }, { type: 'descendant' }, { type: 'tag', name: 'b' } ] ``` Actually, this array is wrapped in another array, but that's another story (involving commas in selectors). Now that we know the meaning of every part of the selector, we can compile it. That's where it becomes interesting. The basic idea is to turn every part of the selector into a function, which takes an element as its only argument. The function checks whether a passed element matches its part of the selector: If it does, the element is passed to the next turned-into-a-function part of the selector, which does the same. If an element is accepted by all parts of the selector, it _matches_ the selector and double rainbow ALL THE WAY. As said before, we want to do right-to-left execution with all the big O improvements nonsense, so elements are passed from the rightmost part of the selector (`b` in our example) to the leftmost (~~which would be `c`~~ of course `a`). _//TODO: More in-depth description. Implementation details. Build a spaceship._ ## API ```js const CSSselect = require("css-select"); ``` __Note:__ css-select throws errors when invalid selectors are passed to it, contrary to the behavior in browsers, which swallow them. This is done to aid with writing css selectors, but can be unexpected when processing arbitrary strings. #### `CSSselect(query, elems, options)` Queries `elems`, returns an array containing all matches. - `query` can be either a CSS selector or a function. - `elems` can be either an array of elements, or a single element. If it is an element, its children will be queried. - `options` is described below. Aliases: `CSSselect.selectAll(query, elems)`, `CSSselect.iterate(query, elems)`. #### `CSSselect.compile(query)` Compiles the query, returns a function. #### `CSSselect.is(elem, query, options)` Tests whether or not an element is matched by `query`. `query` can be either a CSS selector or a function. #### `CSSselect.selectOne(query, elems, options)` Arguments are the same as for `CSSselect(query, elems)`. Only returns the first match, or `null` if there was no match. ### Options - `xmlMode`: When enabled, tag names will be case-sensitive. Default: `false`. - `strict`: Limits the module to only use CSS3 selectors. Default: `false`. - `rootFunc`: The last function in the stack, will be called with the last element that's looked at. Should return `true`. - `adapter`: The adapter to use when interacting with the backing DOM structure. By default it uses [`domutils`](https://github.com/fb55/domutils). #### Custom Adapters A custom adapter must implement the following functions: ``` isTag, existsOne, getAttributeValue, getChildren, getName, getParent, getSiblings, getText, hasAttrib, removeSubsets, findAll, findOne ``` The method signature notation used below should be fairly intuitive - if not, see the [`rtype`](https://github.com/ericelliott/rtype) or [`TypeScript`](https://www.typescriptlang.org/) docs, as it is very similar to both of those. You may also want to look at -[`domutils`](https://github.com/fb55/domutils) to see the default -implementation, or at -[`css-select-browser-adapter`](https://github.com/nrkn/css-select-browser-adapter/blob/master/index.js) -for an implementation backed by the DOM. ```ts { // is the node a tag? isTag: ( node:Node ) => isTag:Boolean, // does at least one of passed element nodes pass the test predicate? existsOne: ( test:Predicate, elems:[ElementNode] ) => existsOne:Boolean, // get the attribute value getAttributeValue: ( elem:ElementNode, name:String ) => value:String, // get the node's children getChildren: ( node:Node ) => children:[Node], // get the name of the tag getName: ( elem:ElementNode ) => tagName:String, // get the parent of the node getParent: ( node:Node ) => parentNode:Node, /* get the siblings of the node. Note that unlike jQuery's `siblings` method, this is expected to include the current node as well */ getSiblings: ( node:Node ) => siblings:[Node], // get the text content of the node, and its children if it has any getText: ( node:Node ) => text:String, // does the element have the named attribute? hasAttrib: ( elem:ElementNode, name:String ) => hasAttrib:Boolean, // takes an array of nodes, and removes any duplicates, as well as any nodes // whose ancestors are also in the array removeSubsets: ( nodes:[Node] ) => unique:[Node], // finds all of the element nodes in the array that match the test predicate, // as well as any of their children that match it findAll: ( test:Predicate, nodes:[Node] ) => elems:[ElementNode], // finds the first node in the array that matches the test predicate, or one // of its children findOne: ( test:Predicate, elems:[ElementNode] ) => findOne:ElementNode, /* The adapter can also optionally include an equals method, if your DOM structure needs a custom equality test to compare two objects which refer to the same underlying node. If not provided, `css-select` will fall back to `a === b`. */ equals: ( a:Node, b:Node ) => Boolean } ``` ## Supported selectors _As defined by CSS 4 and / or jQuery._ * Universal (`*`) * Tag (`<tagname>`) * Descendant (` `) * Child (`>`) * Parent (`<`) * * Sibling (`+`) * Adjacent (`~`) * Attribute (`[attr=foo]`), with supported comparisons: * `[attr]` (existential) * `=` * `~=` * `|=` * `*=` * `^=` * `$=` * `!=` * * Also, `i` can be added after the comparison to make the comparison case-insensitive (eg. `[attr=foo i]`) * * Pseudos: * `:not` * `:contains` * * `:icontains` * (case-insensitive version of `:contains`) * `:has` * * `:root` * `:empty` * `:parent` * * `:[first|last]-child[-of-type]` * `:only-of-type`, `:only-child` * `:nth-[last-]child[-of-type]` * `:link` * `:visited`, `:hover`, `:active` * (these depend on optional Adapter methods, so these will work only if implemented in Adapter) * `:selected` *, `:checked` * `:enabled`, `:disabled` * `:required`, `:optional` * `:header`, `:button`, `:input`, `:text`, `:checkbox`, `:file`, `:password`, `:reset`, `:radio` etc. * * `:matches` * __*__: Not part of CSS3 --- License: BSD-2-Clause ## 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. ## `css-select` for enterprise Available as part of the Tidelift Subscription The maintainers of `css-select` 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-css-select?utm_source=npm-css-select&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) # 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) [![Gitter chat](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/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 one 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 # 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. # [postcss][postcss]-discard-comments > Discard comments in your CSS files with PostCSS. ## Install With [npm](https://npmjs.org/package/postcss-discard-comments) do: ``` npm install postcss-discard-comments --save ``` ## Example ### Input ```css h1/* heading */{ margin: 0 auto } ``` ### Output ```css h1 { margin: 0 auto } ``` This module discards comments from your CSS files; by default, it will remove all regular comments (`/* comment */`) and preserve comments marked as important (`/*! important */`). Note that this module does not handle source map comments because they are not available to it; PostCSS handles this internally, so if they are removed then you will have to [configure source maps in PostCSS][maps]. [maps]: https://github.com/postcss/postcss/blob/master/docs/source-maps.md ## API ### comments([options]) #### options ##### remove(function) Type: `function` Return: `boolean` Variable: `comment` contains a comment without `/**/` For each comment, return true to remove, or false to keep the comment. ```js function(comment) {} ``` ```js var css = '/* headings *//*@ h1 */h1{margin:0 auto}/*@ h2 */h2{color:red}'; console.log(postcss(comments({ remove: function(comment) { return comment[0] == "@"; } })).process(css).css); //=> /* headings */h1{margin:0 auto}h2{color:red} ``` **NOTE:** If you use the `remove` function other options will not be available. ##### removeAll Type: `boolean` Default: `false` Remove all comments marked as important. ```js var css = '/*! heading */h1{margin:0 auto}/*! heading 2 */h2{color:red}'; console.log(postcss(comments({removeAll: true})).process(css).css); //=> h1{margin:0 auto}h2{color:red} ``` ##### removeAllButFirst Type: `boolean` Default: `false` Remove all comments marked as important, but the first one. ```js var css = '/*! heading */h1{margin:0 auto}/*! heading 2 */h2{color:red}'; console.log(postcss(comments({removeAllButFirst: true})).process(css).css); //=> /*! heading */h1{margin:0 auto}h2{color:red} ``` ## Usage See the [PostCSS documentation](https://github.com/postcss/postcss#usage) for examples for your environment. ## Contributors See [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md). ## License MIT © [Ben Briggs](http://beneb.info) [postcss]: https://github.com/postcss/postcss # 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 [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 [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. ### `.canonicalizedDomain()` ### `.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. ### `.removeAllCookies(cb(err))` Removes all cookies from the jar. This is a new backwards-compatible feature of `tough-cookie` version 2.5, so not all Stores will implement it efficiently. For Stores that do not implement `removeAllCookies`, the fallback is to call `removeCookie` after `getAllCookies`. If `getAllCookies` fails or isn't implemented in the Store, that error is returned. If one or more of the `removeCookie` calls fail, only the first error is returned. ### `.removeAllCookiesSync()` Sync version of `.removeAllCookies()` ## 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.removeAllCookies(cb(err))` _Optional_. Removes all cookies from the store. Pass an error if one or more cookies can't be removed. **Note**: New method as of `tough-cookie` version 2.5, so not all Stores will implement this, plus some stores may choose not to implement this. ### `store.getAllCookies(cb(err, cookies))` _Optional_. 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. **Note**: not all Stores can implement this due to technical limitations, so it is optional. ## 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. Supports serialization, `getAllCookies`, and `removeAllCookies`. ## 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: 'tough-cookie@1.x.y', // 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 BSD-3-Clause: ```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. ``` # Stealthy-Require [![Build Status](https://img.shields.io/travis/analog-nico/stealthy-require/master.svg?style=flat-square)](https://travis-ci.org/analog-nico/stealthy-require) [![Coverage Status](https://img.shields.io/coveralls/analog-nico/stealthy-require.svg?style=flat-square)](https://coveralls.io/r/analog-nico/stealthy-require) [![Dependency Status](https://img.shields.io/david/analog-nico/stealthy-require.svg?style=flat-square)](https://david-dm.org/analog-nico/stealthy-require) This is probably the closest you can currently get to require something in node.js with completely bypassing the require cache. `stealthy-require` works like this: 1. It clears the require cache. 2. It calls a callback in which you require your module(s) without the cache kicking in. 3. It clears the cache again and restores its old state. The restrictions are: - [Native modules cannot be required twice.](https://github.com/nodejs/node/issues/5016) Thus this module bypasses the require cache only for non-native (e.g. JS) modules. - The require cache is only bypassed for all operations that happen synchronously when a module is required. If a module lazy loads another module at a later time that require call will not bypass the cache anymore. This means you should have a close look at all internal require calls before you decide to use this library. ## Installation [![NPM Stats](https://nodei.co/npm/stealthy-require.png?downloads=true)](https://npmjs.org/package/stealthy-require) This is a module for node.js and is installed via npm: ``` bash npm install stealthy-require --save ``` ## Usage Let's say you want to bypass the require cache for this require call: ``` js var request = require('request'); ``` With `stealthy-require` you can do that like this: ``` js var stealthyRequire = require('stealthy-require'); var requestFresh = stealthyRequire(require.cache, function () { return require('request'); }); ``` The require cache is bypassed for the module you require (i.e. `request`) as well as all modules the module requires (i.e. `http` and many more). Sometimes the require cache shall not be bypassed for specific modules. E.g. `request` is required but `tough-cookie` – on which `request` depends on – shall be required using the regular cache. For that you can pass two extra arguments to `stealthyRequire(...)`: - A callback that requires the modules that shall be required without bypassing the cache - The `module` variable ``` js var stealthyRequire = require('stealthy-require'); var requestFresh = stealthyRequire(require.cache, function () { return require('request'); }, function () { require('tough-cookie'); // No return needed // You can require multiple modules here }, module); ``` ## Usage with Module Bundlers - [Webpack](https://webpack.github.io) works out-of-the-box like described in the [Usage section](#usage) above. - [Browserify](http://browserify.org) does not expose `require.cache`. However, as of `browserify@13.0.1` the cache is passed as the 6th argument to CommonJS modules. Thus you can pass this argument instead: ``` js // Tweak for Browserify - using arguments[5] instead of require.cache var requestFresh = stealthyRequire(arguments[5], function () { return require('request'); }); ``` ## Preventing a Memory Leak When Repeatedly Requiring Fresh Module Instances in Node.js If you are using `stealthy-require` in node.js and repeatedly require fresh module instances the `module.children` array will hold all module instances which prevents unneeded instances to be garbage collected. Assume your code calls `doSomething()` repeatedly. ``` js var stealthyRequire = require('stealthy-require'); function doSomething() { var freshInstance = stealthyRequire(require.cache, function () { return require('some-module'); }); return freshInstance.calc(); } ``` After `doSomething()` returns `freshInstance` is not used anymore but won’t be garbage collected because `module.children` still holds a reference. The solution is to truncate `module.children` accordingly: ``` js var stealthyRequire = require('stealthy-require'); function doSomething() { var initialChildren = module.children.slice(); // Creates a shallow copy of the array var freshInstance = stealthyRequire(require.cache, function () { return require('some-module'); }); module.children = initialChildren; return freshInstance.calc(); } ``` The `slice` operation removes all new `module.children` entries created during the `stealthyRequire(...)` call and thus `freshInstance` gets garbage collected after `doSomething()` returns. ## Technical Walkthrough ``` js // 1. Load stealthy-require var stealthyRequire = require('stealthy-require'); // This does nothing but loading the code. // It has no side-effects like patching the module loader or anything. // Any regular require works as always. var request1 = require('request'); // 2. Call stealthyRequire with passing the require cache and a callback. var requestFresh = stealthyRequire(require.cache, function () { // 2a. Before this callback gets called the require cache is cleared. // 2b. Any require taking place here takes place on a clean require cache. // Since the require call is part of the user's code it also works with module bundlers. return require('request'); // Anything returned here will be returned by stealthyRequire(...). // 2c. After this callback gets called the require cache is // - cleared again and // - restored to its old state before step 2. }); // Any regular require again works as always. // In this case require returns the cached request module instance. var request2 = require('request'); // And voilà: request1 === request2 // -> true request1 === requestFresh // -> false ``` ## Contributing To set up your development environment for `stealthy-require`: 1. Clone this repo to your desktop, 2. in the shell `cd` to the main folder, 3. hit `npm install`, 4. hit `npm install gulp -g` if you haven't installed gulp globally yet, and 5. run `gulp dev`. (Or run `node ./node_modules/.bin/gulp dev` if you don't want to install gulp globally.) `gulp dev` watches all source files and if you save some changes it will lint the code and execute all tests. The test coverage report can be viewed from `./coverage/lcov-report/index.html`. If you want to debug a test you should use `gulp test-without-coverage` to run all tests without obscuring the code by the test coverage instrumentation. ## Change History - v1.1.1 (2017-05-08) - Fix that stops `undefined` entries from appearing in `require.cache` *(Thanks to @jasperjn from reporting this in [issue #4](https://github.com/analog-nico/stealthy-require/issues/4))* - v1.1.0 (2017-04-25) - Added ability to disable bypassing the cache for certain modules *(Thanks to @novemberborn for suggesting this in [issue #3](https://github.com/analog-nico/stealthy-require/issues/3))* - Added section in README about a [potential memory leak](#preventing-a-memory-leak-when-repeatedly-requiring-fresh-module-instances-in-nodejs) *(Thanks to @Flarna and @novemberborn for bringing that up in [issue #2](https://github.com/analog-nico/stealthy-require/issues/2))* - Performance optimizations *(Thanks to @jcready for [pull request #1](https://github.com/analog-nico/stealthy-require/pull/1))* - v1.0.0 (2016-07-18) - **Breaking Change:** API completely changed. Please read the [Usage section](#usage) again. - Redesigned library to support module bundlers like [Webpack](https://webpack.github.io) and [Browserify](http://browserify.org) - v0.1.0 (2016-05-26) - Initial version ## License (ISC) In case you never heard about the [ISC license](http://en.wikipedia.org/wiki/ISC_license) it is functionally equivalent to the MIT license. See the [LICENSE file](LICENSE) for details. # 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;calvin.metcalf@gmail.com&gt; - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 * **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) &lt;mathiasbuus@gmail.com&gt; * **Matteo Collina** ([@mcollina](https://github.com/mcollina)) &lt;matteo.collina@gmail.com&gt; - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E * **Irina Shestak** ([@lrlna](https://github.com/lrlna)) &lt;shestak.irina@gmail.com&gt; * **Yoshua Wyuts** ([@yoshuawuyts](https://github.com/yoshuawuyts)) &lt;yoshuawuyts@gmail.com&gt; [sauce]: https://saucelabs.com # 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;calvin.metcalf@gmail.com&gt; - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 * **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) &lt;mathiasbuus@gmail.com&gt; * **Matteo Collina** ([@mcollina](https://github.com/mcollina)) &lt;matteo.collina@gmail.com&gt; - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E * **Irina Shestak** ([@lrlna](https://github.com/lrlna)) &lt;shestak.irina@gmail.com&gt; * **Yoshua Wyuts** ([@yoshuawuyts](https://github.com/yoshuawuyts)) &lt;yoshuawuyts@gmail.com&gt; [sauce]: https://saucelabs.com # [postcss][postcss]-ordered-values > Ensure values are ordered consistently in your CSS. ## Install With [npm](https://npmjs.org/package/postcss-ordered-values) do: ``` npm install postcss-ordered-values --save ``` ## Example Some CSS properties accept their values in an arbitrary order; for this reason, it is entirely possible that different developers will write their values in different orders. This module normalizes the order, making it easier for other modules to understand which declarations are duplicates. ### Input ```css h1 { border: solid 1px red; border: red solid .5em; border: rgba(0, 30, 105, 0.8) solid 1px; border: 1px solid red; } ``` ### Output ```css h1 { border: 1px solid red; border: .5em solid red; border: 1px solid rgba(0, 30, 105, 0.8); border: 1px solid red; } ``` ## Support List For more examples, see the [tests](src/__tests__/index.js). * `animation`, `-webkit-animation` * `border(border-left|right|top|bottom)` * `box-shadow` * `outline` * `flex-flow` * `transition`, `-webkit-transition` ## Usage See the [PostCSS documentation](https://github.com/postcss/postcss#usage) for examples for your environment. ## Contributors See [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md). ## License MIT © [Ben Briggs](http://beneb.info) [postcss]: https://github.com/postcss/postcss # 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;tj@vision-media.ca&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. 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`. # 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._ # 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 > parseurl@1.3.3 bench nodejs-parseurl > node benchmark/index.js http_parser@2.8.0 node@10.6.0 v8@6.7.288.46-node.13 uv@1.21.0 zlib@1.2.11 ares@1.14.0 modules@64 nghttp2@1.32.0 napi@3 openssl@1.1.0h icu@61.1 unicode@10.0 cldr@33.0 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 # test-exclude The file include/exclude logic used by [nyc] and [babel-plugin-istanbul]. [![Build Status](https://travis-ci.org/istanbuljs/test-exclude.svg)](https://travis-ci.org/istanbuljs/test-exclude) [![Coverage Status](https://coveralls.io/repos/github/istanbuljs/test-exclude/badge.svg?branch=master)](https://coveralls.io/github/istanbuljs/test-exclude?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/istanbuljs/test-exclude.svg)](https://greenkeeper.io/) ## Usage ```js const TestExclude = require('test-exclude'); const exclude = new TestExclude(); if (exclude().shouldInstrument('./foo.js')) { // let's instrument this file for test coverage! } ``` ### TestExclude(options) The test-exclude constructor accepts an options object. The defaults are taken from [@istanbuljs/schema]. #### options.cwd This is the base directory by which all comparisons are performed. Files outside `cwd` are not included. Default: `process.cwd()` #### options.exclude Array of path globs to be ignored. Note this list does not include `node_modules` which is added separately. See [@istanbuljs/schema/default-excludes.js] for default list. #### options.excludeNodeModules By default `node_modules` is excluded. Setting this option `true` allows `node_modules` to be included. #### options.include Array of path globs that can be included. By default this is unrestricted giving a result similar to `['**']` but more optimized. #### options.extension Array of extensions that can be included. This ensures that nyc only attempts to process files which it might understand. Note use of some formats may require adding parser plugins to your nyc or babel configuration. Default: `['.js', '.cjs', '.mjs', '.ts', '.tsx', '.jsx']` ### TestExclude#shouldInstrument(filename): boolean Test if `filename` matches the rules of this test-exclude instance. ```js const exclude = new TestExclude(); exclude.shouldInstrument('index.js'); // true exclude.shouldInstrument('test.js'); // false exclude.shouldInstrument('README.md'); // false exclude.shouldInstrument('node_modules/test-exclude/index.js'); // false ``` In this example code: * `index.js` is true because it matches the default `options.extension` list and is not part of the default `options.exclude` list. * `test.js` is excluded because it matches the default `options.exclude` list. * `README.md` is not matched by the default `options.extension` * `node_modules/test-exclude/index.js` is excluded because `options.excludeNodeModules` is true by default. ### TestExculde#globSync(cwd = options.cwd): Array[string] This synchronously retrieves a list of files within `cwd` which should be instrumented. Note that setting `cwd` to a parent of `options.cwd` is ineffective, this argument can only be used to further restrict the result. ### TestExclude#glob(cwd = options.cwd): Promise<Array[string]> This function does the same as `TestExclude#globSync` but does so asynchronously. The Promise resolves to an Array of strings. ## `test-exclude` for enterprise Available as part of the Tidelift Subscription. The maintainers of `test-exclude` 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-test-exclude?utm_source=npm-test-exclude&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) [nyc]: https://github.com/istanbuljs/nyc [babel-plugin-istanbul]: https://github.com/istanbuljs/babel-plugin-istanbul [@istanbuljs/schema]: https://github.com/istanbuljs/schema [@istanbuljs/schema/default-excludes.js]: https://github.com/istanbuljs/schema/blob/master/default-exclude.js # 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 # 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)) ``` # 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) # 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._ # 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. ## Usage **Direct** ```js const promisify = require('util.promisify'); // Use `promisify` just like the built-in method on `util` ``` **Shim** ```js require('util.promisify/shim')(); // `util.promisify` is now defined const util = require('util'); // Use `util.promisify` ``` 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. ## Promisifying modules If you want to promisify a whole module, like the `fs` module, you can use [`util.promisify-all`](https://www.npmjs.com/package/util.promisify-all). # [postcss][postcss]-normalize-whitespace > Normalize whitespace with PostCSS. ## Install With [npm](https://npmjs.org/package/postcss-normalize-whitespace) do: ``` npm install postcss-normalize-whitespace --save ``` ## Example ### Input ```css h1{ width: calc(10px - ( 100px / var(--test) )) } ``` ### Output ```css h1{ width: calc(10px - 100px / var(--test)) } ``` ## Usage See the [PostCSS documentation](https://github.com/postcss/postcss#usage) for examples for your environment. ## Contributors See [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md). ## License MIT © [Ben Briggs](http://beneb.info) [postcss]: https://github.com/postcss/postcss # 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._ # simple-swizzle [![Travis-CI.org Build Status](https://img.shields.io/travis/Qix-/node-simple-swizzle.svg?style=flat-square)](https://travis-ci.org/Qix-/node-simple-swizzle) [![Coveralls.io Coverage Rating](https://img.shields.io/coveralls/Qix-/node-simple-swizzle.svg?style=flat-square)](https://coveralls.io/r/Qix-/node-simple-swizzle) > [Swizzle](https://en.wikipedia.org/wiki/Swizzling_(computer_graphics)) your function arguments; pass in mixed arrays/values and get a clean array ## Usage ```js var swizzle = require('simple-swizzle'); function myFunc() { var args = swizzle(arguments); // ... return args; } myFunc(1, [2, 3], 4); // [1, 2, 3, 4] myFunc(1, 2, 3, 4); // [1, 2, 3, 4] myFunc([1, 2, 3, 4]); // [1, 2, 3, 4] ``` Functions can also be wrapped to automatically swizzle arguments and be passed the resulting array. ```js var swizzle = require('simple-swizzle'); var swizzledFn = swizzle.wrap(function (args) { // ... return args; }); swizzledFn(1, [2, 3], 4); // [1, 2, 3, 4] swizzledFn(1, 2, 3, 4); // [1, 2, 3, 4] swizzledFn([1, 2, 3, 4]); // [1, 2, 3, 4] ``` ## License Licensed under the [MIT License](http://opensource.org/licenses/MIT). You can find a copy of it in [LICENSE](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> 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) # [postcss][postcss]-normalize-unicode > Normalize unicode with PostCSS. ## Install With [npm](https://npmjs.org/package/postcss-normalize-unicode) do: ``` npm install postcss-normalize-unicode --save ``` ## Example ### Input ```css @font-face{ font-family: test; unicode-range: u+2b00-2bff } ``` ### Output ```css @font-face{ font-family: test; unicode-range: u+2b?? } ``` ## Usage See the [PostCSS documentation](https://github.com/postcss/postcss#usage) for examples for your environment. ## Contributors See [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md). ## License MIT © [Ben Briggs](http://beneb.info) [postcss]: https://github.com/postcss/postcss # 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, 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. # saxes A sax-style non-validating parser for XML. Saxes is a fork of [sax](https://github.com/isaacs/sax-js) 1.2.4. All mentions of sax in this project's documentation are references to sax 1.2.4. Designed with [node](http://nodejs.org/) in mind, but should work fine in the browser or other CommonJS implementations. Saxes does not support Node versions older than 10. ## Notable Differences from Sax. * Saxes aims to be much stricter than sax with regards to XML well-formedness. Sax, even in its so-called "strict mode", is not strict. It silently accepts structures that are not well-formed XML. Projects that need better compliance with well-formedness constraints cannot use sax as-is. Consequently, saxes does not support HTML, or pseudo-XML, or bad XML. Saxes will report well-formedness errors in all these cases but it won't try to extract data from malformed documents like sax does. * Saxes is much much faster than sax, mostly because of a substantial redesign of the internal parsing logic. The speed improvement is not merely due to removing features that were supported by sax. That helped a bit, but saxes adds some expensive checks in its aim for conformance with the XML specification. Redesigning the parsing logic is what accounts for most of the performance improvement. * Saxes does not aim to support antiquated platforms. We will not pollute the source or the default build with support for antiquated platforms. If you want support for IE 11, you are welcome to produce a PR that adds a *new build* transpiled to ES5. * Saxes handles errors differently from sax: it provides a default onerror handler which throws. You can replace it with your own handler if you want. If your handler does nothing, there is no `resume` method to call. * There's no `Stream` API. A revamped API may be introduced later. (It is still a "streaming parser" in the general sense that you write a character stream to it.) * Saxes does not have facilities for limiting the size the data chunks passed to event handlers. See the FAQ entry for more details. ## Conformance Saxes supports: * [XML 1.0 fifth edition](https://www.w3.org/TR/2008/REC-xml-20081126/) * [XML 1.1 second edition](https://www.w3.org/TR/2006/REC-xml11-20060816/) * [Namespaces in XML 1.0 (Third Edition)](https://www.w3.org/TR/2009/REC-xml-names-20091208/). * [Namespaces in XML 1.1 (Second Edition)](https://www.w3.org/TR/2006/REC-xml-names11-20060816/). ## Limitations This is a non-validating parser so it only verifies whether the document is well-formed. We do aim to raise errors for all malformed constructs encountered. However, this parser does not thorougly parse the contents of DTDs. So most malformedness errors caused by errors **in DTDs** cannot be reported. ## Regarding `<!DOCTYPE` and `<!ENTITY` 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 `doctype` event, and then fetch the doctypes, and read the entities and add them to `parser.ENTITIES`, then be my guest. ## Documentation The source code contains JSDOC comments. Use them. What follows is a brief summary of what is available. The final authority is the source code. **PAY CLOSE ATTENTION TO WHAT IS PUBLIC AND WHAT IS PRIVATE.** The move to TypeScript makes it so that everything is now formally private, protected, or public. If you use anything not public, that's at your own peril. If there's a mistake in the documentation, raise an issue. If you just assume, you may assume incorrectly. ## Summary Usage Information ### Example ```javascript var saxes = require("./lib/saxes"), parser = new saxes.SaxesParser(); parser.on("error", function (e) { // an error happened. }); parser.on("text", function (t) { // got some text. t is the string of text. }); parser.on("opentag", function (node) { // opened a tag. node has "name" and "attributes" }); parser.on("end", 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(); ``` ### Constructor Arguments Settings supported: * `xmlns` - Boolean. If `true`, then namespaces are supported. Default is `false`. * `position` - Boolean. If `false`, then don't track line/col/position. Unset is treated as `true`. Default is unset. Currently, setting this to `false` only results in a cosmetic change: the errors reported do not contain position information. sax-js would literally turn off the position-computing logic if this flag was set to false. The notion was that it would optimize execution. In saxes at least it turns out that continually testing this flag causes a cost that offsets the benefits of turning off this logic. * `fileName` - String. Set a file name for error reporting. This is useful only when tracking positions. You may leave it unset. * `fragment` - Boolean. If `true`, parse the XML as an XML fragment. Default is `false`. * `additionalNamespaces` - A plain object whose key, value pairs define namespaces known before parsing the XML file. It is not legal to pass bindings for the namespaces `"xml"` or `"xmlns"`. * `defaultXMLVersion` - The default version of the XML specification to use if the document contains no XML declaration. If the document does contain an XML declaration, then this setting is ignored. Must be `"1.0"` or `"1.1"`. The default is `"1.0"`. * `forceXMLVersion` - Boolean. A flag indicating whether to force the XML version used for parsing to the value of ``defaultXMLVersion``. When this flag is ``true``, ``defaultXMLVersion`` must be specified. If unspecified, the default value of this flag is ``false``. Example: suppose you are parsing a document that has an XML declaration specifying XML version 1.1. If you set ``defaultXMLVersion`` to ``"1.0"`` without setting ``forceXMLVersion`` then the XML declaration will override the value of ``defaultXMLVersion`` and the document will be parsed according to XML 1.1. If you set ``defaultXMLVersion`` to ``"1.0"`` and set ``forceXMLVersion`` to ``true``, then the XML declaration will be ignored and the document will be parsed according to XML 1.0. ### Methods `write` - Write bytes onto the stream. You don't have to pass the whole document in one `write` call. You can read your source chunk by chunk and call `write` with each chunk. `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. ### Properties The parser has the following properties: `line`, `column`, `columnIndex`, `position` - Indications of the position in the XML document where the parser currently is looking. The `columnIndex` property counts columns as if indexing into a JavaScript string, whereas the `column` property counts Unicode characters. `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. `opt` - Any options passed into the constructor. `xmlDecl` - The XML declaration for this document. It contains the fields `version`, `encoding` and `standalone`. They are all `undefined` before encountering the XML declaration. If they are undefined after the XML declaration, the corresponding value was not set by the declaration. There is no event associated with the XML declaration. In a well-formed document, the XML declaration may be preceded only by an optional BOM. So by the time any event generated by the parser happens, the declaration has been processed if present at all. Otherwise, you have a malformed document, and as stated above, you cannot rely on the parser data! ### Error Handling The parser continues to parse even upon encountering errors, and does its best to continue reporting errors. You should heed all errors reported. After an error, however, saxes may interpret your document incorrectly. For instance ``<foo a=bc="d"/>`` is invalid XML. Did you mean to have ``<foo a="bc=d"/>`` or ``<foo a="b" c="d"/>`` or some other variation? For the sake of continuing to provide errors, saxes will continue parsing the document, but the structure it reports may be incorrect. It is only after the errors are fixed in the document that saxes can provide a reliable interpretation of the document. That leaves you with two rules of thumb when using saxes: * Pay attention to the errors that saxes report. The default `onerror` handler throws, so by default, you cannot miss errors. * **ONCE AN ERROR HAS BEEN ENCOUNTERED, STOP RELYING ON THE EVENT HANDLERS OTHER THAN `onerror`.** As explained above, when saxes runs into a well-formedness problem, it makes a guess in order to continue reporting more errors. The guess may be wrong. ### Events To listen to an event, override `on<eventname>`. The list of supported events are also in the exported `EVENTS` array. See the JSDOC comments in the source code for a description of each supported event. ### Parsing XML Fragments The XML specification does not define any method by which to parse XML fragments. However, there are usage scenarios in which it is desirable to parse fragments. In order to allow this, saxes provides three initialization options. If you pass the option `fragment: true` to the parser constructor, the parser will expect an XML fragment. It essentially starts with a parsing state equivalent to the one it would be in if `parser.write("<foo">)` had been called right after initialization. In other words, it expects content which is acceptable inside an element. This also turns off well-formedness checks that are inappropriate when parsing a fragment. The option `additionalNamespaces` allows you to define additional prefix-to-URI bindings known before parsing starts. You would use this over `resolvePrefix` if you have at the ready a series of namespaces bindings to use. The option `resolvePrefix` allows you to pass a function which saxes will use if it is unable to resolve a namespace prefix by itself. You would use this over `additionalNamespaces` in a context where getting a complete list of defined namespaces is onerous. Note that you can use `additionalNamespaces` and `resolvePrefix` together if you want. `additionalNamespaces` applies before `resolvePrefix`. The options `additionalNamespaces` and `resolvePrefix` are really meant to be used for parsing fragments. However, saxes won't prevent you from using them with `fragment: false`. Note that if you do this, your document may parse without errors and yet be malformed because the document can refer to namespaces which are not defined *in* the document. Of course, `additionalNamespaces` and `resolvePrefix` are used only if `xmlns` is `true`. If you are parsing a fragment that does not use namespaces, there's no point in setting these options. ### Performance Tips * saxes works faster on files that use newlines (``\u000A``) as end of line markers than files that use other end of line markers (like ``\r`` or ``\r\n``). The XML specification requires that conformant applications behave as if all characters that are to be treated as end of line characters are converted to ``\u000A`` prior to parsing. The optimal code path for saxes is a file in which all end of line characters are already ``\u000A``. * Don't split Unicode strings you feed to saxes across surrogates. When you naively split a string in JavaScript, you run the risk of splitting a Unicode character into two surrogates. e.g. In the following example ``a`` and ``b`` each contain half of a single Unicode character: ``const a = "\u{1F4A9}"[0]; const b = "\u{1F4A9}"[1]`` If you feed such split surrogates to versions of saxes prior to 4, you'd get errors. Saxes version 4 and over are able to detect when a chunk of data ends with a surrogate and carry over the surrogate to the next chunk. However this operation entails slicing and concatenating strings. If you can feed your data in a way that does not split surrogates, you should do it. (Obviously, feeding all the data at once with a single write is fastest.) * Don't set event handlers you don't need. Saxes has always aimed to avoid doing work that will just be tossed away but future improvements hope to do this more aggressively. One way saxes knows whether or not some data is needed is by checking whether a handler has been set for a specific event. ## FAQ Q. Why has saxes dropped support for limiting the size of data chunks passed to event handlers? A. With sax you could set ``MAX_BUFFER_LENGTH`` to cause the parser to limit the size of data chunks passed to event handlers. So if you ran into a span of text above the limit, multiple ``text`` events with smaller data chunks were fired instead of a single event with a large chunk. However, that functionality had some problematic characteristics. It had an arbitrary default value. It was library-wide so all parsers created from a single instance of the ``sax`` library shared it. This could potentially cause conflicts among libraries running in the same VM but using sax for different purposes. These issues could have been easily fixed, but there were larger issues. The buffer limit arbitrarily applied to some events but not others. It would split ``text``, ``cdata`` and ``script`` events. However, if a ``comment``, ``doctype``, ``attribute`` or ``processing instruction`` were more than the limit, the parser would generate an error and you were left picking up the pieces. It was not intuitive to use. You'd think setting the limit to 1K would prevent chunks bigger than 1K to be passed to event handlers. But that was not the case. A comment in the source code told you that you might go over the limit if you passed large chunks to ``write``. So if you want a 1K limit, don't pass 64K chunks to ``write``. Fair enough. You know what limit you want so you can control the size of the data you pass to ``write``. So you limit the chunks to ``write`` to 1K at a time. Even if you do this, your event handlers may get data chunks that are 2K in size. Suppose on the previous ``write`` the parser has just finished processing an open tag, so it is ready for text. Your ``write`` passes 1K of text. You are not above the limit yet, so no event is generated yet. The next ``write`` passes another 1K of text. It so happens that sax checks buffer limits only once per ``write``, after the chunk of data has been processed. Now you've hit the limit and you get a ``text`` event with 2K of data. So even if you limit your ``write`` calls to the buffer limit you've set, you may still get events with chunks at twice the buffer size limit you've specified. We may consider reinstating an equivalent functionality, provided that it addresses the issues above and does not cause a huge performance drop for use-case scenarios that don't need it. # <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.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 ### 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. 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 # 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 # 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("git@github.com: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 (`git@github.com: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("git@github.com: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://git@github.com/npm/hosted-git-info.git` * info.ssh(opts) eg, `git@github.com: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. # 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;tj@vision-media.ca&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"> <img width="100" height="100" src="logo.svg" alt=""><br> jsdom </h1> jsdom is a pure-JavaScript implementation of many web standards, notably the WHATWG [DOM](https://dom.spec.whatwg.org/) and [HTML](https://html.spec.whatwg.org/multipage/) Standards, for use with Node.js. In general, the goal of the project is to emulate enough of a subset of a web browser to be useful for testing and scraping real-world web applications. The latest versions of jsdom require Node.js v10 or newer. (Versions of jsdom below v16 still work with previous Node.js versions, but are unsupported.) ## Basic usage ```js const jsdom = require("jsdom"); const { JSDOM } = jsdom; ``` To use jsdom, you will primarily use the `JSDOM` constructor, which is a named export of the jsdom main module. Pass the constructor a string. You will get back a `JSDOM` object, which has a number of useful properties, notably `window`: ```js const dom = new JSDOM(`<!DOCTYPE html><p>Hello world</p>`); console.log(dom.window.document.querySelector("p").textContent); // "Hello world" ``` (Note that jsdom will parse the HTML you pass it just like a browser does, including implied `<html>`, `<head>`, and `<body>` tags.) The resulting object is an instance of the `JSDOM` class, which contains a number of useful properties and methods besides `window`. In general, it can be used to act on the jsdom from the "outside," doing things that are not possible with the normal DOM APIs. For simple cases, where you don't need any of this functionality, we recommend a coding pattern like ```js const { window } = new JSDOM(`...`); // or even const { document } = (new JSDOM(`...`)).window; ``` Full documentation on everything you can do with the `JSDOM` class is below, in the section "`JSDOM` Object API". ## Customizing jsdom The `JSDOM` constructor accepts a second parameter which can be used to customize your jsdom in the following ways. ### Simple options ```js const dom = new JSDOM(``, { url: "https://example.org/", referrer: "https://example.com/", contentType: "text/html", includeNodeLocations: true, storageQuota: 10000000 }); ``` - `url` sets the value returned by `window.location`, `document.URL`, and `document.documentURI`, and affects things like resolution of relative URLs within the document and the same-origin restrictions and referrer used while fetching subresources. It defaults to `"about:blank"`. - `referrer` just affects the value read from `document.referrer`. It defaults to no referrer (which reflects as the empty string). - `contentType` affects the value read from `document.contentType`, as well as how the document is parsed: as HTML or as XML. Values that are not a [HTML mime type](https://mimesniff.spec.whatwg.org/#html-mime-type) or an [XML mime type](https://mimesniff.spec.whatwg.org/#xml-mime-type) will throw. It defaults to `"text/html"`. If a `charset` parameter is present, it can affect [binary data processing](#encoding-sniffing). - `includeNodeLocations` preserves the location info produced by the HTML parser, allowing you to retrieve it with the `nodeLocation()` method (described below). It also ensures that line numbers reported in exception stack traces for code running inside `<script>` elements are correct. It defaults to `false` to give the best performance, and cannot be used with an XML content type since our XML parser does not support location info. - `storageQuota` is the maximum size in code units for the separate storage areas used by `localStorage` and `sessionStorage`. Attempts to store data larger than this limit will cause a `DOMException` to be thrown. By default, it is set to 5,000,000 code units per origin, as inspired by the HTML specification. Note that both `url` and `referrer` are canonicalized before they're used, so e.g. if you pass in `"https:example.com"`, jsdom will interpret that as if you had given `"https://example.com/"`. If you pass an unparseable URL, the call will throw. (URLs are parsed and serialized according to the [URL Standard](http://url.spec.whatwg.org/).) ### Executing scripts jsdom's most powerful ability is that it can execute scripts inside the jsdom. These scripts can modify the content of the page and access all the web platform APIs jsdom implements. However, this is also highly dangerous when dealing with untrusted content. The jsdom sandbox is not foolproof, and code running inside the DOM's `<script>`s can, if it tries hard enough, get access to the Node.js environment, and thus to your machine. As such, the ability to execute scripts embedded in the HTML is disabled by default: ```js const dom = new JSDOM(`<body> <script>document.body.appendChild(document.createElement("hr"));</script> </body>`); // The script will not be executed, by default: dom.window.document.body.children.length === 1; ``` To enable executing scripts inside the page, you can use the `runScripts: "dangerously"` option: ```js const dom = new JSDOM(`<body> <script>document.body.appendChild(document.createElement("hr"));</script> </body>`, { runScripts: "dangerously" }); // The script will be executed and modify the DOM: dom.window.document.body.children.length === 2; ``` Again we emphasize to only use this when feeding jsdom code you know is safe. If you use it on arbitrary user-supplied code, or code from the Internet, you are effectively running untrusted Node.js code, and your machine could be compromised. If you want to execute _external_ scripts, included via `<script src="">`, you'll also need to ensure that they load them. To do this, add the option `resources: "usable"` [as described below](#loading-subresources). (You'll likely also want to set the `url` option, for the reasons discussed there.) Event handler attributes, like `<div onclick="">`, are also governed by this setting; they will not function unless `runScripts` is set to `"dangerously"`. (However, event handler _properties_, like `div.onclick = ...`, will function regardless of `runScripts`.) If you are simply trying to execute script "from the outside", instead of letting `<script>` elements and event handlers attributes run "from the inside", you can use the `runScripts: "outside-only"` option, which enables fresh copies of all the JavaScript spec-provided globals to be installed on `window`. This includes things like `window.Array`, `window.Promise`, etc. It also, notably, includes `window.eval`, which allows running scripts, but with the jsdom `window` as the global: ```js const { window } = new JSDOM(``, { runScripts: "outside-only" }); window.eval(`document.body.innerHTML = "<p>Hello, world!</p>";`); window.document.body.children.length === 1; ``` This is turned off by default for performance reasons, but is safe to enable. (Note that in the default configuration, without setting `runScripts`, the values of `window.Array`, `window.eval`, etc. will be the same as those provided by the outer Node.js environment. That is, `window.eval === eval` will hold, so `window.eval` will not run scripts in a useful way.) We strongly advise against trying to "execute scripts" by mashing together the jsdom and Node global environments (e.g. by doing `global.window = dom.window`), and then executing scripts or test code inside the Node global environment. Instead, you should treat jsdom like you would a browser, and run all scripts and tests that need access to a DOM inside the jsdom environment, using `window.eval` or `runScripts: "dangerously"`. This might require, for example, creating a browserify bundle to execute as a `<script>` element—just like you would in a browser. Finally, for advanced use cases you can use the `dom.getInternalVMContext()` method, documented below. ### Pretending to be a visual browser jsdom does not have the capability to render visual content, and will act like a headless browser by default. It provides hints to web pages through APIs such as `document.hidden` that their content is not visible. When the `pretendToBeVisual` option is set to `true`, jsdom will pretend that it is rendering and displaying content. It does this by: * Changing `document.hidden` to return `false` instead of `true` * Changing `document.visibilityState` to return `"visible"` instead of `"prerender"` * Enabling `window.requestAnimationFrame()` and `window.cancelAnimationFrame()` methods, which otherwise do not exist ```js const window = (new JSDOM(``, { pretendToBeVisual: true })).window; window.requestAnimationFrame(timestamp => { console.log(timestamp > 0); }); ``` Note that jsdom still [does not do any layout or rendering](#unimplemented-parts-of-the-web-platform), so this is really just about _pretending_ to be visual, not about implementing the parts of the platform a real, visual web browser would implement. ### Loading subresources #### Basic options By default, jsdom will not load any subresources such as scripts, stylesheets, images, or iframes. If you'd like jsdom to load such resources, you can pass the `resources: "usable"` option, which will load all usable resources. Those are: * Frames and iframes, via `<frame>` and `<iframe>` * Stylesheets, via `<link rel="stylesheet">` * Scripts, via `<script>`, but only if `runScripts: "dangerously"` is also set * Images, via `<img>`, but only if the `canvas` npm package is also installed (see "[Canvas Support](#canvas-support)" below) When attempting to load resources, recall that the default value for the `url` option is `"about:blank"`, which means that any resources included via relative URLs will fail to load. (The result of trying to parse the URL `/something` against the URL `about:blank` is an error.) So, you'll likely want to set a non-default value for the `url` option in those cases, or use one of the [convenience APIs](#convenience-apis) that do so automatically. #### Advanced configuration _This resource loader system is new as of jsdom v12.0.0, and we'd love your feedback on whether it meets your needs and how easy it is to use. Please file an issue to discuss!_ To more fully customize jsdom's resource-loading behavior, you can pass an instance of the `ResourceLoader` class as the `resources` option value: ```js const resourceLoader = new jsdom.ResourceLoader({ proxy: "http://127.0.0.1:9001", strictSSL: false, userAgent: "Mellblomenator/9000", }); const dom = new JSDOM(``, { resources: resourceLoader }); ``` The three options to the `ResourceLoader` constructor are: - `proxy` is the address of an HTTP proxy to be used. - `strictSSL` can be set to false to disable the requirement that SSL certificates be valid. - `userAgent` affects the `User-Agent` header sent, and thus the resulting value for `navigator.userAgent`. It defaults to <code>\`Mozilla/5.0 (${process.platform || "unknown OS"}) AppleWebKit/537.36 (KHTML, like Gecko) jsdom/${jsdomVersion}\`</code>. You can further customize resource fetching by subclassing `ResourceLoader` and overriding the `fetch()` method. For example, here is a version that only returns results for requests to a trusted origin: ```js class CustomResourceLoader extends jsdom.ResourceLoader { fetch(url, options) { // Override the contents of this script to do something unusual. if (url === "https://example.com/some-specific-script.js") { return Promise.resolve(Buffer.from("window.someGlobal = 5;")); } return super.fetch(url, options); } } ``` jsdom will call your custom resource loader's `fetch()` method whenever it encounters a "usable" resource, per the above section. The method takes a URL string, as well as a few options which you should pass through unmodified if calling `super.fetch()`. It must return a promise for a Node.js `Buffer` object, or return `null` if the resource is intentionally not to be loaded. In general, most cases will want to delegate to `super.fetch()`, as shown. One of the options you will receive in `fetch()` will be the element (if applicable) that is fetching a resource. ```js class CustomResourceLoader extends jsdom.ResourceLoader { fetch(url, options) { if (options.element) { console.log(`Element ${options.element.localName} is requesting the url ${url}`); } return super.fetch(url, options); } } ``` ### Virtual consoles Like web browsers, jsdom has the concept of a "console". This records both information directly sent from the page, via scripts executing inside the document, as well as information from the jsdom implementation itself. We call the user-controllable console a "virtual console", to distinguish it from the Node.js `console` API and from the inside-the-page `window.console` API. By default, the `JSDOM` constructor will return an instance with a virtual console that forwards all its output to the Node.js console. To create your own virtual console and pass it to jsdom, you can override this default by doing ```js const virtualConsole = new jsdom.VirtualConsole(); const dom = new JSDOM(``, { virtualConsole }); ``` Code like this will create a virtual console with no behavior. You can give it behavior by adding event listeners for all the possible console methods: ```js virtualConsole.on("error", () => { ... }); virtualConsole.on("warn", () => { ... }); virtualConsole.on("info", () => { ... }); virtualConsole.on("dir", () => { ... }); // ... etc. See https://console.spec.whatwg.org/#logging ``` (Note that it is probably best to set up these event listeners *before* calling `new JSDOM()`, since errors or console-invoking script might occur during parsing.) If you simply want to redirect the virtual console output to another console, like the default Node.js one, you can do ```js virtualConsole.sendTo(console); ``` There is also a special event, `"jsdomError"`, which will fire with error objects to report errors from jsdom itself. This is similar to how error messages often show up in web browser consoles, even if they are not initiated by `console.error`. So far, the following errors are output this way: - Errors loading or parsing subresources (scripts, stylesheets, frames, and iframes) - Script execution errors that are not handled by a window `onerror` event handler that returns `true` or calls `event.preventDefault()` - Not-implemented errors resulting from calls to methods, like `window.alert`, which jsdom does not implement, but installs anyway for web compatibility If you're using `sendTo(c)` to send errors to `c`, by default it will call `c.error(errorStack[, errorDetail])` with information from `"jsdomError"` events. If you'd prefer to maintain a strict one-to-one mapping of events to method calls, and perhaps handle `"jsdomError"`s yourself, then you can do ```js virtualConsole.sendTo(c, { omitJSDOMErrors: true }); ``` ### Cookie jars Like web browsers, jsdom has the concept of a cookie jar, storing HTTP cookies. Cookies that have a URL on the same domain as the document, and are not marked HTTP-only, are accessible via the `document.cookie` API. Additionally, all cookies in the cookie jar will impact the fetching of subresources. By default, the `JSDOM` constructor will return an instance with an empty cookie jar. To create your own cookie jar and pass it to jsdom, you can override this default by doing ```js const cookieJar = new jsdom.CookieJar(store, options); const dom = new JSDOM(``, { cookieJar }); ``` This is mostly useful if you want to share the same cookie jar among multiple jsdoms, or prime the cookie jar with certain values ahead of time. Cookie jars are provided by the [tough-cookie](https://www.npmjs.com/package/tough-cookie) package. The `jsdom.CookieJar` constructor is a subclass of the tough-cookie cookie jar which by default sets the `looseMode: true` option, since that [matches better how browsers behave](https://github.com/whatwg/html/issues/804). If you want to use tough-cookie's utilities and classes yourself, you can use the `jsdom.toughCookie` module export to get access to the tough-cookie module instance packaged with jsdom. ### Intervening before parsing jsdom allows you to intervene in the creation of a jsdom very early: after the `Window` and `Document` objects are created, but before any HTML is parsed to populate the document with nodes: ```js const dom = new JSDOM(`<p>Hello</p>`, { beforeParse(window) { window.document.childNodes.length === 0; window.someCoolAPI = () => { /* ... */ }; } }); ``` This is especially useful if you are wanting to modify the environment in some way, for example adding shims for web platform APIs jsdom does not support. ## `JSDOM` object API Once you have constructed a `JSDOM` object, it will have the following useful capabilities: ### Properties The property `window` retrieves the `Window` object that was created for you. The properties `virtualConsole` and `cookieJar` reflect the options you pass in, or the defaults created for you if nothing was passed in for those options. ### Serializing the document with `serialize()` The `serialize()` method will return the [HTML serialization](https://html.spec.whatwg.org/#html-fragment-serialisation-algorithm) of the document, including the doctype: ```js const dom = new JSDOM(`<!DOCTYPE html>hello`); dom.serialize() === "<!DOCTYPE html><html><head></head><body>hello</body></html>"; // Contrast with: dom.window.document.documentElement.outerHTML === "<html><head></head><body>hello</body></html>"; ``` ### Getting the source location of a node with `nodeLocation(node)` The `nodeLocation()` method will find where a DOM node is within the source document, returning the [parse5 location info](https://www.npmjs.com/package/parse5#options-locationinfo) for the node: ```js const dom = new JSDOM( `<p>Hello <img src="foo.jpg"> </p>`, { includeNodeLocations: true } ); const document = dom.window.document; const bodyEl = document.body; // implicitly created const pEl = document.querySelector("p"); const textNode = pEl.firstChild; const imgEl = document.querySelector("img"); console.log(dom.nodeLocation(bodyEl)); // null; it's not in the source console.log(dom.nodeLocation(pEl)); // { startOffset: 0, endOffset: 39, startTag: ..., endTag: ... } console.log(dom.nodeLocation(textNode)); // { startOffset: 3, endOffset: 13 } console.log(dom.nodeLocation(imgEl)); // { startOffset: 13, endOffset: 32 } ``` Note that this feature only works if you have set the `includeNodeLocations` option; node locations are off by default for performance reasons. ### Interfacing with the Node.js `vm` module using `getInternalVMContext()` The built-in [`vm`](https://nodejs.org/api/vm.html) module of Node.js is what underpins jsdom's script-running magic. Some advanced use cases, like pre-compiling a script and then running it multiple times, benefit from using the `vm` module directly with a jsdom-created `Window`. To get access to the [contextified global object](https://nodejs.org/api/vm.html#vm_what_does_it_mean_to_contextify_an_object), suitable for use with the `vm` APIs, you can use the `getInternalVMContext()` method: ```js const { Script } = require("vm"); const dom = new JSDOM(``, { runScripts: "outside-only" }); const script = new Script(` if (!this.ran) { this.ran = 0; } ++this.ran; `); const vmContext = dom.getInternalVMContext(); script.runInContext(vmContext); script.runInContext(vmContext); script.runInContext(vmContext); console.assert(dom.window.ran === 3); ``` This is somewhat-advanced functionality, and we advise sticking to normal DOM APIs (such as `window.eval()` or `document.createElement("script")`) unless you have very specific needs. Note that this method will throw an exception if the `JSDOM` instance was created without `runScripts` set, or if you are [using jsdom in a web browser](#running-jsdom-inside-a-web-browser). ### Reconfiguring the jsdom with `reconfigure(settings)` The `top` property on `window` is marked `[Unforgeable]` in the spec, meaning it is a non-configurable own property and thus cannot be overridden or shadowed by normal code running inside the jsdom, even using `Object.defineProperty`. Similarly, at present jsdom does not handle navigation (such as setting `window.location.href = "https://example.com/"`); doing so will cause the virtual console to emit a `"jsdomError"` explaining that this feature is not implemented, and nothing will change: there will be no new `Window` or `Document` object, and the existing `window`'s `location` object will still have all the same property values. However, if you're acting from outside the window, e.g. in some test framework that creates jsdoms, you can override one or both of these using the special `reconfigure()` method: ```js const dom = new JSDOM(); dom.window.top === dom.window; dom.window.location.href === "about:blank"; dom.reconfigure({ windowTop: myFakeTopForTesting, url: "https://example.com/" }); dom.window.top === myFakeTopForTesting; dom.window.location.href === "https://example.com/"; ``` Note that changing the jsdom's URL will impact all APIs that return the current document URL, such as `window.location`, `document.URL`, and `document.documentURI`, as well as the resolution of relative URLs within the document, and the same-origin checks and referrer used while fetching subresources. It will not, however, perform navigation to the contents of that URL; the contents of the DOM will remain unchanged, and no new instances of `Window`, `Document`, etc. will be created. ## Convenience APIs ### `fromURL()` In addition to the `JSDOM` constructor itself, jsdom provides a promise-returning factory method for constructing a jsdom from a URL: ```js JSDOM.fromURL("https://example.com/", options).then(dom => { console.log(dom.serialize()); }); ``` The returned promise will fulfill with a `JSDOM` instance if the URL is valid and the request is successful. Any redirects will be followed to their ultimate destination. The options provided to `fromURL()` are similar to those provided to the `JSDOM` constructor, with the following additional restrictions and consequences: - The `url` and `contentType` options cannot be provided. - The `referrer` option is used as the HTTP `Referer` request header of the initial request. - The `resources` option also affects the initial request; this is useful if you want to, for example, configure a proxy (see above). - The resulting jsdom's URL, content type, and referrer are determined from the response. - Any cookies set via HTTP `Set-Cookie` response headers are stored in the jsdom's cookie jar. Similarly, any cookies already in a supplied cookie jar are sent as HTTP `Cookie` request headers. ### `fromFile()` Similar to `fromURL()`, jsdom also provides a `fromFile()` factory method for constructing a jsdom from a filename: ```js JSDOM.fromFile("stuff.html", options).then(dom => { console.log(dom.serialize()); }); ``` The returned promise will fulfill with a `JSDOM` instance if the given file can be opened. As usual in Node.js APIs, the filename is given relative to the current working directory. The options provided to `fromFile()` are similar to those provided to the `JSDOM` constructor, with the following additional defaults: - The `url` option will default to a file URL corresponding to the given filename, instead of to `"about:blank"`. - The `contentType` option will default to `"application/xhtml+xml"` if the given filename ends in `.xht`, `.xhtml`, or `.xml`; otherwise it will continue to default to `"text/html"`. ### `fragment()` For the very simplest of cases, you might not need a whole `JSDOM` instance with all its associated power. You might not even need a `Window` or `Document`! Instead, you just need to parse some HTML, and get a DOM object you can manipulate. For that, we have `fragment()`, which creates a `DocumentFragment` from a given string: ```js const frag = JSDOM.fragment(`<p>Hello</p><p><strong>Hi!</strong>`); frag.childNodes.length === 2; frag.querySelector("strong").textContent === "Hi!"; // etc. ``` Here `frag` is a [`DocumentFragment`](https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment) instance, whose contents are created by parsing the provided string. The parsing is done using a `<template>` element, so you can include any element there (including ones with weird parsing rules like `<td>`). It's also important to note that the resulting `DocumentFragment` will not have [an associated browsing context](https://html.spec.whatwg.org/multipage/#concept-document-bc): that is, elements' `ownerDocument` will have a null `defaultView` property, resources will not load, etc. All invocations of the `fragment()` factory result in `DocumentFragment`s that share the same template owner `Document`. This allows many calls to `fragment()` with no extra overhead. But it also means that calls to `fragment()` cannot be customized with any options. Note that serialization is not as easy with `DocumentFragment`s as it is with full `JSDOM` objects. If you need to serialize your DOM, you should probably use the `JSDOM` constructor more directly. But for the special case of a fragment containing a single element, it's pretty easy to do through normal means: ```js const frag = JSDOM.fragment(`<p>Hello</p>`); console.log(frag.firstChild.outerHTML); // logs "<p>Hello</p>" ``` ## Other noteworthy features ### Canvas support jsdom includes support for using the [`canvas`](https://www.npmjs.com/package/canvas) package to extend any `<canvas>` elements with the canvas API. To make this work, you need to include `canvas` as a dependency in your project, as a peer of `jsdom`. If jsdom can find the `canvas` package, it will use it, but if it's not present, then `<canvas>` elements will behave like `<div>`s. Since jsdom v13, version 2.x of `canvas` is required; version 1.x is no longer supported. ### Encoding sniffing In addition to supplying a string, the `JSDOM` constructor can also be supplied binary data, in the form of a Node.js [`Buffer`](https://nodejs.org/docs/latest/api/buffer.html) or a standard JavaScript binary data type like `ArrayBuffer`, `Uint8Array`, `DataView`, etc. When this is done, jsdom will [sniff the encoding](https://html.spec.whatwg.org/multipage/syntax.html#encoding-sniffing-algorithm) from the supplied bytes, scanning for `<meta charset>` tags just like a browser does. If the supplied `contentType` option contains a `charset` parameter, that encoding will override the sniffed encoding—unless a UTF-8 or UTF-16 BOM is present, in which case those take precedence. (Again, this is just like a browser.) This encoding sniffing also applies to `JSDOM.fromFile()` and `JSDOM.fromURL()`. In the latter case, any `Content-Type` headers sent with the response will take priority, in the same fashion as the constructor's `contentType` option. Note that in many cases supplying bytes in this fashion can be better than supplying a string. For example, if you attempt to use Node.js's `buffer.toString("utf-8")` API, Node.js will not strip any leading BOMs. If you then give this string to jsdom, it will interpret it verbatim, leaving the BOM intact. But jsdom's binary data decoding code will strip leading BOMs, just like a browser; in such cases, supplying `buffer` directly will give the desired result. ### Closing down a jsdom Timers in the jsdom (set by `window.setTimeout()` or `window.setInterval()`) will, by definition, execute code in the future in the context of the window. Since there is no way to execute code in the future without keeping the process alive, outstanding jsdom timers will keep your Node.js process alive. Similarly, since there is no way to execute code in the context of an object without keeping that object alive, outstanding jsdom timers will prevent garbage collection of the window on which they are scheduled. If you want to be sure to shut down a jsdom window, use `window.close()`, which will terminate all running timers (and also remove any event listeners on the window and document). ### Running jsdom inside a web browser jsdom has some support for being run inside a web browser, using [browserify](https://browserify.org/). That is, inside a web browser, you can use a browserified jsdom to create an entirely self-contained set of plain JavaScript objects which look and act much like the browser's existing DOM objects, while being entirely independent of them. "Virtual DOM", indeed! jsdom's primary target is still Node.js, and so we use language features that are only present in recent Node.js versions (namely, Node.js v8+). Thus, older browsers will likely not work. (Even transpilation will not help: we use `Proxy`s extensively throughout the jsdom codebase.) Notably, jsdom works well inside a web worker. The original contributor, [@lawnsea](https://github.com/lawnsea/), who made this possible, has [published a paper](https://pdfs.semanticscholar.org/47f0/6bb6607a975500a30e9e52d7c9fbc0034e27.pdf) about his project which uses this capability. Not everything works perfectly when running jsdom inside a web browser. Sometimes that is because of fundamental limitations (such as not having filesystem access), but sometimes it is simply because we haven't spent enough time making the appropriate small tweaks. Bug reports are certainly welcome. ### Debugging the DOM using Chrome Devtools As of Node.js v6 you can debug programs using Chrome Devtools. See the [official documentation](https://nodejs.org/en/docs/inspector/) for how to get started. By default jsdom elements are formatted as plain old JS objects in the console. To make it easier to debug, you can use [jsdom-devtools-formatter](https://github.com/viddo/jsdom-devtools-formatter), which lets you inspect them like real DOM elements. ## Caveats ### Asynchronous script loading People often have trouble with asynchronous script loading when using jsdom. Many pages load scripts asynchronously, but there is no way to tell when they're done doing so, and thus when it's a good time to run your code and inspect the resulting DOM structure. This is a fundamental limitation; we cannot predict what scripts on the web page will do, and so cannot tell you when they are done loading more scripts. This can be worked around in a few ways. The best way, if you control the page in question, is to use whatever mechanisms are given by the script loader to detect when loading is done. For example, if you're using a module loader like RequireJS, the code could look like: ```js // On the Node.js side: const window = (new JSDOM(...)).window; window.onModulesLoaded = () => { console.log("ready to roll!"); }; ``` ```html <!-- Inside the HTML you supply to jsdom --> <script> requirejs(["entry-module"], () => { window.onModulesLoaded(); }); </script> ``` If you do not control the page, you could try workarounds such as polling for the presence of a specific element. For more details, see the discussion in [#640](https://github.com/jsdom/jsdom/issues/640), especially [@matthewkastor](https://github.com/matthewkastor)'s [insightful comment](https://github.com/jsdom/jsdom/issues/640#issuecomment-22216965). ### Unimplemented parts of the web platform Although we enjoy adding new features to jsdom and keeping it up to date with the latest web specs, it has many missing APIs. Please feel free to file an issue for anything missing, but we're a small and busy team, so a pull request might work even better. Beyond just features that we haven't gotten to yet, there are two major features that are currently outside the scope of jsdom. These are: - **Navigation**: the ability to change the global object, and all other objects, when clicking a link or assigning `location.href` or similar. - **Layout**: the ability to calculate where elements will be visually laid out as a result of CSS, which impacts methods like `getBoundingClientRects()` or properties like `offsetTop`. Currently jsdom has dummy behaviors for some aspects of these features, such as sending a "not implemented" `"jsdomError"` to the virtual console for navigation, or returning zeros for many layout-related properties. Often you can work around these limitations in your code, e.g. by creating new `JSDOM` instances for each page you "navigate" to during a crawl, or using `Object.defineProperty()` to change what various layout-related getters and methods return. Note that other tools in the same space, such as PhantomJS, do support these features. On the wiki, we have a more complete writeup about [jsdom vs. PhantomJS](https://github.com/jsdom/jsdom/wiki/jsdom-vs.-PhantomJS). ## Supporting jsdom jsdom is a community-driven project maintained by a team of [volunteers](https://github.com/orgs/jsdom/people). You could support jsdom by: - [Getting professional support for jsdom](https://tidelift.com/subscription/pkg/npm-jsdom?utm_source=npm-jsdom&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](https://github.com/jsdom/jsdom/blob/master/Contributing.md) directly to the project. ## Getting help If you need help with jsdom, please feel free to use any of the following venues: - The [mailing list](http://groups.google.com/group/jsdom) (best for "how do I" questions) - The [issue tracker](https://github.com/jsdom/jsdom/issues) (best for bug reports) - The IRC channel: [#jsdom on freenode](irc://irc.freenode.net/jsdom) # 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 tslib@1.6.1 ``` ## yarn ```sh # TypeScript 2.3.3 or later yarn add tslib # TypeScript 2.3.2 or earlier yarn add tslib@1.6.1 ``` ## bower ```sh # TypeScript 2.3.3 or later bower install tslib # TypeScript 2.3.2 or earlier bower install tslib@1.6.1 ``` ## JSPM ```sh # TypeScript 2.3.3 or later jspm install tslib # TypeScript 2.3.2 or earlier jspm install tslib@1.6.1 ``` # 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.13.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/) # 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 > etag@1.8.1 bench nodejs-etag > node benchmark/index.js http_parser@2.7.0 node@6.11.1 v8@5.1.281.103 uv@1.11.0 zlib@1.2.11 ares@1.10.1-DEV icu@58.2 modules@48 openssl@1.0.2k > 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 # 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._ 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 }); }); ... ``` # 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). <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 # 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._ 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**. # 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._ <a href="http://promisesaplus.com/"> <img src="https://promises-aplus.github.io/promises-spec/assets/logo-small.png" align="right" alt="Promises/A+ logo" /> </a> # request-promise-core [![Gitter](https://img.shields.io/badge/gitter-join_chat-blue.svg?style=flat-square&maxAge=2592000)](https://gitter.im/request/request-promise?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Build Status](https://img.shields.io/travis/request/promise-core/master.svg?style=flat-square&maxAge=2592000)](https://travis-ci.org/request/promise-core) [![Coverage Status](https://img.shields.io/coveralls/request/promise-core.svg?style=flat-square&maxAge=2592000)](https://coveralls.io/r/request/promise-core) [![Dependency Status](https://img.shields.io/david/request/promise-core.svg?style=flat-square&maxAge=2592000)](https://david-dm.org/request/promise-core) [![Known Vulnerabilities](https://snyk.io/test/npm/promise-core/badge.svg?style=flat-square&maxAge=2592000)](https://snyk.io/test/npm/promise-core) This package is the core for the following packages: - [`request-promise`](https://github.com/request/request-promise) - [`request-promise-any`](https://github.com/request/request-promise-any) - [`request-promise-bluebird`](https://github.com/request/request-promise-bluebird) - [`request-promise-native`](https://github.com/request/request-promise-native) `request-promise-core` contains the core logic to add Promise support to [`request`](https://github.com/request/request). Please use one of the libraries above. It is only recommended to use this library directly, if you have very specific requirements. ## Installation for `request@^2.34` This module is installed via npm: ``` npm install --save request npm install --save request-promise-core ``` `request` is defined as a peer-dependency and thus has to be installed separately. ## Usage for `request@^2.34` ``` js // 1. Load the request library // Only use a direct require if you are 100% sure that: // - Your project does not use request directly. That is without the Promise capabilities by calling require('request'). // - Any of the installed libraries use request. // ...because Request's prototype will be patched in step 2. /* var request = require('request'); */ // Instead use: var stealthyRequire = require('stealthy-require'); var request = stealthyRequire(require.cache, function () { return require('request'); }); // 2. Add Promise support to request var configure = require('request-promise-core/configure/request2'); configure({ request: request, // Pass your favorite ES6-compatible promise implementation PromiseImpl: Promise, // Expose all methods of the promise instance you want to call on the request(...) call expose: [ 'then', // Allows to use request(...).then(...) 'catch', // Allows to use request(...).catch(...) 'promise' // Allows to use request(...).promise() which returns the promise instance ], // Optional: Pass a callback that is called within the Promise constructor constructorMixin: function (resolve, reject) { // `this` is the request object // Additional arguments may be passed depending on the PromiseImpl used } }); // 3. Use request with its promise capabilities // E.g. crawl a web page: request('http://www.google.com') .then(function (htmlString) { // Process html... }) .catch(function (err) { // Crawling failed... }); ``` ## Installation and Usage for `request@next` [Request Next](https://github.com/request/request/issues/1982) is still in alpha. However, `request-promise-core` is already designed to be compatible and ships with a configuration helper – `require('request-promise-core/configure/request-next')` – that is [used by `request-promise`](https://github.com/request/request-promise/blob/next/lib/rp.js) in its "next" branch. ## Contributing To set up your development environment: 1. clone the repo to your desktop, 2. in the shell `cd` to the main folder, 3. hit `npm install`, 4. hit `npm install gulp -g` if you haven't installed gulp globally yet, and 5. run `gulp dev`. (Or run `node ./node_modules/.bin/gulp dev` if you don't want to install gulp globally.) `gulp dev` watches all source files and if you save some changes it will lint the code and execute all tests. The test coverage report can be viewed from `./coverage/lcov-report/index.html`. If you want to debug a test you should use `gulp test-without-coverage` to run all tests without obscuring the code by the test coverage instrumentation. ## Change History - 1.1.4 (2020-07-21) - Security fix: bumped `lodash` to `^4.17.19` following [this advisory](https://www.npmjs.com/advisories/1523). - 1.1.3 (2019-11-03) - Security fix: bumped `lodash` to `^4.17.15`. See [vulnerabilty reports](https://snyk.io/vuln/search?q=lodash&type=npm). *(Thanks to @daniel-nagy for pull request [#20](https://github.com/request/promise-core/pull/20) and thanks to @quetzaluz for reporting this in issue [#21](https://github.com/request/promise-core/issues/21).)* - 1.1.2 (2019-02-14) - Security fix: bumped `lodash` to `^4.17.11`. See [vulnerabilty reports](https://snyk.io/vuln/search?q=lodash&type=npm). *(Thanks to @lucaswillering and @sam-warren-finnair for reporting this in issues [#12](https://github.com/request/promise-core/issues/12) and [#13](https://github.com/request/promise-core/issues/13) and thanks to @Alec321 for pull request [#14](https://github.com/request/promise-core/pull/14).)* - 1.1.1 (2016-08-08) - Renamed package to `request-promise-core` because there were [too](https://github.com/request/request-promise/issues/137) [many](https://github.com/request/request-promise/issues/141) issues with the scoped package name `@request/promise-core` - 1.1.0 (2016-07-30) - Added `constructorMixin` option to enable [request/request-promise#123](https://github.com/request/request-promise/pull/123) - 1.0.0 (2016-07-15) - All tests green, ready for prime time - 1.0.0-rc.1 (2016-07-10) - Reimplementation of core logic based on `request-promise@3.0.0` - Plus `transform2xxOnly` option (fixes [request/request-promise#131](https://github.com/request/request-promise/issues/131)) ## License (ISC) In case you never heard about the [ISC license](http://en.wikipedia.org/wiki/ISC_license) it is functionally equivalent to the MIT license. See the [LICENSE file](LICENSE) for details. # 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 # browser-process-hrtime Browser shim for Node.js `process.hrtime()`. See [documentation at nodejs.org](http://nodejs.org/api/process.html#process_process_hrtime) This module does not provide the same level of time precision as node.js, but provides a matching API and response format. ### usage Use hrtime independent of environment (node or browser). It will use `process.hrtime` first and fallback if not present. ```js const hrtime = require('browser-process-hrtime') const start = hrtime() // ... const delta = hrtime(start) ``` ### monkey-patching You can monkey-patch `process.hrtime` for your dependency graph like this: ```js process.hrtime = require('browser-process-hrtime') const coolTool = require('module-that-uses-hrtime-somewhere-in-its-depths') ``` ### note This was originally pull-requested against [node-process](https://github.com/defunctzombie/node-process), but they are trying to stay lean. # 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/node-forge@0.7.0/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/node-forge@0.7.0/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); // PKCS#7 Sign in detached mode. // Includes the signature and certificate without the signed data. p7.sign({detached: true}); ``` <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: support@digitalbazaar.com * IRC: [#forgejs][] on [freenode][] Donations --------- Financial support is welcome and helps contribute to futher development: * For [PayPal][] please send to paypal@digitalbazaar.com. * Something else? Please contact support@digitalbazaar.com. [#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 # send [![NPM Version][npm-version-image]][npm-url] [![NPM Downloads][npm-downloads-image]][npm-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 ### Serve a specific file This simple example will send a specific file to all requests. ```js var http = require('http') var send = require('send') var server = http.createServer(function onRequest (req, res) { send(req, '/path/to/index.html') .pipe(res) }) server.listen(3000) ``` ### Serve all files from a directory This simple example will just serve up all the files in a given directory as the top-level. For example, a request `GET /foo.txt` will send back `/www/public/foo.txt`. ```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, { root: '/www/public' }) .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, { root: '/www/public' }) .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/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/public' }) .on('error', error) .on('directory', redirect) .on('headers', headers) .pipe(res) }) server.listen(3000) ``` ## License [MIT](LICENSE) [appveyor-image]: https://badgen.net/appveyor/ci/dougwilson/send/master?label=windows [appveyor-url]: https://ci.appveyor.com/project/dougwilson/send [coveralls-image]: https://badgen.net/coveralls/c/github/pillarjs/send/master [coveralls-url]: https://coveralls.io/r/pillarjs/send?branch=master [node-image]: https://badgen.net/npm/node/send [node-url]: https://nodejs.org/en/download/ [npm-downloads-image]: https://badgen.net/npm/dm/send [npm-url]: https://npmjs.org/package/send [npm-version-image]: https://badgen.net/npm/v/send [travis-image]: https://badgen.net/travis/pillarjs/send/master?label=linux [travis-url]: https://travis-ci.org/pillarjs/send # 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). # 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;julian@juliangruber.com&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. 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 # 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;julian@juliangruber.com&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 [![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(); // ⇨ '2c5ea4c0-4067-11e9-8bad-9b1deb4d3b7d' ``` 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(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' ``` 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' ``` ## 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 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. 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); // ⇨ // [ // 44, 94, 164, 192, 64, 103, // 17, 233, 146, 52, 155, 29, // 235, 77, 59, 125 // ] uuidv1(null, arr, 16); // ⇨ // [ // 44, 94, 164, 192, 64, 103, 17, 233, // 146, 52, 155, 29, 235, 77, 59, 125, // 44, 94, 164, 193, 64, 103, 17, 233, // 146, 52, 155, 29, 235, 77, 59, 125 // ] ``` ### 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); // ⇨ // [ // 155, 29, 235, 77, 59, // 125, 75, 173, 155, 221, // 43, 13, 123, 61, 203, // 109 // ] uuidv4(null, buffer, 16); // ⇨ // [ // 155, 29, 235, 77, 59, 125, 75, 173, // 155, 221, 43, 13, 123, 61, 203, 109, // 27, 157, 107, 205, 187, 253, 75, 45, // 155, 93, 171, 141, 251, 189, 75, 237 // ] ``` ### 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) # 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. 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. # 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/) # Parse `data:` URLs This package helps you parse `data:` URLs [according to the WHATWG Fetch Standard](https://fetch.spec.whatwg.org/#data-urls): ```js const parseDataURL = require("data-url"); const textExample = parseDataURL("data:,Hello%2C%20World!"); console.log(textExample.mimeType.toString()); // "text/plain;charset=US-ASCII" console.log(textExample.body.toString()); // "Hello, World!" const htmlExample = dataURL("data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E"); console.log(htmlExample.mimeType.toString()); // "text/html" console.log(htmlExample.body.toString()); // <h1>Hello, World!</h1> const pngExample = parseDataURL("data:image/png;base64,iVBORw0KGgoAAA" + "ANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4" + "//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU" + "5ErkJggg=="); console.log(pngExample.mimeType.toString()); // "image/png" console.log(pngExample.body); // <Buffer 89 50 4e 47 0d ... > ``` ## API This package's main module's default export is a function that accepts a string and returns a `{ mimeType, body }` object, or `null` if the result cannot be parsed as a `data:` URL. - The `mimeType` property is an instance of [whatwg-mimetype](https://www.npmjs.com/package/whatwg-mimetype)'s `MIMEType` class. - The `body` property is a Node.js [`Buffer`](https://nodejs.org/docs/latest/api/buffer.html) instance. As shown in the examples above, both of these have useful `toString()` methods for manipulating them as string values. However… ### A word of caution on string decoding Because Node.js's `Buffer.prototype.toString()` assumes a UTF-8 encoding, simply doing `dataURL.body.toString()` may not work correctly if the `data:` URL's contents were not originally written in UTF-8. This includes if the encoding is "US-ASCII", [aka windows-1252](https://encoding.spec.whatwg.org/#names-and-labels), which is notable for being the default in many cases. A more complete decoding example would use the [whatwg-encoding](https://www.npmjs.com/package/whatwg-encoding) package as follows: ```js const parseDataURL = require("data-url"); const { labelToName, decode } = require("whatwg-encoding"); const dataURL = parseDataURL(arbitraryString); const encodingName = labelToName(dataURL.mimeType.parameters.get("charset")); const bodyDecoded = decode(dataURL.body, encodingName); ``` For example, given an `arbitraryString` of `data:,Hello!`, this will produce a `bodyDecoded` of `"Hello!"`, as expected. But given an `arbitraryString` of `"data:,Héllo!"`, this will correctly produce a `bodyDecoded` of `"Héllo!"`, whereas just doing `dataURL.body.toString()` will give back `"Héllo!"`. In summary, only use `dataURL.body.toString()` when you are very certain your data is inside the ASCII range (i.e. code points within the range U+0000 to U+007F). ### Advanced functionality: parsing from a URL record If you are using the [whatwg-url](https://github.com/jsdom/whatwg-url) package, you may already have a "URL record" object on hand, as produced by that package's `parseURL` export. In that case, you can use this package's `fromURLRecord` export to save a bit of work: ```js const { parseURL } = require("whatwg-url"); const dataURLFromURLRecord = require("data-url").fromURLRecord; const urlRecord = parseURL("data:,Hello%2C%20World!"); const dataURL = dataURLFromURLRecord(urlRecord); ``` In practice, we expect this functionality only to be used by consumers like [jsdom](https://www.npmjs.com/package/jsdom), which are using these packages at a very low level. # 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._ # 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. <p align="center"> <img src="https://raw.githubusercontent.com/tabrindle/envinfo/master/logo.png" align="center" width="700px"/> <h3 align="center">envinfo generates a report of the common details needed when troubleshooting software issues, such as your operating system, binary versions, browsers, installed languages, and more</h3> <hr/> </p> [![CircleCI](https://circleci.com/gh/tabrindle/envinfo/tree/master.svg?style=svg)](https://circleci.com/gh/tabrindle/envinfo/tree/master) [![Build Status](https://travis-ci.org/tabrindle/envinfo.svg?branch=master)](https://travis-ci.org/tabrindle/envinfo) [![npm version](https://badge.fury.io/js/envinfo.svg)](https://badge.fury.io/js/envinfo) [![npm downloads per month](https://img.shields.io/npm/dm/envinfo.svg?maxAge=86400)](https://www.npmjs.com/package/envinfo) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![All Contributors](https://img.shields.io/badge/all_contributors-10-orange.svg?style=flat-square)](#contributors) ## The problem - It works on my computer - "command not found" - what version of "command" are you running? - what version of "different command" are you running? - do you have "insert obscure android sdk version"? - every github issue reporting template ever: **Please mention other relevant information such as the browser version, Node.js version, Operating System and programming language.** ## This solution - Gather all of this information in one spot, quickly, and painlessly. ## Installation To use as a CLI tool, install this package globally: ```sh npm install -g envinfo || yarn global add envinfo ``` Or, use without installing with npx: `npx envinfo` To use as a library in another project: ```sh npm install envinfo || yarn add envinfo ``` ## CLI Usage `envinfo` || `npx envinfo` ```bash System: OS: macOS Mojave 10.14.5 CPU: (8) x64 Intel(R) Core(TM) i7-7820HQ CPU @ 2.90GHz Memory: 2.97 GB / 16.00 GB Shell: 5.3 - /bin/zsh Binaries: Node: 8.16.0 - ~/.nvm/versions/node/v8.16.0/bin/node Yarn: 1.15.2 - ~/.yarn/bin/yarn npm: 6.9.0 - ~/.nvm/versions/node/v8.16.0/bin/npm Watchman: 4.9.0 - /usr/local/bin/watchman Managers: Cargo: 1.31.0 - ~/.cargo/bin/cargo CocoaPods: 1.7.3 - /usr/local/bin/pod Composer: 1.8.6 - /usr/local/bin/composer Gradle: 5.5 - /usr/local/bin/gradle Homebrew: 2.1.7 - /usr/local/bin/brew Maven: 3.6.1 - /usr/local/bin/mvn pip2: 19.0.3 - /usr/local/bin/pip2 pip3: 19.0.2 - /usr/local/bin/pip3 RubyGems: 2.5.2.3 - /usr/bin/gem Utilities: CMake: 3.13.3 - /usr/local/bin/cmake Make: 3.81 - /usr/bin/make GCC: 10.14. - /usr/bin/gcc Git: 2.20.0 - /usr/local/bin/git Mercurial: 4.5.3 - /usr/bin/hg Clang: 1001.0.46.4 - /usr/bin/clang Subversion: 1.10.3 - /usr/bin/svn Servers: Apache: 2.4.34 - /usr/sbin/apachectl Nginx: 1.13.12 - /usr/local/bin/nginx Virtualization: Docker: 18.09.1 - /usr/local/bin/docker Parallels: 13.3.0 - /usr/local/bin/prlctl VirtualBox: 5.2.20 - /usr/local/bin/vboxmanage SDKs: iOS SDK: Platforms: iOS 12.2, macOS 10.14, tvOS 12.2, watchOS 5.2 Android SDK: API Levels: 28 Build Tools: 28.0.3 System Images: android-28 | Google Play Intel x86 Atom IDEs: Android Studio: 3.2 AI-181.5540.7.32.5056338 Atom: 1.23.3 Emacs: 22.1.1 - /usr/bin/emacs Nano: 2.0.6 - /usr/bin/nano VSCode: 1.36.0 - /usr/local/bin/code Vim: 8.0 - /usr/bin/vim Xcode: 10.2.1/10E1001 - /usr/bin/xcodebuild Languages: Bash: 4.4.23 - /usr/local/bin/bash Elixir: 1.6.2 - /usr/local/bin/elixir Go: 1.11.1 - /usr/local/bin/go Java: 1.8.0_192 - /usr/bin/javac Perl: 5.18.4 - /usr/bin/perl PHP: 7.1.23 - /usr/bin/php Python: 2.7.16 - /usr/local/bin/python Python3: 3.7.2 - /usr/local/bin/python3 R: 3.6.0 - /usr/local/bin/R Ruby: 2.3.7 - /usr/bin/ruby Rust: 1.16.0 - /Users/tabrindle/.cargo/bin/rustup Databases: MongoDB: 3.6.4 - /usr/local/bin/mongo MySQL: 10.3.10 (MariaDB) - /usr/local/bin/mysql PostgreSQL: 10.3 - /usr/local/bin/postgres SQLite: 3.24.0 - /usr/bin/sqlite3 Browsers: Chrome: 75.0.3770.100 Chrome Canary: 77.0.3847.0 Firefox: 68.0 Firefox Developer Edition: 69.0 Firefox Nightly: 69.0a1 Safari: 12.1.1 Safari Technology Preview: 13.0 npmPackages: apollo-client: ^2.3.1 => 2.3.1 jest: ^22.2.1 => 22.2.1 ... react: ^16.3.2 => 16.3.2 react-apollo: ^2.1.4 => 2.1.4 run4staged: ^1.1.1 => 1.1.1 solidarity: 2.0.5 => 2.0.5 styled-components: ^3.1.6 => 3.1.6 npmGlobalPackages: create-react-app: 1.5.2 create-react-native-app: 1.0.0 envinfo: 5.10.0 exp: 49.2.2 gatsby-cli: 1.1.52 npm: 5.6.0 react-native-cli: 2.0.1 solidarity: 2.1.0 typescript: 2.8.1 ``` ## Programmatic Usage Envinfo takes a configuration object and returns a Promise that resolves a string (optionally yaml, json or markdown) ```javascript import envinfo from 'envinfo'; envinfo.run( { System: ['OS', 'CPU'], Binaries: ['Node', 'Yarn', 'npm'], Browsers: ['Chrome', 'Firefox', 'Safari'], npmPackages: ['styled-components', 'babel-plugin-styled-components'], }, { json: true, showNotFound: true } ).then(env => console.log(env)); ``` logs: ```json { "System": { "OS": "macOS High Sierra 10.13", "CPU": "x64 Intel(R) Core(TM) i7-4870HQ CPU @ 2.50GHz" }, "Binaries": { "Node": { "version": "8.11.0", "path": "~/.nvm/versions/node/v8.11.0/bin/node" }, "Yarn": { "version": "1.5.1", "path": "~/.yarn/bin/yarn" }, "npm": { "version": "5.6.0", "path": "~/.nvm/versions/node/v8.11.0/bin/npm" } }, "Browsers": { "Chrome": { "version": "67.0.3396.62" }, "Firefox": { "version": "59.0.2" }, "Safari": { "version": "11.0" } }, "npmPackages": { "styled-components": { "wanted": "^3.2.1", "installed": "3.2.1" }, "babel-plugin-styled-components": "Not Found" } } ``` All of envinfo's helpers are also exported for use. You can use envinfo as a whole, or just the parts that you need, like this: ```javascript const envinfo = require('envinfo'); // each helper returns a promise const node = await envinfo.helpers.getNodeInfo(); // The promises resolve to an array of values: ["Name", "Version", "Path"] // e.g. ["Node", "10.9.0", "/usr/local/bin/node"] console.log(`Node: ${node[1]} - ${node[2]}`); // "Node: 10.9.0 - ~/.nvm/versions/node/v8.14.0/bin/node" ``` ## CLI Options ``` --system Print general system info such as OS, CPU, Memory and Shell --browsers Get version numbers of installed web browsers --SDKs Get platforms, build tools and SDKs of iOS and Android --IDEs Get version numbers of installed IDEs --languages Get version numbers of installed languages such as Java, Python, PHP, etc --binaries Get version numbers of node, npm, watchman, etc --npmPackages Get version numbers of locally installed npm packages - glob, string, or comma delimited list --npmGlobalPackages Get version numbers of globally installed npm packages --duplicates Mark duplicate npm packages inside parentheses eg. (2.1.4) --fullTree Traverse entire node_modules dependency tree, not just top level --markdown Print output in markdown format --json Print output in JSON format --console Print to console (defaults to on for CLI usage, off for programmatic usage) ``` ## Integration envinfo is live in: - [React Native](https://github.com/facebook/react-native) (`react-native info`) - [Create React App](https://github.com/facebook/create-react-app) (`create-react-app --info`) - [Expo CLI](https://github.com/expo/expo-cli) (`expo diagnostics`) - [Webpack](https://github.com/webpack/webpack-cli) (`webpack-cli info`) - [Solidarity](https://github.com/infinitered/solidarity) (`solidarity report`) - [Gatsby](https://github.com/gatsbyjs/gatsby) (`gatsby info`) envinfo is used in the ISSUE_TEMPLATE of: - [styled-components](https://github.com/styled-components/styled-components) - [Jest](https://github.com/facebook/jest) - [Apollo Client](https://github.com/apollographql/apollo-client) ## Alternatives - type `command -v` until you smash your computer - [specs](https://github.com/mcandre/specs) - an excellent ruby gem that runs `command -v` for you on :all-the-things: Great for raw info. - [screenfetch](https://github.com/KittyKatt/screenFetch) - fetch system and terminal information, and display a pretty ascii logo - [Solidarity](https://github.com/infinitered/solidarity) - a project based environment checker - write your own ## License MIT ## Contributing PRs for additional features are welcome! Run `npm run lint && npm run format` before committing. This project came out of a [PR](https://github.com/facebook/react-native/pull/14428) to the React Native CLI tool - issues are reported frequently without important environment information, like Node/npm versions. ## 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://avatars1.githubusercontent.com/u/2925048?v=4" width="100px;"/><br /><sub><b>Trevor Brindle</b></sub>](http://trevorbrindle.com)<br />[💬](#question-tabrindle "Answering Questions") [📝](#blog-tabrindle "Blogposts") [🐛](https://github.com/tabrindle/envinfo/issues?q=author%3Atabrindle "Bug reports") [💻](https://github.com/tabrindle/envinfo/commits?author=tabrindle "Code") [📖](https://github.com/tabrindle/envinfo/commits?author=tabrindle "Documentation") [💡](#example-tabrindle "Examples") [🤔](#ideas-tabrindle "Ideas, Planning, & Feedback") [👀](#review-tabrindle "Reviewed Pull Requests") [📢](#talk-tabrindle "Talks") [⚠️](https://github.com/tabrindle/envinfo/commits?author=tabrindle "Tests") | [<img src="https://avatars0.githubusercontent.com/u/997157?v=4" width="100px;"/><br /><sub><b>Gant Laborde</b></sub>](http://gantlaborde.com/)<br />[📝](#blog-GantMan "Blogposts") [🐛](https://github.com/tabrindle/envinfo/issues?q=author%3AGantMan "Bug reports") [💻](https://github.com/tabrindle/envinfo/commits?author=GantMan "Code") [🤔](#ideas-GantMan "Ideas, Planning, & Feedback") | [<img src="https://avatars1.githubusercontent.com/u/599352?v=4" width="100px;"/><br /><sub><b>Anton Fisher</b></sub>](http://antonfisher.com)<br />[🐛](https://github.com/tabrindle/envinfo/issues?q=author%3Aantonfisher "Bug reports") [💻](https://github.com/tabrindle/envinfo/commits?author=antonfisher "Code") | [<img src="https://avatars1.githubusercontent.com/u/960133?v=4" width="100px;"/><br /><sub><b>Ahmad Awais ⚡️</b></sub>](https://AhmadAwais.com/)<br />[🐛](https://github.com/tabrindle/envinfo/issues?q=author%3Aahmadawais "Bug reports") [💻](https://github.com/tabrindle/envinfo/commits?author=ahmadawais "Code") | [<img src="https://avatars2.githubusercontent.com/u/9251453?v=4" width="100px;"/><br /><sub><b>Hasan</b></sub>](https://github.com/LEQADA)<br />[🐛](https://github.com/tabrindle/envinfo/issues?q=author%3ALEQADA "Bug reports") [💻](https://github.com/tabrindle/envinfo/commits?author=LEQADA "Code") | [<img src="https://avatars3.githubusercontent.com/u/1232725?v=4" width="100px;"/><br /><sub><b>Ernesto Ramírez</b></sub>](http://twitter.com/_ErnestoR)<br />[🐛](https://github.com/tabrindle/envinfo/issues?q=author%3AErnestoR "Bug reports") [💻](https://github.com/tabrindle/envinfo/commits?author=ErnestoR "Code") | [<img src="https://avatars1.githubusercontent.com/u/3759816?v=4" width="100px;"/><br /><sub><b>Jiawen Geng</b></sub>](https://www.gengjiawen.com)<br />[🐛](https://github.com/tabrindle/envinfo/issues?q=author%3Agengjiawen "Bug reports") [💻](https://github.com/tabrindle/envinfo/commits?author=gengjiawen "Code") [🤔](#ideas-gengjiawen "Ideas, Planning, & Feedback") [⚠️](https://github.com/tabrindle/envinfo/commits?author=gengjiawen "Tests") | | :---: | :---: | :---: | :---: | :---: | :---: | :---: | | [<img src="https://avatars3.githubusercontent.com/u/12520493?v=4" width="100px;"/><br /><sub><b>Zac Anger</b></sub>](https://zacanger.com)<br />[💻](https://github.com/tabrindle/envinfo/commits?author=zacanger "Code") [🐛](https://github.com/tabrindle/envinfo/issues?q=author%3Azacanger "Bug reports") | [<img src="https://avatars3.githubusercontent.com/u/497214?v=4" width="100px;"/><br /><sub><b>Ville Immonen</b></sub>](https://twitter.com/VilleImmonen)<br />[🐛](https://github.com/tabrindle/envinfo/issues?q=author%3Afson "Bug reports") [💻](https://github.com/tabrindle/envinfo/commits?author=fson "Code") | [<img src="https://avatars2.githubusercontent.com/u/27246?v=4" width="100px;"/><br /><sub><b>Olmo Maldonado</b></sub>](http://ibolmo.com)<br />[🐛](https://github.com/tabrindle/envinfo/issues?q=author%3Aibolmo "Bug reports") [💻](https://github.com/tabrindle/envinfo/commits?author=ibolmo "Code") | <!-- ALL-CONTRIBUTORS-LIST:END --> This project follows the [all-contributors](https://github.com/kentcdodds/all-contributors) specification. Contributions of any kind welcome! <p align="center"> <a href="https://github.com/inikulin/parse5"> <img src="https://raw.github.com/inikulin/parse5/master/media/logo.png" alt="parse5" /> </a> </p> <div align="center"> <h1>parse5</h1> <i><b>HTML parser and serializer.</b></i> </div> <br> <div align="center"> <code>npm install --save parse5</code> </div> <br> <p align="center"> 📖 <a href="https://github.com/inikulin/parse5/tree/master/packages/parse5/docs/index.md"><b>Documentation</b></a> 📖 </p> --- <p align="center"> <a href="https://github.com/inikulin/parse5/tree/master/docs/list-of-packages.md">List of parse5 toolset packages</a> </p> <p align="center"> <a href="https://github.com/inikulin/parse5">GitHub</a> </p> <p align="center"> <a href="http://astexplorer.net/#/1CHlCXc4n4">Online playground</a> </p> <p align="center"> <a href="https://github.com/inikulin/parse5/tree/master/docs/version-history.md">Version history</a> </p> # 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). # PostCSS Discard Overridden [PostCSS] plugin to discard overridden `@keyframes` or `@counter-style`. `@keyframes` or `@counter-style` will be overridden by those who share the same identifiers and appear later in stylesheets. So we can discard all of them except the last one. When defined inside a `@media` or `@supports` rule, `@keyframes` and `@counter-style` rules only override global rules in some of the client browsers so they need handled separately. This plugin has taken care of this and transforms the PostCss AST **safely**. [PostCSS]: https://github.com/postcss/postcss ```css @-webkit-keyframes fade-in { 0% { opacity: 0; } 100% { opacity: 0.8; } } @keyframes fade-in { 0% { opacity: 0; } 100% { opacity: 0.8; } } @media (max-width: 500px) { @-webkit-keyframes fade-in { 0% { opacity: 0; } 100% { opacity: 1; } } @keyframes fade-in { 0% { opacity: 0; } 100% { opacity: 1; } } @-webkit-keyframes fade-in { 0% { opacity: 0; } 100% { opacity: 0.8; } } @keyframes fade-in { 0% { opacity: 0; } 100% { opacity: 0.8; } } @supports (display: flex) { @-webkit-keyframes fade-in { 0% { opacity: 0; } 100% { opacity: 1; } } @keyframes fade-in { 0% { opacity: 0; } 100% { opacity: 1; } } } } @-webkit-keyframes fade-in { 0% { opacity: 0; } 100% { opacity: 1; } } @keyframes fade-in { 0% { opacity: 0; } 100% { opacity: 1; } } ``` ```css @media (max-width: 500px) { @-webkit-keyframes fade-in { 0% { opacity: 0; } 100% { opacity: 0.8; } } @keyframes fade-in { 0% { opacity: 0; } 100% { opacity: 0.8; } } @supports (display: flex) { @-webkit-keyframes fade-in { 0% { opacity: 0; } 100% { opacity: 1; } } @keyframes fade-in { 0% { opacity: 0; } 100% { opacity: 1; } } } } @-webkit-keyframes fade-in { 0% { opacity: 0; } 100% { opacity: 1; } } @keyframes fade-in { 0% { opacity: 0; } 100% { opacity: 1; } } ``` ## Usage See the [PostCSS documentation](https://github.com/postcss/postcss#usage) for examples for your environment. ## Contributors See [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md). pako - zlib port to javascript, very fast! ========================================== [![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) __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 v1.2.8 ported). 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 [@creatronix](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 partialy afferted by marshling (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. License ------- MIT # babel-runtime # 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._ # 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@^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. # 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' }, ] } ``` ### unicode-range The unicode-range CSS descriptor sets the specific range of characters to be used from a font defined by @font-face and made available for use on the current page (`unicode-range: U+0025-00FF`). Node-specific properties: - **value**: The "unicode-range" itself. ## 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:trysound@yandex.ru) # magic-string <p align="center"> <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> <a href="https://david-dm.org/Rich-Harris/magic-string"> <img src="https://david-dm.org/Rich-Harris/magic-string.svg" alt="dependency status"> </a> <a href="http://codecov.io/github/Rich-Harris/magic-string?branch=master"> <img src="http://codecov.io/github/Rich-Harris/magic-string/coverage.svg?branch=master" alt="Coverage via Codecov" /> </a> </p> 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 var MagicString = require( 'magic-string' ); var 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;' var map = s.generateMap({ source: 'source.js', file: 'converted.js.map', includeContent: true }); // generates a v3 sourcemap require( 'fs' ).writeFile( 'converted.js', s.toString() ); require( 'fs' ).writeFile( 'converted.js.map', map.toString() ); ``` You can pass an options argument: ```js var 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.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`. ## Bundling To concatenate several sources, use `MagicString.Bundle`: ```js var 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 var 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 var bundle = new MagicString.Bundle(); var source = new MagicString( someCode, { filename: 'foo.js' }); bundle.addSource( source ); ``` ## License MIT # [NWSAPI](http://dperini.github.io/nwsapi/) Fast CSS Selectors API Engine ![](https://img.shields.io/npm/v/nwsapi.svg?colorB=orange&style=flat) ![](https://img.shields.io/github/tag/dperini/nwsapi.svg?style=flat) ![](https://img.shields.io/npm/dw/nwsapi.svg?style=flat) ![](https://img.shields.io/github/issues/dperini/nwsapi.svg?style=flat) NWSAPI is the development progress of [NWMATCHER](https://github.com/dperini/nwmatcher) aiming at [Selectors Level 4](https://www.w3.org/TR/selectors-4/) conformance. It has been completely reworked to be easily extended and maintained. It is a right-to-left selector parser and compiler written in pure Javascript with no external dependencies. It was initially thought as a cross browser library to improve event delegation and web page scraping in various frameworks but it has become a popular replacement of the native CSS selection and matching functionality in newer browsers and headless environments. It uses [regular expressions](https://en.wikipedia.org/wiki/Regular_expression) to parse CSS selector strings and [metaprogramming](https://en.wikipedia.org/wiki/Metaprogramming) to transforms these selector strings into Javascript function resolvers. This process is executed only once for each selector string allowing memoization of the function resolvers and achieving unmatched performances. ## Installation To include NWSAPI in a standard web page: ```html <script type="text/javascript" src="nwsapi.js"></script> ``` To include NWSAPI in a standard web page and automatically replace the native QSA: ```html <script type="text/javascript" src="nwsapi.js" onload="NW.Dom.install()"></script> ``` To use NWSAPI with Node.js: ``` $ npm install nwsapi ``` NWSAPI currently supports browsers (as a global, `NW.Dom`) and headless environments (as a CommonJS module). ## Supported Selectors Here is a list of all the CSS2/CSS3/CSS4 [Supported selectors](https://github.com/dperini/nwsapi/wiki/CSS-supported-selectors). ## Features and Compliance You can read more about NWSAPI [features and compliance](https://github.com/dperini/nwsapi/wiki/Features-and-compliance) on the wiki. ## API ### DOM Selection #### `ancestor( selector, context, callback )` Returns a reference to the nearest ancestor element matching `selector`, starting at `context`. Returns `null` if no element is found. If `callback` is provided, it is invoked for the matched element. #### `first( selector, context, callback )` Returns a reference to the first element matching `selector`, starting at `context`. Returns `null` if no element matches. If `callback` is provided, it is invoked for the matched element. #### `match( selector, element, callback )` Returns `true` if `element` matches `selector`, starting at `context`; returns `false` otherwise. If `callback` is provided, it is invoked for the matched element. #### `select( selector, context, callback )` Returns an array of all the elements matching `selector`, starting at `context`; returns empty `Array` otherwise. If `callback` is provided, it is invoked for each matching element. ### DOM Helpers #### `byId( id, from )` Returns a reference to the first element with ID `id`, optionally filtered to descendants of the element `from`. #### `byTag( tag, from )` Returns an array of elements having the specified tag name `tag`, optionally filtered to descendants of the element `from`. #### `byClass( class, from )` Returns an array of elements having the specified class name `class`, optionally filtered to descendants of the element `from`. ### Engine Configuration #### `configure( options )` The following is the list of currently available configuration options, their default values and descriptions, they are boolean flags that can be set to `true` or `false`: * `IDS_DUPES`: true - true to allow using multiple elements having the same id, false to disallow * `LIVECACHE`: true - true for caching both results and resolvers, false for caching only resolvers * `MIXEDCASE`: true - true to match tag names case insensitive, false to match using case sensitive * `LOGERRORS`: true - true to print errors and warnings to the console, false to mute both of them ### Examples on extending the basic functionalities #### `configure( { <configuration-flag>: [ true | false ] } )` Disable logging errors/warnings to console, disallow duplicate ids. Example: ```js NW.Dom.configure( { LOGERRORS: false, IDS_DUPES: false } ); ``` NOTE: NW.Dom.configure() without parameters return the current configuration. #### `registerCombinator( symbol, resolver )` Registers a new symbol and its matching resolver in the combinators table. Example: ```js NW.Dom.registerCombinator( '^', 'e.parentElement' ); ``` #### `registerOperator( symbol, resolver )` Registers a new symbol and its matching resolver in the attribute operators table. Example: ```js NW.Dom.registerOperator( '!=', { p1: '^', p2: '$', p3: 'false' } ); ``` #### `registerSelector( name, rexp, func )` Registers a new selector, the matching RE and the resolver function, in the selectors table. Example: ```js NW.Dom.registerSelector('Controls', /^\:(control)(.*)/i, (function(global) { return function(match, source, mode, callback) { var status = true; source = 'if(/^(button|input|select|textarea)/i.test(e.nodeName)){' + source + '}'; return { 'source': source, 'status': status }; }; })(this)); ``` # defaults A simple one level options merge utility ## install `npm install defaults` ## use ```javascript var defaults = require('defaults'); var handle = function(options, fn) { options = defaults(options, { timeout: 100 }); setTimeout(function() { fn(options); }, options.timeout); } handle({ timeout: 1000 }, function() { // we're here 1000 ms later }); handle({ timeout: 10000 }, function() { // we're here 10s later }); ``` ## summary this module exports a function that takes 2 arguments: `options` and `defaults`. When called, it overrides all of `undefined` properties in `options` with the clones of properties defined in `defaults` Sidecases: if called with a falsy `options` value, options will be initialized to a new object before being merged onto. ## license [MIT](LICENSE) # 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._ # object.values <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 `Object.values` shim. Invoke its "shim" method to shim `Object.values` if it is unavailable or noncompliant. 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://tc39.github.io/ecma262/#sec-object.values). Most common usage: ```js var assert = require('assert'); var values = require('object.values'); var obj = { a: 1, b: 2, c: 3 }; var expected = [1, 2, 3]; if (typeof Symbol === 'function' && typeof Symbol() === 'symbol') { // for environments with Symbol support var sym = Symbol(); obj[sym] = 4; obj.d = sym; expected.push(sym); } assert.deepEqual(values(obj), expected); if (!Object.values) { values.shim(); } assert.deepEqual(Object.values(obj), expected); ``` ## Tests Simply clone the repo, `npm install`, and run `npm test` [package-url]: https://npmjs.com/package/object.values [npm-version-svg]: http://versionbadg.es/es-shims/Object.values.svg [travis-svg]: https://travis-ci.org/es-shims/Object.values.svg [travis-url]: https://travis-ci.org/es-shims/Object.values [deps-svg]: https://david-dm.org/es-shims/Object.values.svg [deps-url]: https://david-dm.org/es-shims/Object.values [dev-deps-svg]: https://david-dm.org/es-shims/Object.values/dev-status.svg [dev-deps-url]: https://david-dm.org/es-shims/Object.values#info=devDependencies [testling-svg]: https://ci.testling.com/es-shims/Object.values.png [testling-url]: https://ci.testling.com/es-shims/Object.values [npm-badge-png]: https://nodei.co/npm/object.values.png?downloads=true&stars=true [license-image]: http://img.shields.io/npm/l/object.values.svg [license-url]: LICENSE [downloads-image]: http://img.shields.io/npm/dm/object.values.svg [downloads-url]: http://npm-stat.com/charts.html?package=object.values # posthtml-parser [![npm version](https://badge.fury.io/js/posthtml-parser.svg)](http://badge.fury.io/js/posthtml-parser) [![Build Status](https://travis-ci.org/posthtml/posthtml-parser.svg?branch=master)](https://travis-ci.org/posthtml/posthtml-parser?branch=master) [![Coverage Status](https://coveralls.io/repos/posthtml/posthtml-parser/badge.svg?branch=master)](https://coveralls.io/r/posthtml/posthtml-parser?branch=master) Parse HTML/XML to [PostHTML AST](https://github.com/posthtml/posthtml-parser#posthtml-ast-format). More about [PostHTML](https://github.com/posthtml/posthtml#readme) ## Install [NPM](http://npmjs.com) install ``` $ npm install posthtml-parser ``` ## Usage #### Input HTML ```html <a class="animals" href="#"> <span class="animals__cat" style="background: url(cat.png)">Cat</span> </a> ``` ```js const parser = require('posthtml-parser') const fs = require('fs') const html = fs.readFileSync('path/to/input.html').toString() console.log(parser(html)) // Logs a PostHTML AST ``` #### input HTML ```html <a class="animals" href="#"> <span class="animals__cat" style="background: url(cat.png)">Cat</span> </a> ``` #### Result PostHTMLTree ```js [{ tag: 'a', attrs: { class: 'animals', href: '#' }, content: [ '\n ', { tag: 'span', attrs: { class: 'animals__cat', style: 'background: url(cat.png)' }, content: ['Cat'] }, '\n' ] }] ``` ## PostHTML AST Format Any parser being used with PostHTML should return a standard PostHTML [Abstract Syntax Tree](https://www.wikiwand.com/en/Abstract_syntax_tree) (AST). Fortunately, this is a very easy format to produce and understand. The AST is an array that can contain strings and objects. Any strings represent plain text content to be written to the output. Any objects represent HTML tags. Tag objects generally look something like this: ```js { tag: 'div', attrs: { class: 'foo' }, content: ['hello world!'] } ``` Tag objects can contain three keys. The `tag` key takes the name of the tag as the value. This can include custom tags. The optional `attrs` key takes an object with key/value pairs representing the attributes of the html tag. A boolean attribute has an empty string as its value. Finally, the optional `content` key takes an array as its value, which is a PostHTML AST. In this manner, the AST is a tree that should be walked recursively. ## Options ### `directives` Type: `Array` Default: `[{name: '!doctype', start: '<', end: '>'}]` Description: *Adds processing of custom directives. Note: The property ```name``` in custom directives can be ```String``` or ```RegExp``` type* ### `xmlMode` Type: `Boolean` Default: `false` Description: *Indicates whether special tags (`<script>` and `<style>`) should get special treatment and if "empty" tags (eg. `<br>`) can have children. If false, the content of special tags will be text only. For feeds and other XML content (documents that don't consist of HTML), set this to true.* ### `decodeEntities` Type: `Boolean` Default: `false` Description: *If set to true, entities within the document will be decoded.* ### `lowerCaseTags` Type: `Boolean` Default: `false` Description: *If set to true, all tags will be lowercased. If `xmlMode` is disabled.* ### `lowerCaseAttributeNames` Type: `Boolean` Default: `false` Description: *If set to true, all attribute names will be lowercased. This has noticeable impact on speed.* ### `recognizeCDATA` Type: `Boolean` Default: `false` Description: *If set to true, CDATA sections will be recognized as text even if the `xmlMode` option is not enabled. NOTE: If `xmlMode` is set to `true` then CDATA sections will always be recognized as text.* ### `recognizeSelfClosing` Type: `Boolean` Default: `false` Description: *If set to true, self-closing tags will trigger the `onclosetag` event even if `xmlMode` is not set to `true`. NOTE: If `xmlMode` is set to `true` then self-closing tags will always be recognized.* ## License [MIT](LICENSE) agent-base ========== ### Turn a function into an [`http.Agent`][http.Agent] instance [![Build Status](https://travis-ci.org/TooTallNate/node-agent-base.svg?branch=master)](https://travis-ci.org/TooTallNate/node-agent-base) This module provides an `http.Agent` generator. That is, you pass it an async callback function, and it returns a new `http.Agent` instance that will invoke the given callback function when sending outbound HTTP requests. #### Some subclasses: Here's some more interesting uses of `agent-base`. Send a pull request to list yours! * [`http-proxy-agent`][http-proxy-agent]: An HTTP(s) proxy `http.Agent` implementation for HTTP endpoints * [`https-proxy-agent`][https-proxy-agent]: An HTTP(s) proxy `http.Agent` implementation for HTTPS endpoints * [`pac-proxy-agent`][pac-proxy-agent]: A PAC file proxy `http.Agent` implementation for HTTP and HTTPS * [`socks-proxy-agent`][socks-proxy-agent]: A SOCKS (v4a) proxy `http.Agent` implementation for HTTP and HTTPS Installation ------------ Install with `npm`: ``` bash $ npm install agent-base ``` Example ------- Here's a minimal example that creates a new `net.Socket` connection to the server for every HTTP request (i.e. the equivalent of `agent: false` option): ```js var net = require('net'); var tls = require('tls'); var url = require('url'); var http = require('http'); var agent = require('agent-base'); var endpoint = 'http://nodejs.org/api/'; var parsed = url.parse(endpoint); // This is the important part! parsed.agent = agent(function (req, opts) { var socket; // `secureEndpoint` is true when using the https module if (opts.secureEndpoint) { socket = tls.connect(opts); } else { socket = net.connect(opts); } return socket; }); // Everything else works just like normal... http.get(parsed, function (res) { console.log('"response" event!', res.headers); res.pipe(process.stdout); }); ``` Returning a Promise or using an `async` function is also supported: ```js agent(async function (req, opts) { await sleep(1000); // etc… }); ``` Return another `http.Agent` instance to "pass through" the responsibility for that HTTP request to that agent: ```js agent(function (req, opts) { return opts.secureEndpoint ? https.globalAgent : http.globalAgent; }); ``` API --- ## Agent(Function callback[, Object options]) → [http.Agent][] Creates a base `http.Agent` that will execute the callback function `callback` for every HTTP request that it is used as the `agent` for. The callback function is responsible for creating a `stream.Duplex` instance of some kind that will be used as the underlying socket in the HTTP request. The `options` object accepts the following properties: * `timeout` - Number - Timeout for the `callback()` function in milliseconds. Defaults to Infinity (optional). The callback function should have the following signature: ### callback(http.ClientRequest req, Object options, Function cb) → undefined The ClientRequest `req` can be accessed to read request headers and and the path, etc. The `options` object contains the options passed to the `http.request()`/`https.request()` function call, and is formatted to be directly passed to `net.connect()`/`tls.connect()`, or however else you want a Socket to be created. Pass the created socket to the callback function `cb` once created, and the HTTP request will continue to proceed. If the `https` module is used to invoke the HTTP request, then the `secureEndpoint` property on `options` _will be set to `true`_. License ------- (The MIT License) Copyright (c) 2013 Nathan Rajlich &lt;nathan@tootallnate.net&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. [http-proxy-agent]: https://github.com/TooTallNate/node-http-proxy-agent [https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent [pac-proxy-agent]: https://github.com/TooTallNate/node-pac-proxy-agent [socks-proxy-agent]: https://github.com/TooTallNate/node-socks-proxy-agent [http.Agent]: https://nodejs.org/api/http.html#http_class_http_agent # vlq.js Convert integers to a Base64-encoded VLQ string, and vice versa. No dependencies, works in node.js or browsers, supports AMD. ## Why would you want to do that? Sourcemaps are the most likely use case. Mappings from original source to generated content are encoded as a sequence of VLQ strings. ## What is a VLQ string? A [variable-length quantity](http://en.wikipedia.org/wiki/Variable-length_quantity) is a compact way of encoding large integers in text (i.e. in situations where you can't transmit raw binary data). An integer represented as digits will always take up more space than the equivalent VLQ representation: | Integer | VLQ | | :------------------ | :--------- | | 0 | A | | 1 | C | | -1 | D | | 123 | 2H | | 123456789 | qxmvrH | | 123456789123456789 | gxvh6sB | ## Installation ```bash npm install vlq ``` ...or... ```bash bower install vlq ``` ...or grab the vlq.js file and include it with a `<script src='vlq.js'>` tag. ## Usage ### Encoding `vlq.encode` accepts an integer, or an array of integers, and returns a string: ```js vlq.encode( 123 ); // '2H'; vlq.encode([ 123, 456, 789 ]); // '2HwcqxB' ``` ### Decoding `vlq.decode` accepts a string and always returns an array: ```js vlq.decode( '2H' ); // [ 123 ] vlq.decode( '2HwcqxB' ); // [ 123, 456, 789 ] ``` ## Using vlq.js with sourcemaps [See here for an example of using vlq.js with sourcemaps.](https://github.com/Rich-Harris/vlq/tree/master/sourcemaps) ## Credits Adapted from [murzwin.com/base64vlq.html](http://murzwin.com/base64vlq.html) by Alexander Pavlov. ## License [MIT](LICENSE). # 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 # 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._ # <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/ # 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._ # 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) All the types of nodes in htmlparser2's DOM. # 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._ # fb-watchman `fb-watchman` is a filesystem watcher that uses the [Watchman](https://facebook.github.io/watchman/) file watching service from Facebook. Watchman provides file change notification services using very efficient recursive watches and also allows more advanced change matching and filesystem tree querying operations using [a powerful expression syntax](https://facebook.github.io/watchman/docs/file-query.html#expressions). ## Install You should [install Watchman]( https://facebook.github.io/watchman/docs/install.html) to make the most of this module. Then simply: ``` $ npm install fb-watchman ``` ## Key Concepts - Watchman recursively watches directories. - Each watched directory is called a `root`. - You must initiate a `watch` on a `root` using the `watch-project` command prior to subscribing to changes - Rather than separately watching many sibling directories, `watch-project` consolidates and re-uses existing watches relative to a project root (the location of your `.watchmanconfig` or source control repository root) - change notifications are relative to the project root ## How do I use it? [Read the NodeJS watchman documentation](https://facebook.github.io/watchman/docs/nodejs.html) 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` # DOMException This package implements the [`DOMException`](https://heycam.github.io/webidl/#idl-DOMException) class, from web browsers. It exists in service of [jsdom](https://github.com/tmpvar/jsdom) and related packages. Example usage: ```js const DOMException = require("domexception"); const e1 = new DOMException("Something went wrong", "BadThingsError"); console.assert(e1.name === "BadThingsError"); console.assert(e1.code === 0); const e2 = new DOMException("Another exciting error message", "NoModificationAllowedError"); console.assert(e2.name === "NoModificationAllowedError"); console.assert(e2.code === 7); console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10); ``` # 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._ # 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._ # 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._ [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. ### `.canonicalizedDomain()` ### `.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. ### `.removeAllCookies(cb(err))` Removes all cookies from the jar. This is a new backwards-compatible feature of `tough-cookie` version 2.5, so not all Stores will implement it efficiently. For Stores that do not implement `removeAllCookies`, the fallback is to call `removeCookie` after `getAllCookies`. If `getAllCookies` fails or isn't implemented in the Store, that error is returned. If one or more of the `removeCookie` calls fail, only the first error is returned. ### `.removeAllCookiesSync()` Sync version of `.removeAllCookies()` ## 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.removeAllCookies(cb(err))` _Optional_. Removes all cookies from the store. Pass an error if one or more cookies can't be removed. **Note**: New method as of `tough-cookie` version 2.5, so not all Stores will implement this, plus some stores may choose not to implement this. ### `store.getAllCookies(cb(err, cookies))` _Optional_. 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. **Note**: not all Stores can implement this due to technical limitations, so it is optional. ## 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. Supports serialization, `getAllCookies`, and `removeAllCookies`. ## 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: 'tough-cookie@1.x.y', // 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 BSD-3-Clause: ```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. ``` # unicode-trie A data structure for fast Unicode character metadata lookup, ported from ICU ## Background When implementing many Unicode algorithms such as text segmentation, normalization, bidi processing, etc., fast access to character metadata is crucial to good performance. There over a million code points in the Unicode standard, many of which produce the same result when looked up, so an array or hash table is not appropriate - those data structures are fast but would require a lot of memory. The data is generally grouped in ranges, so you could do a binary search, but that is not fast enough for some applications. The [International Components for Unicode](http://site.icu-project.org) (ICU) project came up with a data structure based on a [Trie](http://en.wikipedia.org/wiki/Trie) that provides fast access to Unicode metadata. The range data is precompiled to a serialized and flattened trie, which is then used at runtime to lookup the necessary data. According to my own tests, this is generally at least 50% faster than binary search, with not too much additional memory required. ## Installation npm install unicode-trie ## Building a Trie Unicode Tries are generally precompiled from data in the Unicode database for faster runtime performance. To build a Unicode Trie, use the `UnicodeTrieBuilder` class. ```coffeescript UnicodeTrieBuilder = require 'unicode-trie/builder' # create a trie t = new UnicodeTrieBuilder # optional parameters for default value, and error value # if not provided, both are set to 0 t = new UnicodeTrieBuilder 10, 999 # set individual values and ranges t.set 0x4567, 99 t.setRange 0x40, 0xe7, 0x1234 # you can lookup a value if you like t.get 0x4567 # => 99 # get a compiled trie (returns a UnicodeTrie object) trie = t.freeze() # write compressed trie to a binary file fs.writeFile 'data.trie', t.toBuffer() ``` ## Using a precompiled Trie Once you've built a precompiled trie, you can load it into the `UnicodeTrie` class, which is a readonly representation of the trie. From there, you can lookup values. ```coffeescript UnicodeTrie = require 'unicode-trie' fs = require 'fs' # load serialized trie from binary file data = fs.readFileSync 'data.trie' trie = new UnicodeTrie data # lookup a value trie.get 0x4567 # => 99 ``` ## License MIT # cosmiconfig [![Build Status](https://img.shields.io/travis/davidtheclark/cosmiconfig/master.svg?label=unix%20build)](https://travis-ci.org/davidtheclark/cosmiconfig) [![Build status](https://img.shields.io/appveyor/ci/davidtheclark/cosmiconfig/master.svg?label=windows%20build)](https://ci.appveyor.com/project/davidtheclark/cosmiconfig/branch/master) [![codecov](https://codecov.io/gh/davidtheclark/cosmiconfig/branch/master/graph/badge.svg)](https://codecov.io/gh/davidtheclark/cosmiconfig) Cosmiconfig searches for and loads configuration for your program. It features smart defaults based on conventional expectations in the JavaScript ecosystem. But it's also flexible enough to search wherever you'd like to search, and load whatever you'd like to load. By default, Cosmiconfig will start where you tell it to start and search up the directory tree for the following: - a `package.json` property - a JSON or YAML, extensionless "rc file" - an "rc file" with the extensions `.json`, `.yaml`, `.yml`, or `.js`. - a `.config.js` CommonJS module For example, if your module's name is "soursocks", cosmiconfig will search up the directory tree for configuration in the following places: - a `soursocks` property in `package.json` - a `.soursocksrc` file in JSON or YAML format - a `.soursocksrc.json` file - a `.soursocksrc.yaml`, `.soursocksrc.yml`, or `.soursocksrc.js` file - a `soursocks.config.js` file exporting a JS object Cosmiconfig continues to search up the directory tree, checking each of these places in each directory, until it finds some acceptable configuration (or hits the home directory). 👀 **Looking for the v4 docs?** v5 involves significant revisions to Cosmiconfig's API, allowing for much greater flexibility and clarifying some things. If you have trouble switching from v4 to v5, please file an issue. If you are still using v4, those v4 docs are available [in the `4.0.0` tag](https://github.com/davidtheclark/cosmiconfig/tree/4.0.0). ## Table of contents - [Installation](#installation) - [Usage](#usage) - [Result](#result) - [cosmiconfig()](#cosmiconfig-1) - [moduleName](#modulename) - [explorer.search()](#explorersearch) - [searchFrom](#searchfrom) - [explorer.searchSync()](#explorersearchsync) - [explorer.load()](#explorerload) - [explorer.loadSync()](#explorerloadsync) - [explorer.clearLoadCache()](#explorerclearloadcache) - [explorer.clearSearchCache()](#explorerclearsearchcache) - [explorer.clearCaches()](#explorerclearcaches) - [cosmiconfigOptions](#cosmiconfigoptions) - [searchPlaces](#searchplaces) - [loaders](#loaders) - [packageProp](#packageprop) - [stopDir](#stopdir) - [cache](#cache) - [transform](#transform) - [ignoreEmptySearchPlaces](#ignoreemptysearchplaces) - [Caching](#caching) - [Differences from rc](#differences-from-rc) - [Contributing & Development](#contributing--development) ## Installation ``` npm install cosmiconfig ``` Tested in Node 4+. ## Usage Create a Cosmiconfig explorer, then either `search` for or directly `load` a configuration file. ```js const cosmiconfig = require('cosmiconfig'); // ... const explorer = cosmiconfig(moduleName); // Search for a configuration by walking up directories. // See documentation for search, below. explorer.search() .then((result) => { // result.config is the parsed configuration object. // result.filepath is the path to the config file that was found. // result.isEmpty is true if there was nothing to parse in the config file. }) .catch((error) => { // Do something constructive. }); // Load a configuration directly when you know where it should be. // The result object is the same as for search. // See documentation for load, below. explorer.load(pathToConfig).then(..); // You can also search and load synchronously. const searchedFor = explorer.searchSync(); const loaded = explorer.loadSync(pathToConfig); ``` ## Result The result object you get from `search` or `load` has the following properties: - **config:** The parsed configuration object. `undefined` if the file is empty. - **filepath:** The path to the configuration file that was found. - **isEmpty:** `true` if the configuration file is empty. This property will not be present if the configuration file is not empty. ## cosmiconfig() ```js const explorer = cosmiconfig(moduleName[, cosmiconfigOptions]) ``` Creates a cosmiconfig instance ("explorer") configured according to the arguments, and initializes its caches. ### moduleName Type: `string`. **Required.** Your module name. This is used to create the default [`searchPlaces`] and [`packageProp`]. **[`cosmiconfigOptions`] are documented below.** You may not need them, and should first read about the functions you'll use. ## explorer.search() ```js explorer.search([searchFrom]).then(result => {..}) ``` Searches for a configuration file. Returns a Promise that resolves with a [result] or with `null`, if no configuration file is found. You can do the same thing synchronously with [`searchSync()`]. Let's say your module name is `goldengrahams` so you initialized with `const explorer = cosmiconfig('goldengrahams');`. Here's how your default [`search()`] will work: - Starting from `process.cwd()` (or some other directory defined by the `searchFrom` argument to [`search()`]), look for configuration objects in the following places: 1. A `goldengrahams` property in a `package.json` file. 2. A `.goldengrahamsrc` file with JSON or YAML syntax. 3. A `.goldengrahamsrc.json` file. 4. A `.goldengrahamsrc.yaml`, `.goldengrahamsrc.yml`, or `.goldengrahamsrc.js` file. 5. A `goldengrahams.config.js` JS file exporting the object. - If none of those searches reveal a configuration object, move up one directory level and try again. So the search continues in `./`, `../`, `../../`, `../../../`, etc., checking the same places in each directory. - Continue searching until arriving at your home directory (or some other directory defined by the cosmiconfig option [`stopDir`]). - If at any point a parseable configuration is found, the [`search()`] Promise resolves with its [result] \(or, with [`searchSync()`], the [result] is returned). - If no configuration object is found, the [`search()`] Promise resolves with `null` (or, with [`searchSync()`], `null` is returned). - If a configuration object is found *but is malformed* (causing a parsing error), the [`search()`] Promise rejects with that error (so you should `.catch()` it). (Or, with [`searchSync()`], the error is thrown.) **If you know exactly where your configuration file should be, you can use [`load()`], instead.** **The search process is highly customizable.** Use the cosmiconfig options [`searchPlaces`] and [`loaders`] to precisely define where you want to look for configurations and how you want to load them. ### searchFrom Type: `string`. Default: `process.cwd()`. A filename. [`search()`] will start its search here. If the value is a directory, that's where the search starts. If it's a file, the search starts in that file's directory. ## explorer.searchSync() ```js const result = explorer.searchSync([searchFrom]); ``` Synchronous version of [`search()`]. Returns a [result] or `null`. ## explorer.load() ```js explorer.load(loadPath).then(result => {..}) ``` Loads a configuration file. Returns a Promise that resolves with a [result] or rejects with an error (if the file does not exist or cannot be loaded). Use `load` if you already know where the configuration file is and you just need to load it. ```js explorer.load('load/this/file.json'); // Tries to load load/this/file.json. ``` If you load a `package.json` file, the result will be derived from whatever property is specified as your [`packageProp`]. ## explorer.loadSync() ```js const result = explorer.loadSync(loadPath); ``` Synchronous version of [`load()`]. Returns a [result]. ## explorer.clearLoadCache() Clears the cache used in [`load()`]. ## explorer.clearSearchCache() Clears the cache used in [`search()`]. ## explorer.clearCaches() Performs both [`clearLoadCache()`] and [`clearSearchCache()`]. ## cosmiconfigOptions Type: `Object`. Possible options are documented below. ### searchPlaces Type: `Array<string>`. Default: See below. An array of places that [`search()`] will check in each directory as it moves up the directory tree. Each place is relative to the directory being searched, and the places are checked in the specified order. **Default `searchPlaces`:** ```js [ 'package.json', `.${moduleName}rc`, `.${moduleName}rc.json`, `.${moduleName}rc.yaml`, `.${moduleName}rc.yml`, `.${moduleName}rc.js`, `${moduleName}.config.js`, ] ``` Create your own array to search more, fewer, or altogether different places. Every item in `searchPlaces` needs to have a loader in [`loaders`] that corresponds to its extension. (Common extensions are covered by default loaders.) Read more about [`loaders`] below. `package.json` is a special value: When it is included in `searchPlaces`, Cosmiconfig will always parse it as JSON and load a property within it, not the whole file. That property is defined with the [`packageProp`] option, and defaults to your module name. Examples, with a module named `porgy`: ```js // Disallow extensions on rc files: [ 'package.json', '.porgyrc', 'porgy.config.js' ] // ESLint searches for configuration in these places: [ '.eslintrc.js', '.eslintrc.yaml', '.eslintrc.yml', '.eslintrc.json', '.eslintrc', 'package.json' ] // Babel looks in fewer places: [ 'package.json', '.babelrc' ] // Maybe you want to look for a wide variety of JS flavors: [ 'porgy.config.js', 'porgy.config.mjs', 'porgy.config.ts', 'porgy.config.coffee' ] // ^^ You will need to designate custom loaders to tell // Cosmiconfig how to handle these special JS flavors. // Look within a .config/ subdirectory of every searched directory: [ 'package.json', '.porgyrc', '.config/.porgyrc', '.porgyrc.json', '.config/.porgyrc.json' ] ``` ### loaders Type: `Object`. Default: See below. An object that maps extensions to the loader functions responsible for loading and parsing files with those extensions. Cosmiconfig exposes its default loaders for `.js`, `.json`, and `.yaml` as `cosmiconfig.loadJs`, `cosmiconfig.loadJson`, and `cosmiconfig.loadYaml`, respectively. **Default `loaders`:** ```js { '.json': cosmiconfig.loadJson, '.yaml': cosmiconfig.loadYaml, '.yml': cosmiconfig.loadYaml, '.js': cosmiconfig.loadJs, noExt: cosmiconfig.loadYaml } ``` (YAML is a superset of JSON; which means YAML parsers can parse JSON; which is how extensionless files can be either YAML *or* JSON with only one parser.) **If you provide a `loaders` object, your object will be *merged* with the defaults.** So you can override one or two without having to override them all. **Keys in `loaders`** are extensions (starting with a period), or `noExt` to specify the loader for files *without* extensions, like `.soursocksrc`. **Values in `loaders`** are either a loader function (described below) or an object with `sync` and/or `async` properties, whose values are loader functions. **The most common use case for custom loaders value is to load extensionless `rc` files as strict JSON**, instead of JSON *or* YAML (the default). To accomplish that, provide the following `loaders` value: ```js { noExt: cosmiconfig.loadJson } ``` If you want to load files that are not handled by the loader functions Cosmiconfig exposes, you can write a custom loader function or use one from NPM if it exists. **Third-party loaders:** - [@endemolshinegroup/cosmiconfig-typescript-loader](https://github.com/EndemolShineGroup/cosmiconfig-typescript-loader) **Use cases for custom loader function:** - Allow configuration syntaxes that aren't handled by Cosmiconfig's defaults, like JSON5, INI, or XML. - Allow ES2015 modules from `.mjs` configuration files. - Parse JS files with Babel before deriving the configuration. **Custom loader functions** have the following signature: ```js // Sync (filepath: string, content: string) => Object | null // Async (filepath: string, content: string) => Object | null | Promise<Object | null> ``` Cosmiconfig reads the file when it checks whether the file exists, so it will provide you with both the file's path and its content. Do whatever you need to, and return either a configuration object or `null` (or, for async-only loaders, a Promise that resolves with one of those). `null` indicates that no real configuration was found and the search should continue. It's easiest if you make your custom loader function synchronous. Then it can be used regardless of whether you end up calling [`search()`] or [`searchSync()`], [`load()`] or [`loadSync()`]. If you want or need to provide an async-only loader, you can do so by making the value of `loaders` an object with an `async` property whose value is the async loader. You can also add a `sync` property to designate a sync loader, if you want to use both async and sync search and load functions. A few things to note: - If you use a custom loader, be aware of whether it's sync or async and how that aligned with your usage of sync or async search and load functions. - **Special JS syntax can also be handled by using a `require` hook**, because `cosmiconfig.loadJs` just uses `require`. Whether you use custom loaders or a `require` hook is up to you. Examples: ```js // Allow JSON5 syntax: { '.json': json5Loader } // Allow XML, and treat sync and async separately: { '.xml': { async: asyncXmlLoader, sync: syncXmlLoader } } // Allow a special configuration syntax of your own creation: { '.special': specialLoader } // Allow many flavors of JS, using custom loaders: { '.mjs': esmLoader, '.ts': typeScriptLoader, '.coffee': coffeeScriptLoader } // Allow many flavors of JS but rely on require hooks: { '.mjs': cosmiconfig.loadJs, '.ts': cosmiconfig.loadJs, '.coffee': cosmiconfig.loadJs } ``` ### packageProp Type: `string | Array<string>`. Default: `` `${moduleName}` ``. Name of the property in `package.json` to look for. Use a period-delimited string or an array of strings to describe a path to nested properties. For example, the value `'configs.myPackage'` or `['configs', 'myPackage']` will get you the `"myPackage"` value in a `package.json` like this: ```json { "configs": { "myPackage": {..} } } ``` If nested property names within the path include periods, you need to use an array of strings. For example, the value `['configs', 'foo.bar', 'baz']` will get you the `"baz"` value in a `package.json` like this: ```json { "configs": { "foo.bar": { "baz": {..} } } } ``` If a string includes period but corresponds to a top-level property name, it will not be interpreted as a period-delimited path. For example, the value `'one.two'` will get you the `"three"` value in a `package.json` like this: ```json { "one.two": "three", "one": { "two": "four" } } ``` ### stopDir Type: `string`. Default: Absolute path to your home directory. Directory where the search will stop. ### cache Type: `boolean`. Default: `true`. If `false`, no caches will be used. Read more about ["Caching"](#caching) below. ### transform Type: `(Result) => Promise<Result> | Result`. A function that transforms the parsed configuration. Receives the [result]. If using [`search()`] or [`load()`] \(which are async), the transform function can return the transformed result or return a Promise that resolves with the transformed result. If using [`searchSync()`] or [`loadSync()`], the function must be synchronous and return the transformed result. The reason you might use this option — instead of simply applying your transform function some other way — is that *the transformed result will be cached*. If your transformation involves additional filesystem I/O or other potentially slow processing, you can use this option to avoid repeating those steps every time a given configuration is searched or loaded. ### ignoreEmptySearchPlaces Type: `boolean`. Default: `true`. By default, if [`search()`] encounters an empty file (containing nothing but whitespace) in one of the [`searchPlaces`], it will ignore the empty file and move on. If you'd like to load empty configuration files, instead, set this option to `false`. Why might you want to load empty configuration files? If you want to throw an error, or if an empty configuration file means something to your program. ## Caching As of v2, cosmiconfig uses caching to reduce the need for repetitious reading of the filesystem or expensive transforms. Every new cosmiconfig instance (created with `cosmiconfig()`) has its own caches. To avoid or work around caching, you can do the following: - Set the `cosmiconfig` option [`cache`] to `false`. - Use the cache-clearing methods [`clearLoadCache()`], [`clearSearchCache()`], and [`clearCaches()`]. - Create separate instances of cosmiconfig (separate "explorers"). ## Differences from [rc](https://github.com/dominictarr/rc) [rc](https://github.com/dominictarr/rc) serves its focused purpose well. cosmiconfig differs in a few key ways — making it more useful for some projects, less useful for others: - Looks for configuration in some different places: in a `package.json` property, an rc file, a `.config.js` file, and rc files with extensions. - Built-in support for JSON, YAML, and CommonJS formats. - Stops at the first configuration found, instead of finding all that can be found up the directory tree and merging them automatically. - Options. - Asynchronous by default (though can be run synchronously). ## Contributing & Development Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms. And please do participate! [result]: #result [`load()`]: #explorerload [`loadsync()`]: #explorerloadsync [`search()`]: #explorersearch [`searchsync()`]: #explorersearchsync [`clearloadcache()`]: #explorerclearloadcache [`clearsearchcache()`]: #explorerclearsearchcache [`clearcaches()`]: #explorerclearcaches [`packageprop`]: #packageprop [`cache`]: #cache [`stopdir`]: #stopdir [`searchplaces`]: #searchplaces [`loaders`]: #loaders [`cosmiconfigoptions`]: #cosmiconfigoptions # rgb-regex [![Build Status](https://secure.travis-ci.org/regexps/rgb-regex.png?branch=master)](https://travis-ci.org/regexps/rgb-regex) Regex for RGB color strings. ## Installation ```bash npm install --save rgb-regex ``` ## Usage ```javascript var rgbRegex = require('rgb-regex'); rgbRegex({ exact: true }).test('rgb(12, 34, 56)'); // => true rgbRegex({ exact: true }).test('unicorns'); // -> false rgbRegex({ exact: true }).test('rgb(,,)'); // => false rgbRegex().exec('rgb(12, 34, 56)'); // => [ // '12', // '34', // '56', // index: 0, // input: 'rgb(12,34,56)' // ] 'rgb(12, 34, 56) cats and dogs'.match(rgbRegex()); // = ['rgb(12, 34, 56)'] ``` ## License MIT ## 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. Create new Pull Request Crafted with <3 by John Otander ([@4lpine](https://twitter.com/4lpine)). *** > This package was initially generated with [yeoman](http://yeoman.io) and the [p generator](https://github.com/johnotander/generator-p.git). # 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/micromatch/is-glob) | [homepage](https://github.com/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 bet") * [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.") * [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** | | --- | --- | | 102 | [jonschlinkert](https://github.com/jonschlinkert) | | 3 | [aretecode](https://github.com/aretecode) | | 2 | [miguelmota](https://github.com/miguelmota) | | 1 | [doowb](https://github.com/doowb) | | 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 | [tunnckoCore](https://github.com/tunnckoCore) | | 1 | [xiaofen9](https://github.com/xiaofen9) | ### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) ### License Copyright © 2020, [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 January 16, 2020._ Like `chown -R`. Takes the same arguments as `fs.chown()` # 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) # 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 # 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 `node@0.10.x`. ## License Form-Data is released under the [MIT](License) license. # 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._ # 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. # 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. # htmlparser2 [![NPM version](http://img.shields.io/npm/v/htmlparser2.svg?style=flat)](https://npmjs.org/package/htmlparser2) [![Downloads](https://img.shields.io/npm/dm/htmlparser2.svg?style=flat)](https://npmjs.org/package/htmlparser2) [![Build Status](http://img.shields.io/travis/fb55/htmlparser2/master.svg?style=flat)](http://travis-ci.org/fb55/htmlparser2) [![Coverage](http://img.shields.io/coveralls/fb55/htmlparser2.svg?style=flat)](https://coveralls.io/r/fb55/htmlparser2) A forgiving HTML/XML/RSS parser. The parser can handle streams and provides a callback interface. ## Installation npm install htmlparser2 A live demo of htmlparser2 is available [here](https://astexplorer.net/#/2AmVrGuGVJ). ## Usage ```javascript var htmlparser = require("htmlparser2"); var parser = new htmlparser.Parser({ onopentag: function(name, attribs){ if(name === "script" && attribs.type === "text/javascript"){ console.log("JS! Hooray!"); } }, ontext: function(text){ console.log("-->", text); }, onclosetag: function(tagname){ if(tagname === "script"){ console.log("That's it?!"); } } }, {decodeEntities: true}); parser.write("Xyz <script type='text/javascript'>var foo = '<<bar>>';</ script>"); parser.end(); ``` Output (simplified): ``` --> Xyz JS! Hooray! --> var foo = '<<bar>>'; That's it?! ``` ## Documentation Read more about the parser and its options in the [wiki](https://github.com/fb55/htmlparser2/wiki/Parser-options). ## Get a DOM The `DomHandler` (known as `DefaultHandler` in the original `htmlparser` module) produces a DOM (document object model) that can be manipulated using the [`DomUtils`](https://github.com/fb55/DomUtils) helper. The `DomHandler`, while still bundled with this module, was moved to its [own module](https://github.com/fb55/domhandler). Have a look at it for further information. ## Parsing RSS/RDF/Atom Feeds ```javascript new htmlparser.FeedHandler(function(<error> error, <object> feed){ ... }); ``` Note: While the provided feed handler works for most feeds, you might want to use [danmactough/node-feedparser](https://github.com/danmactough/node-feedparser), which is much better tested and actively maintained. ## Performance After having some artificial benchmarks for some time, __@AndreasMadsen__ published his [`htmlparser-benchmark`](https://github.com/AndreasMadsen/htmlparser-benchmark), which benchmarks HTML parses based on real-world websites. At the time of writing, the latest versions of all supported parsers show the following performance characteristics on [Travis CI](https://travis-ci.org/AndreasMadsen/htmlparser-benchmark/builds/10805007) (please note that Travis doesn't guarantee equal conditions for all tests): ``` gumbo-parser : 34.9208 ms/file ± 21.4238 html-parser : 24.8224 ms/file ± 15.8703 html5 : 419.597 ms/file ± 264.265 htmlparser : 60.0722 ms/file ± 384.844 htmlparser2-dom: 12.0749 ms/file ± 6.49474 htmlparser2 : 7.49130 ms/file ± 5.74368 hubbub : 30.4980 ms/file ± 16.4682 libxmljs : 14.1338 ms/file ± 18.6541 parse5 : 22.0439 ms/file ± 15.3743 sax : 49.6513 ms/file ± 26.6032 ``` ## How does this module differ from [node-htmlparser](https://github.com/tautologistics/node-htmlparser)? This is a fork of the `htmlparser` module. The main difference is that this is intended to be used only with node (it runs on other platforms using [browserify](https://github.com/substack/node-browserify)). `htmlparser2` was rewritten multiple times and, while it maintains an API that's compatible with `htmlparser` in most cases, the projects don't share any code anymore. The parser now provides a callback interface close to [sax.js](https://github.com/isaacs/sax-js) (originally targeted at [readabilitySAX](https://github.com/fb55/readabilitysax)). As a result, old handlers won't work anymore. The `DefaultHandler` and the `RssHandler` were renamed to clarify their purpose (to `DomHandler` and `FeedHandler`). The old names are still available when requiring `htmlparser2`, your code should work as expected. # w3c-hr-time This module implements the W3C [High Resolution Time Level 2][HR-TIME] specification. It provides exactly three exports: - `Performance` class - `getGlobalMonotonicClockMS(): number` - `clockIsAccurate: boolean` In all APIs, a "high-resolution timestamp" means a number in milliseconds that may have a fractional part, if the system clock is accurate enough (see "Clock accuracy" section below). It is identical to the [`DOMHighResTimeStamp`][] type in the High Resolution Time spec. Portability is paramount to this module. It uses only APIs exposed from Node.js core like `Date.now()` and `process.hrtime()` and does not use or require any native modules. It also employs the [browser-process-hrtime][] module for graceful degrades for platforms that do not have `process.hrtime()` (such as browsers). ## `Performance` class ```js const { Performance } = require("w3c-hr-time"); const performance = new Performance(); console.log(performance.timeOrigin); // Prints a number close to Date.now() but that may have fractional parts, like // 1514888563819.351. console.log(new Date(performance.timeOrigin)); // Prints a date close to new Date(), like 2018-01-02T10:22:43.819Z. setTimeout(() => { console.log(performance.now()); // Prints a number close to 5000, like 5008.023059. }, 5000); ``` Perhaps the most interesting export is the [`Performance`][] class. By constructing the class, you can get an instance quite similar to the `window.performance` object in browsers. Specifically, the following APIs are implemented: * [`performance.now(): number`][`Performance#now()`] returns the high-resolution duration since the construction of the `Performance` object. * [`performance.timeOrigin: number`][`Performance#timeOrigin`] is a high-resolution timestamp of the `Performance` object's construction, expressed in [Unix time][]. * [`performance.toJSON(): object`][`Performance#toJSON()`] returns an object with `timeOrigin` property set to the corresponding value of this object. This allows serializing the `Performance` object with `JSON.stringify()`. In browsers, the returned object may contain additional properties such as `navigation` and `timing`. However, those properties are specific to browser navigation and are unsuitable for a Node.js implementation. Furthermore, they are specified not in the High Resolution Time spec but in [Navigation Timing][NAVIGATION-TIMING], and are thereby outside the scope of this module. ### Limitations This module does not aim for full [Web IDL][WEBIDL] conformance, so things like `performance.toJSON.call({})` will not throw `TypeError`s like it does in browsers. If you need full Web IDL conformance, you may be interested in the [webidl2js][] module. The `Performance` class provided also does not have `mark()`, `measure()`, `getEntries()`, and such functions. They are specified in other specs than High Resolution Timing, such as [User Timing][USER-TIMING] (marks and measures) and [Performance Timeline][PERFORMANCE-TIMELINE] (entries management). Those specs extend the definition of the `Performance` class defined in High Resolution Timing, and to implement those specs you can extend the `Performance` class exported by this module. Due to the limitations of the APIs exposed through Node.js, the construction of a `Performance` object may take up to 1 millisecond to gather information for high-resolution `timeOrigin`. ## Global monotonic clock The High Resolution Time spec defines a [global monotonic clock][] that is "shared by time origin's *[sic]*, is monotonically increasing and not subject to system clock adjustments or system clock skew, and whose reference point is the Unix time." This module exports a function `getGlobalMonotonicClockMS()` that is the basis of all timing functions used my this module when a monotonic time is required. It returns a high-resolution timestamp whose zero value is at some arbitrary point in the past. (For the current high-resolution timestamp based on the Unix epoch, use `new Performance().timeOrigin` instead.) ```js const { getGlobalMonotonicClockMS } = require("w3c-hr-time"); const start = getGlobalMonotonicClockMS(); console.log(start); // Prints a millisecond timestamp based on an arbitrary point in the past, like // 280249733.012151. setTimeout(() => { console.log(getGlobalMonotonicClockMS() - a); // Prints a number close to 5000, like 5006.156536. }, 5000); ``` Unlike other functions that return only integer timestamps if the system clock does not provide enough resolution, this function may still return timestamps with fractional parts on those systems with less accurate clocks. See "Clock accuracy" section below for more information. ## Clock accuracy The High Resolution Time spec [states][HR-TIME §4] that > A [`DOMHighResTimeStamp`][] *SHOULD* represent a time in milliseconds accurate to 5 microseconds - see [8. Privacy and Security][HR-TIME §8]. > > If the User Agent is unable to provide a time value accurate to 5 microseconds due to hardware or software constraints, the User Agent can represent a [`DOMHighResTimeStamp`][] as a time in milliseconds accurate to a millisecond. This module implements this suggestion faithfully. It executes a test at `require()`-time to determine if the system clock (both `Date.now()` and `process.hrtime()`) is accurate enough to 5 microseconds. The result of this test can be accessed through the exported `clockIsAccurate` boolean value. ```js const { Performance, clockIsAccurate } = require("w3c-hr-time"); const performance = new Performance(); if (!clockIsAccurate) { console.assert(Number.isInteger(performance.timeOrigin)); console.assert(Number.isInteger(performance.now())); } ``` If `clockIsAccurate` is false, `performance.timeOrigin` and `performance.now()` are always rounded to millisecond accuracy. `getGlobalMonotonicClockMS()` however is exempt from this requirement due to its best-effort nature, and the fact that it is not an API exposed by the High Resolution Time spec. ## Clock drift [Clock drift][clock drift] can be observed through system or user clock adjustments -- that is, the speed at which `Date.now()` changes may be faster or slower than real time if there is a pending adjustment to the system clock, for example through NTP synchronizing. In the spec, the [global monotonic clock][] is defined to be immune to such drifts. Correspondingly, the APIs exposed through this module that are defined using the global monotonic clock such as `performance.now()` and `getGlobalMonotonicClockMS()` are also guaranteed to reflect real time. For example, if `performance.now()` returns 1000, it is guaranteed that the time of this call is exactly one second since the construction of the `Performance` object. But the difference in `Date.now()`'s value from the construction of the `Performance` object to when `performance.now()` returns 1000 may not be exactly 1000. You may also see `performance.now() - Date.now()` diverge over time as a result of clock drifts. On the other hand, `performance.timeOrigin` returns the *[Unix time][]* at which the `Performance` object is constructed and relies on the current time exposed through `Date.now()`. That means that it is susceptible to clock drifts that has occurred before the `Performance` object was constructed. ## Supporting w3c-hr-time The jsdom project (including w3c-hr-time) 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 w3c-hr-time](https://tidelift.com/subscription/pkg/npm-w3c-hr-time?utm_source=npm-w3c-hr-time&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. ## License This software is licensed under the MIT license. See LICENSE.md file for more detail. [HR-TIME]: https://w3c.github.io/hr-time/ [NAVIGATION-TIMING]: https://w3c.github.io/navigation-timing/ [PERFORMANCE-TIMELINE]: https://w3c.github.io/performance-timeline/ [USER-TIMING]: https://w3c.github.io/user-timing/ [WEBIDL]: https://heycam.github.io/webidl/ [HR-TIME §4]: https://w3c.github.io/hr-time/#dom-domhighrestimestamp [HR-TIME §8]: https://w3c.github.io/hr-time/#privacy-security [`DOMHighResTimeStamp`]: https://w3c.github.io/hr-time/#dom-domhighrestimestamp [`Performance`]: https://w3c.github.io/hr-time/#dfn-performance [`Performance#now()`]: https://w3c.github.io/hr-time/#dom-performance-now [`Performance#timeOrigin`]: https://w3c.github.io/hr-time/#dom-performance-timeorigin [`Performance#toJSON()`]: https://w3c.github.io/hr-time/#dom-performance-tojson [browser-process-hrtime]: https://www.npmjs.com/package/browser-process-hrtime [clock drift]: https://en.wikipedia.org/wiki/Clock_drift [global monotonic clock]: https://w3c.github.io/hr-time/#dfn-global-monotonic-clock [Unix time]: https://en.wikipedia.org/wiki/Unix_time [webidl2js]: https://github.com/jsdom/webidl2js 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 `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value components are invalid (`9999999999999999.4.7.4` is likely invalid). 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. # 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 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. # Deprecated! As of Feb 11th 2020, request is fully deprecated. No new changes are expected land. In fact, none have landed for some time. For more information about why request is deprecated and possible alternatives refer to [this issue](https://github.com/request/request/issues/3142). # 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 const request = require('request'); request('http://www.google.com', function (error, response, body) { console.error('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.error(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') { const 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 const 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) Also, [`util.promisify`](https://nodejs.org/api/util.html#util_util_promisify_original), which is available from Node.js v8.0 can be used to convert a regular function that takes a callback to return a promise instead. [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 const 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 const r = request.post('http://service.com/upload', function optionalCallback(err, httpResponse, body) {...}) const 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 const username = 'username', password = 'password', url = 'http://' + username + ':' + password + '@some.server.com'; request({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 const request = require('request'); const options = { url: 'https://api.github.com/repos/request/request', headers: { 'User-Agent': 'request' } }; function callback(error, response, body) { if (!error && response.statusCode == 200) { const 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 const 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 const req_data = qs.parse(body) const 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 const 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 const 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 const 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'); const 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 const fs = require('fs') , path = require('path') , certFile = path.resolve(__dirname, 'ssl/client.crt') , keyFile = path.resolve(__dirname, 'ssl/client.key') , request = require('request'); const 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') } }); ``` The `ca` value can be an array of certificates, in the event you have a private or internal corporate public-key infrastructure hierarchy. For example, if you want to connect to https://api.some-server.com which presents a key chain consisting of: 1. its own public key, which is signed by: 2. an intermediate "Corp Issuing Server", that is in turn signed by: 3. a root CA "Corp Root CA"; you can configure your request as follows: ```js request.get({ url: 'https://api.some-server.com/', agentOptions: { ca: [ fs.readFileSync('Corp Issuing Server.pem'), fs.readFileSync('Corp Root CA.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 const 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 number of milliseconds, controls two timeouts. - **Read timeout**: Time to wait for a server to send response headers (and start the response body) before aborting the request. - **Connection timeout**: Sets the socket to timeout after `timeout` milliseconds of inactivity. Note that increasing the timeout beyond the OS-wide TCP connection timeout will not have any effect ([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-12) 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 const 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 const 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() ``` ### response.caseless.get('header-name') Function that returns the specified response header field using a [case-insensitive match](https://tools.ietf.org/html/rfc7230#section-3.2) ```js request('http://www.google.com', function (error, response, body) { // print the Content-Type header even if the server returned it as 'content-type' (lowercase) console.log('Content-Type is:', response.caseless.get('Content-Type')); }); ``` [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 const 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 const 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 const 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 const j = request.jar() const request = request.defaults({jar:j}) request('http://www.google.com', function () { request('http://images.google.com') }) ``` OR ```js const j = request.jar(); const cookie = request.cookie('key1=value1'); const 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 const FileCookieStore = require('tough-cookie-filestore'); // NOTE - currently the 'cookies.json' file must already exist! const 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#api) for details. To inspect your cookie jar after a request: ```js const j = request.jar() request({url: 'http://www.google.com', jar: j}, function () { const cookie_string = j.getCookieString(url); // "key1=value1; key2=value2; ..." const cookies = j.getCookies(url); // [{key: 'key1', value: 'value1', domain: "www.google.com", ...}, ...] }) ``` [back to top](#table-of-contents) # 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 symbol-tree =========== [![Travis CI Build Status](https://api.travis-ci.org/jsdom/js-symbol-tree.svg?branch=master)](https://travis-ci.org/jsdom/js-symbol-tree) [![Coverage Status](https://coveralls.io/repos/github/jsdom/js-symbol-tree/badge.svg?branch=master)](https://coveralls.io/github/jsdom/js-symbol-tree?branch=master) Turn any collection of objects into its own efficient tree or linked list using `Symbol`. This library has been designed to provide an efficient backing data structure for DOM trees. You can also use this library as an efficient linked list. Any meta data is stored on your objects directly, which ensures any kind of insertion or deletion is performed in constant time. Because an ES6 `Symbol` is used, the meta data does not interfere with your object in any way. Node.js 4+, io.js and modern browsers are supported. Example ------- A linked list: ```javascript const SymbolTree = require('symbol-tree'); const tree = new SymbolTree(); let a = {foo: 'bar'}; // or `new Whatever()` let b = {foo: 'baz'}; let c = {foo: 'qux'}; tree.insertBefore(b, a); // insert a before b tree.insertAfter(b, c); // insert c after b console.log(tree.nextSibling(a) === b); console.log(tree.nextSibling(b) === c); console.log(tree.previousSibling(c) === b); tree.remove(b); console.log(tree.nextSibling(a) === c); ``` A tree: ```javascript const SymbolTree = require('symbol-tree'); const tree = new SymbolTree(); let parent = {}; let a = {}; let b = {}; let c = {}; tree.prependChild(parent, a); // insert a as the first child tree.appendChild(parent,c ); // insert c as the last child tree.insertAfter(a, b); // insert b after a, it now has the same parent as a console.log(tree.firstChild(parent) === a); console.log(tree.nextSibling(tree.firstChild(parent)) === b); console.log(tree.lastChild(parent) === c); let grandparent = {}; tree.prependChild(grandparent, parent); console.log(tree.firstChild(tree.firstChild(grandparent)) === a); ``` See [api.md](api.md) for more documentation. Testing ------- Make sure you install the dependencies first: npm install You can now run the unit tests by executing: npm test The line and branch coverage should be 100%. API Documentation ----------------- <a name="module_symbol-tree"></a> ## symbol-tree **Author**: Joris van der Wel <joris@jorisvanderwel.com> * [symbol-tree](#module_symbol-tree) * [SymbolTree](#exp_module_symbol-tree--SymbolTree) ⏏ * [new SymbolTree([description])](#new_module_symbol-tree--SymbolTree_new) * [.initialize(object)](#module_symbol-tree--SymbolTree+initialize) ⇒ <code>Object</code> * [.hasChildren(object)](#module_symbol-tree--SymbolTree+hasChildren) ⇒ <code>Boolean</code> * [.firstChild(object)](#module_symbol-tree--SymbolTree+firstChild) ⇒ <code>Object</code> * [.lastChild(object)](#module_symbol-tree--SymbolTree+lastChild) ⇒ <code>Object</code> * [.previousSibling(object)](#module_symbol-tree--SymbolTree+previousSibling) ⇒ <code>Object</code> * [.nextSibling(object)](#module_symbol-tree--SymbolTree+nextSibling) ⇒ <code>Object</code> * [.parent(object)](#module_symbol-tree--SymbolTree+parent) ⇒ <code>Object</code> * [.lastInclusiveDescendant(object)](#module_symbol-tree--SymbolTree+lastInclusiveDescendant) ⇒ <code>Object</code> * [.preceding(object, [options])](#module_symbol-tree--SymbolTree+preceding) ⇒ <code>Object</code> * [.following(object, [options])](#module_symbol-tree--SymbolTree+following) ⇒ <code>Object</code> * [.childrenToArray(parent, [options])](#module_symbol-tree--SymbolTree+childrenToArray) ⇒ <code>Array.&lt;Object&gt;</code> * [.ancestorsToArray(object, [options])](#module_symbol-tree--SymbolTree+ancestorsToArray) ⇒ <code>Array.&lt;Object&gt;</code> * [.treeToArray(root, [options])](#module_symbol-tree--SymbolTree+treeToArray) ⇒ <code>Array.&lt;Object&gt;</code> * [.childrenIterator(parent, [options])](#module_symbol-tree--SymbolTree+childrenIterator) ⇒ <code>Object</code> * [.previousSiblingsIterator(object)](#module_symbol-tree--SymbolTree+previousSiblingsIterator) ⇒ <code>Object</code> * [.nextSiblingsIterator(object)](#module_symbol-tree--SymbolTree+nextSiblingsIterator) ⇒ <code>Object</code> * [.ancestorsIterator(object)](#module_symbol-tree--SymbolTree+ancestorsIterator) ⇒ <code>Object</code> * [.treeIterator(root, options)](#module_symbol-tree--SymbolTree+treeIterator) ⇒ <code>Object</code> * [.index(child)](#module_symbol-tree--SymbolTree+index) ⇒ <code>Number</code> * [.childrenCount(parent)](#module_symbol-tree--SymbolTree+childrenCount) ⇒ <code>Number</code> * [.compareTreePosition(left, right)](#module_symbol-tree--SymbolTree+compareTreePosition) ⇒ <code>Number</code> * [.remove(removeObject)](#module_symbol-tree--SymbolTree+remove) ⇒ <code>Object</code> * [.insertBefore(referenceObject, newObject)](#module_symbol-tree--SymbolTree+insertBefore) ⇒ <code>Object</code> * [.insertAfter(referenceObject, newObject)](#module_symbol-tree--SymbolTree+insertAfter) ⇒ <code>Object</code> * [.prependChild(referenceObject, newObject)](#module_symbol-tree--SymbolTree+prependChild) ⇒ <code>Object</code> * [.appendChild(referenceObject, newObject)](#module_symbol-tree--SymbolTree+appendChild) ⇒ <code>Object</code> <a name="exp_module_symbol-tree--SymbolTree"></a> ### SymbolTree ⏏ **Kind**: Exported class <a name="new_module_symbol-tree--SymbolTree_new"></a> #### new SymbolTree([description]) | Param | Type | Default | Description | | --- | --- | --- | --- | | [description] | <code>string</code> | <code>&quot;&#x27;SymbolTree data&#x27;&quot;</code> | Description used for the Symbol | <a name="module_symbol-tree--SymbolTree+initialize"></a> #### symbolTree.initialize(object) ⇒ <code>Object</code> You can use this function to (optionally) initialize an object right after its creation, to take advantage of V8's fast properties. Also useful if you would like to freeze your object. `O(1)` **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) **Returns**: <code>Object</code> - object | Param | Type | | --- | --- | | object | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+hasChildren"></a> #### symbolTree.hasChildren(object) ⇒ <code>Boolean</code> Returns `true` if the object has any children. Otherwise it returns `false`. * `O(1)` **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) | Param | Type | | --- | --- | | object | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+firstChild"></a> #### symbolTree.firstChild(object) ⇒ <code>Object</code> Returns the first child of the given object. * `O(1)` **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) | Param | Type | | --- | --- | | object | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+lastChild"></a> #### symbolTree.lastChild(object) ⇒ <code>Object</code> Returns the last child of the given object. * `O(1)` **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) | Param | Type | | --- | --- | | object | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+previousSibling"></a> #### symbolTree.previousSibling(object) ⇒ <code>Object</code> Returns the previous sibling of the given object. * `O(1)` **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) | Param | Type | | --- | --- | | object | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+nextSibling"></a> #### symbolTree.nextSibling(object) ⇒ <code>Object</code> Returns the next sibling of the given object. * `O(1)` **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) | Param | Type | | --- | --- | | object | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+parent"></a> #### symbolTree.parent(object) ⇒ <code>Object</code> Return the parent of the given object. * `O(1)` **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) | Param | Type | | --- | --- | | object | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+lastInclusiveDescendant"></a> #### symbolTree.lastInclusiveDescendant(object) ⇒ <code>Object</code> Find the inclusive descendant that is last in tree order of the given object. * `O(n)` (worst case) where `n` is the depth of the subtree of `object` **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) | Param | Type | | --- | --- | | object | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+preceding"></a> #### symbolTree.preceding(object, [options]) ⇒ <code>Object</code> Find the preceding object (A) of the given object (B). An object A is preceding an object B if A and B are in the same tree and A comes before B in tree order. * `O(n)` (worst case) * `O(1)` (amortized when walking the entire tree) **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) | Param | Type | Description | | --- | --- | --- | | object | <code>Object</code> | | | [options] | <code>Object</code> | | | [options.root] | <code>Object</code> | If set, `root` must be an inclusive ancestor of the return value (or else null is returned). This check _assumes_ that `root` is also an inclusive ancestor of the given `object` | <a name="module_symbol-tree--SymbolTree+following"></a> #### symbolTree.following(object, [options]) ⇒ <code>Object</code> Find the following object (A) of the given object (B). An object A is following an object B if A and B are in the same tree and A comes after B in tree order. * `O(n)` (worst case) where `n` is the amount of objects in the entire tree * `O(1)` (amortized when walking the entire tree) **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) | Param | Type | Default | Description | | --- | --- | --- | --- | | object | <code>Object</code> | | | | [options] | <code>Object</code> | | | | [options.root] | <code>Object</code> | | If set, `root` must be an inclusive ancestor of the return value (or else null is returned). This check _assumes_ that `root` is also an inclusive ancestor of the given `object` | | [options.skipChildren] | <code>Boolean</code> | <code>false</code> | If set, ignore the children of `object` | <a name="module_symbol-tree--SymbolTree+childrenToArray"></a> #### symbolTree.childrenToArray(parent, [options]) ⇒ <code>Array.&lt;Object&gt;</code> Append all children of the given object to an array. * `O(n)` where `n` is the amount of children of the given `parent` **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) | Param | Type | Default | Description | | --- | --- | --- | --- | | parent | <code>Object</code> | | | | [options] | <code>Object</code> | | | | [options.array] | <code>Array.&lt;Object&gt;</code> | <code>[]</code> | | | [options.filter] | <code>function</code> | | Function to test each object before it is added to the array. Invoked with arguments (object). Should return `true` if an object is to be included. | | [options.thisArg] | <code>\*</code> | | Value to use as `this` when executing `filter`. | <a name="module_symbol-tree--SymbolTree+ancestorsToArray"></a> #### symbolTree.ancestorsToArray(object, [options]) ⇒ <code>Array.&lt;Object&gt;</code> Append all inclusive ancestors of the given object to an array. * `O(n)` where `n` is the amount of ancestors of the given `object` **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) | Param | Type | Default | Description | | --- | --- | --- | --- | | object | <code>Object</code> | | | | [options] | <code>Object</code> | | | | [options.array] | <code>Array.&lt;Object&gt;</code> | <code>[]</code> | | | [options.filter] | <code>function</code> | | Function to test each object before it is added to the array. Invoked with arguments (object). Should return `true` if an object is to be included. | | [options.thisArg] | <code>\*</code> | | Value to use as `this` when executing `filter`. | <a name="module_symbol-tree--SymbolTree+treeToArray"></a> #### symbolTree.treeToArray(root, [options]) ⇒ <code>Array.&lt;Object&gt;</code> Append all descendants of the given object to an array (in tree order). * `O(n)` where `n` is the amount of objects in the sub-tree of the given `object` **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) | Param | Type | Default | Description | | --- | --- | --- | --- | | root | <code>Object</code> | | | | [options] | <code>Object</code> | | | | [options.array] | <code>Array.&lt;Object&gt;</code> | <code>[]</code> | | | [options.filter] | <code>function</code> | | Function to test each object before it is added to the array. Invoked with arguments (object). Should return `true` if an object is to be included. | | [options.thisArg] | <code>\*</code> | | Value to use as `this` when executing `filter`. | <a name="module_symbol-tree--SymbolTree+childrenIterator"></a> #### symbolTree.childrenIterator(parent, [options]) ⇒ <code>Object</code> Iterate over all children of the given object * `O(1)` for a single iteration **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) **Returns**: <code>Object</code> - An iterable iterator (ES6) | Param | Type | Default | | --- | --- | --- | | parent | <code>Object</code> | | | [options] | <code>Object</code> | | | [options.reverse] | <code>Boolean</code> | <code>false</code> | <a name="module_symbol-tree--SymbolTree+previousSiblingsIterator"></a> #### symbolTree.previousSiblingsIterator(object) ⇒ <code>Object</code> Iterate over all the previous siblings of the given object. (in reverse tree order) * `O(1)` for a single iteration **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) **Returns**: <code>Object</code> - An iterable iterator (ES6) | Param | Type | | --- | --- | | object | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+nextSiblingsIterator"></a> #### symbolTree.nextSiblingsIterator(object) ⇒ <code>Object</code> Iterate over all the next siblings of the given object. (in tree order) * `O(1)` for a single iteration **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) **Returns**: <code>Object</code> - An iterable iterator (ES6) | Param | Type | | --- | --- | | object | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+ancestorsIterator"></a> #### symbolTree.ancestorsIterator(object) ⇒ <code>Object</code> Iterate over all inclusive ancestors of the given object * `O(1)` for a single iteration **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) **Returns**: <code>Object</code> - An iterable iterator (ES6) | Param | Type | | --- | --- | | object | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+treeIterator"></a> #### symbolTree.treeIterator(root, options) ⇒ <code>Object</code> Iterate over all descendants of the given object (in tree order). Where `n` is the amount of objects in the sub-tree of the given `root`: * `O(n)` (worst case for a single iteration) * `O(n)` (amortized, when completing the iterator) **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) **Returns**: <code>Object</code> - An iterable iterator (ES6) | Param | Type | Default | | --- | --- | --- | | root | <code>Object</code> | | | options | <code>Object</code> | | | [options.reverse] | <code>Boolean</code> | <code>false</code> | <a name="module_symbol-tree--SymbolTree+index"></a> #### symbolTree.index(child) ⇒ <code>Number</code> Find the index of the given object (the number of preceding siblings). * `O(n)` where `n` is the amount of preceding siblings * `O(1)` (amortized, if the tree is not modified) **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) **Returns**: <code>Number</code> - The number of preceding siblings, or -1 if the object has no parent | Param | Type | | --- | --- | | child | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+childrenCount"></a> #### symbolTree.childrenCount(parent) ⇒ <code>Number</code> Calculate the number of children. * `O(n)` where `n` is the amount of children * `O(1)` (amortized, if the tree is not modified) **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) | Param | Type | | --- | --- | | parent | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+compareTreePosition"></a> #### symbolTree.compareTreePosition(left, right) ⇒ <code>Number</code> Compare the position of an object relative to another object. A bit set is returned: <ul> <li>DISCONNECTED : 1</li> <li>PRECEDING : 2</li> <li>FOLLOWING : 4</li> <li>CONTAINS : 8</li> <li>CONTAINED_BY : 16</li> </ul> The semantics are the same as compareDocumentPosition in DOM, with the exception that DISCONNECTED never occurs with any other bit. where `n` and `m` are the amount of ancestors of `left` and `right`; where `o` is the amount of children of the lowest common ancestor of `left` and `right`: * `O(n + m + o)` (worst case) * `O(n + m)` (amortized, if the tree is not modified) **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) | Param | Type | | --- | --- | | left | <code>Object</code> | | right | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+remove"></a> #### symbolTree.remove(removeObject) ⇒ <code>Object</code> Remove the object from this tree. Has no effect if already removed. * `O(1)` **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) **Returns**: <code>Object</code> - removeObject | Param | Type | | --- | --- | | removeObject | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+insertBefore"></a> #### symbolTree.insertBefore(referenceObject, newObject) ⇒ <code>Object</code> Insert the given object before the reference object. `newObject` is now the previous sibling of `referenceObject`. * `O(1)` **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) **Returns**: <code>Object</code> - newObject **Throws**: - <code>Error</code> If the newObject is already present in this SymbolTree | Param | Type | | --- | --- | | referenceObject | <code>Object</code> | | newObject | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+insertAfter"></a> #### symbolTree.insertAfter(referenceObject, newObject) ⇒ <code>Object</code> Insert the given object after the reference object. `newObject` is now the next sibling of `referenceObject`. * `O(1)` **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) **Returns**: <code>Object</code> - newObject **Throws**: - <code>Error</code> If the newObject is already present in this SymbolTree | Param | Type | | --- | --- | | referenceObject | <code>Object</code> | | newObject | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+prependChild"></a> #### symbolTree.prependChild(referenceObject, newObject) ⇒ <code>Object</code> Insert the given object as the first child of the given reference object. `newObject` is now the first child of `referenceObject`. * `O(1)` **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) **Returns**: <code>Object</code> - newObject **Throws**: - <code>Error</code> If the newObject is already present in this SymbolTree | Param | Type | | --- | --- | | referenceObject | <code>Object</code> | | newObject | <code>Object</code> | <a name="module_symbol-tree--SymbolTree+appendChild"></a> #### symbolTree.appendChild(referenceObject, newObject) ⇒ <code>Object</code> Insert the given object as the last child of the given reference object. `newObject` is now the last child of `referenceObject`. * `O(1)` **Kind**: instance method of [<code>SymbolTree</code>](#exp_module_symbol-tree--SymbolTree) **Returns**: <code>Object</code> - newObject **Throws**: - <code>Error</code> If the newObject is already present in this SymbolTree | Param | Type | | --- | --- | | referenceObject | <code>Object</code> | | newObject | <code>Object</code> | # htmlnano [![npm version](https://badge.fury.io/js/htmlnano.svg)](http://badge.fury.io/js/htmlnano) [![Build Status](https://travis-ci.org/posthtml/htmlnano.svg?branch=master)](https://travis-ci.org/posthtml/htmlnano) Modular HTML minifier, built on top of the [PostHTML](https://github.com/posthtml/posthtml). Inspired by [cssnano](http://cssnano.co/). > The author of htmlnano is available for hire as a full stack web developer: https://kirillmaltsev.net/services ## [Benchmark](https://github.com/maltsev/html-minifiers-benchmark/blob/master/README.md) [html-minifier@3.5.20]: https://www.npmjs.com/package/html-minifier [htmlnano@0.2.0]: https://www.npmjs.com/package/htmlnano | Website | Source (KB) | [html-minifier@3.5.20] | [htmlnano@0.2.0] | |---------|------------:|----------------:|-----------:| | [stackoverflow.com](http://stackoverflow.com/) | 258 | 205 | 218 | | [github.com](http://github.com/) | 63 | 51 | 56 | | [en.wikipedia.org](https://en.wikipedia.org/wiki/Main_Page) | 77 | 69 | 74 | | [npmjs.com](https://www.npmjs.com/features) | 32 | 29 | 30 | | **Avg. minify rate** | 0% | **15%** | **9%** | ## Usage ### Gulp ```bash npm install --save-dev gulp-htmlnano ``` ```js const gulp = require('gulp'); const htmlnano = require('gulp-htmlnano'); const options = { removeComments: false }; gulp.task('default', function() { return gulp .src('./index.html') .pipe(htmlnano(options)) .pipe(gulp.dest('./build')); }); ``` ### Javascript ```js const htmlnano = require('htmlnano'); const options = { removeEmptyAttributes: false, // Disable the module "removeEmptyAttributes" collapseWhitespace: 'conservative' // Pass options to the module "collapseWhitespace" }; // posthtml, posthtml-render, and posthtml-parse options const postHtmlOptions = { sync: true, // https://github.com/posthtml/posthtml#usage lowerCaseTags: true, // https://github.com/posthtml/posthtml-parser#options quoteAllAttributes: false, // https://github.com/posthtml/posthtml-render#options }; htmlnano // "preset" arg might be skipped (see "Presets" section below for more info) // "postHtmlOptions" arg might be skipped .process(html, options, preset, postHtmlOptions) .then(function (result) { // result.html is minified }) .catch(function (err) { console.error(err); }); ``` ### PostHTML Just add `htmlnano` as a final plugin: ```js const posthtml = require('posthtml'); const options = { removeComments: false, // Disable the module "removeComments" collapseWhitespace: 'conservative' // Pass options to the module "collapseWhitespace" }; const posthtmlPlugins = [ /* other PostHTML plugins */ require('htmlnano')(options) ]; const postHtmlOptions = { // See PostHTML docs }; posthtml(posthtmlPlugins) .process(html, posthtmlOptions) .then(function (result) { // result.html is minified }) .catch(function (err) { console.error(err); }); ``` ## Presets A preset is just an object with modules config. Currently the following presets are available: - [safe](https://github.com/posthtml/htmlnano/blob/master/lib/presets/safe.es6) — a default preset for minifying a regular HTML in a safe way (without breaking anything) - [ampSafe](https://github.com/posthtml/htmlnano/blob/master/lib/presets/ampSafe.es6) - same as `safe` preset but for [AMP pages](https://www.ampproject.org/) - [max](https://github.com/posthtml/htmlnano/blob/master/lib/presets/max.es6) - maximal minification (might break some pages) You can use them the following way: ```js const htmlnano = require('htmlnano'); const ampSafePreset = require('htmlnano').presets.ampSafe; const options = { // Your options }; htmlnano .process(html, options, ampSafePreset) .then(function (result) { // result.html is minified }) .catch(function (err) { console.error(err); }); ``` If you skip `preset` argument [`safe`](https://github.com/posthtml/htmlnano/blob/master/lib/presets/safe.es6) preset would be used by default. If you'd like to define your very own config without any presets pass an empty object as a preset: ```js const htmlnano = require('htmlnano'); const options = { // Your options }; htmlnano .process(html, options, {}) .then(function (result) { // result.html is minified }) .catch(function (err) { console.error(err); }); ``` You might create also your own presets: ```js const htmlnano = require('htmlnano'); // Preset for minifying email templates const emailPreset = { mergeStyles: true, minifyCss: { safe: true }, }; const options = { // Some specific options }; htmlnano .process(html, options, emailPreset) .then(function (result) { // result.html is minified }) .catch(function (err) { console.error(err); }); ``` Feel free [to submit a PR](https://github.com/posthtml/htmlnano/issues/new) with your preset if it might be useful for other developers as well. ## Modules By default the modules should only perform safe transforms, see the module documentation below for details. You can disable modules by passing `false` as option, and enable them by passing `true`. ### collapseAttributeWhitespace Collapse redundant white spaces in list-like attributes (`class`, `rel`, `ping`). ##### Example Source: ```html <div class=" content page "></div> ``` Minified: ```html <div class="content page"></div> ``` ### collapseWhitespace Collapses redundant white spaces (including new lines). It doesn’t affect white spaces in the elements `<style>`, `<textarea>`, `<script>` and `<pre>`. ##### Options - `conservative` — collapses all redundant white spaces to 1 space (default) - `all` — collapses all redundant white spaces ##### Side effects `<i>hello</i> <i>world</i>` after minification will be rendered as `helloworld`. To prevent that use `conservative` option (this is the default option). ##### Example Source: ```html <div> hello world! <style>div { color: red; } </style> </div> ``` Minified (with `all`): ```html <div>hello world!<style>div { color: red; } </style></div> ``` Minified (with `conservative`): ```html <div> hello world! <style>div { color: red; } </style> </div> ``` ### deduplicateAttributeValues Remove duplicate values from list-like attributes (`class`, `rel`, `ping`). ##### Example Source: ```html <div class="sidebar left sidebar"></div> ``` Minified: ```html <div class="sidebar left"></div> ``` ### removeComments ##### Options - `safe` – removes all HTML comments except the conditional comments and [`<!--noindex--><!--/noindex-->`](https://yandex.com/support/webmaster/controlling-robot/html.xml) (default) - `all` — removes all HTML comments ##### Example Source: ```html <div><!-- test --></div> ``` Minified: ```html <div></div> ``` ### removeEmptyAttributes Removes empty [safe-to-remove](https://github.com/posthtml/htmlnano/blob/master/lib/modules/removeEmptyAttributes.es6) attributes. ##### Side effects This module could break your styles or JS if you use selectors with attributes: ```CSS img[style=""] { margin: 10px; } ``` ##### Example Source: ```html <img src="foo.jpg" alt="" style=""> ``` Minified: ```html <img src="foo.jpg" alt=""> ``` ### removeUnusedCss Removes unused CSS inside `<style>` tags with either [uncss](https://github.com/uncss/uncss) or [PurgeCSS](https://github.com/FullHuman/purgecss). #### With uncss ##### Options See [the documentation of uncss](https://github.com/uncss/uncss) for all supported options. uncss options can be passed directly to the `removeUnusedCss` module: ```js htmlnano.process(html, { removeUnusedCss: { ignore: ['.do-not-remove'] } }); ``` The following uncss options are ignored if passed to the module: - `stylesheets` - `ignoreSheets` - `raw` #### With PurgeCSS Use PurgeCSS instead of uncss by adding `tool: 'purgeCSS'` to the options. ##### Options See [the documentation of PurgeCSS](https://www.purgecss.com) for all supported options. PurgeCSS options can be passed directly to the `removeUnusedCss` module: ```js htmlnano.process(html, { removeUnusedCss: { tool: 'purgeCSS', whitelist: ['.do-not-remove'] } }); ``` The following PurgeCSS options are ignored if passed to the module: - `content` - `css` - `extractors` ##### Example Source: ```html <div class="b"> <style> .a { margin: 10px 10px 10px 10px; } .b { color: #ff0000; } </style> </div> ``` Optimized: ```html <div class="b"> <style> .b { color: #ff0000; } </style> </div> ``` ### minifyCss Minifies CSS with [cssnano](http://cssnano.co/) inside `<style>` tags and `style` attributes. ##### Options See [the documentation of cssnano](http://cssnano.co/optimisations/) for all supported optimizations. By default CSS is minified with preset `default`, which shouldn't have any side-effects. To use another preset or disabled some optimizations pass options to `minifyCss` module: ```js htmlnano.process(html, { minifyCss: { preset: ['default', { discardComments: { removeAll: true, }, }] } }); ``` ##### Example Source: ```html <div> <style> h1 { margin: 10px 10px 10px 10px; color: #ff0000; } </style> </div> ``` Minified: ```html <div> <style>h1{margin:10px;color:red}</style> </div> ``` ### minifyJs Minifies JS using [Terser](https://github.com/fabiosantoscode/terser) inside `<script>` tags. ##### Options See [the documentation of Terser](https://github.com/fabiosantoscode/terser#api-reference) for all supported options. Terser options can be passed directly to the `minifyJs` module: ```js htmlnano.process(html, { minifyJs: { output: { quote_style: 1 }, }, }); ``` ##### Example Source: ```html <div> <script> /* comment */ const foo = function () { }; </script> </div> ``` Minified: ```html <div> <script>const foo=function(){};</script> </div> ``` ### minifyJson Minifies JSON inside `<script type="application/json"></script>`. ##### Example Source: ```html <script type="application/json"> { "user": "me" } </script> ``` Minified: ```html <script type="application/json">{"user":"me"}</script> ``` ### minifySvg Minifies SVG inside `<svg>` tags using [SVGO](https://github.com/svg/svgo/). ##### Options See [the documentation of SVGO](https://github.com/svg/svgo/blob/master/README.md) for all supported options. SVGO options can be passed directly to the `minifySvg` module: ```js htmlnano.process(html, { minifySvg: { plugins: [ { collapseGroups: false }, ], }, }); ``` ##### Example Source: ```html <svg version="1.1" baseProfile="full" width="300" height="200" xmlns="http://www.w3.org/2000/svg"> <rect width="100%" height="100%" fill="red" /> <circle cx="150" cy="100" r="80" fill="green" /> <text x="150" y="125" font-size="60" text-anchor="middle" fill="white">SVG</text> </svg>` ``` Minified: ```html <svg baseProfile="full" width="300" height="200" xmlns="http://www.w3.org/2000/svg"><rect width="100%" height="100%" fill="red"/><circle cx="150" cy="100" r="80" fill="green"/><text x="150" y="125" font-size="60" text-anchor="middle" fill="#fff">SVG</text></svg> ``` ### removeRedundantAttributes Removes redundant attributes from tags if they contain default values: - `method="get"` from `<form>` - `type="text"` from `<input>` - `type="submit"` from `<button>` - `language="javascript"` and `type="text/javascript"` from `<script>` - `charset` from `<script>` if it's an external script - `media="all"` from `<style>` and `<link>` ##### Options This module is disabled by default, change option to true to enable this module. ##### Side effects This module could break your styles or JS if you use selectors with attributes: ```CSS form[method="get"] { color: red; } ``` ##### Example Source: ```html <form method="get"> <input type="text"> </form> ``` Minified: ```html <form> <input> </form> ``` ### collapseBooleanAttributes Collapses boolean attributes (like `disabled`) to the minimized form. ##### Options If your document uses [AMP](https://www.ampproject.org/), set the `amphtml` flag to collapse additonal, AMP-specific boolean attributes: ```Json "collapseBooleanAttributes": { "amphtml": true } ``` ##### Side effects This module could break your styles or JS if you use selectors with attributes: ```CSS button[disabled="disabled"] { color: red; } ``` ##### Example Source: ```html <button disabled="disabled">click</button> <script defer=""></script> ``` Minified: ```html <button disabled>click</button> <script defer></script> ``` ### mergeStyles Merges multiple `<style>` with the same `media` and `type` into one tag. `<style scoped>...</style>` are skipped. ##### Example Source: ```html <style>h1 { color: red }</style> <style media="print">div { color: blue }</style> <style type="text/css" media="print">a {}</style> <style>div { font-size: 20px }</style> ``` Minified: ```html <style>h1 { color: red } div { font-size: 20px }</style> <style media="print">div { color: blue } a {}</style> ``` ### mergeScripts Merge multiple `<script>` with the same attributes (`id, class, type, async, defer`) into one (last) tag. ##### Side effects It could break your code if the tags with different attributes share the same variable scope. See the example below. ##### Example Source: ```html <script>const foo = 'A:1';</script> <script class="test">foo = 'B:1';</script> <script type="text/javascript">foo = 'A:2';</script> <script defer>foo = 'C:1';</script> <script>foo = 'A:3';</script> <script defer="defer">foo = 'C:2';</script> <script class="test" type="text/javascript">foo = 'B:2';</script> ``` Minified: ```html <script>const foo = 'A:1'; foo = 'A:2'; foo = 'A:3';</script> <script defer="defer">foo = 'C:1'; foo = 'C:2';</script> <script class="test" type="text/javascript">foo = 'B:1'; foo = 'B:2';</script> ``` ### custom It's also possible to pass custom modules in the minifier. As a function: ```js const options = { custom: function (tree, options) { // Some minification return tree; } }; ``` Or as a list of functions: ```js const options = { custom: [ function (tree, options) { // Some minification return tree; }, function (tree, options) { // Some other minification return tree; } ] }; ``` `options` is an object with all options that were passed to the plugin. ## Contribute Since the minifier is modular, it's very easy to add new modules: 1. Create a ES6-file inside `lib/modules/` with a function that does some minification. For example you can check [`lib/modules/example.es6`](https://github.com/posthtml/htmlnano/blob/master/lib/modules/example.es6). 2. Add the module in [the modules array](https://github.com/posthtml/htmlnano/blob/master/lib/htmlnano.es6#L5). The modules are applied from top to bottom. So you can choose the order for your module. 3. Create a JS-file inside `test/modules/` with some unit-tests. 4. Describe your module in the section "[Modules](https://github.com/posthtml/htmlnano/blob/master/README.md#modules)". 5. Send me a pull request. Other types of contribution (bug fixes, documentation improves, etc) are also welcome! Would like to contribute, but don't have any ideas what to do? Check out [our issues](https://github.com/posthtml/htmlnano/labels/help%20wanted). <!-- 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/domain-browser@1.2.0</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 --> # ASBuild A simple build tool for [AssemblyScript](https://assemblyscript.org) projects, similar to `cargo`, etc. ## Usage ``` asb [entry file] [options] -- [args passed to asc] ``` ### Background AssemblyScript greater than v0.14.4 provides a `asconfig.json` configuration file that can be used to describe the options for building a project. ASBuild uses this and some adds defaults to create an easier CLI interface. ### 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 { "workspace": ["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](./test) # 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). # 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 # 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 # [postcss][postcss]-discard-duplicates > Discard duplicate rules in your CSS files with PostCSS. ## Install With [npm](https://npmjs.org/package/postcss-discard-duplicates) do: ``` npm install postcss-discard-duplicates --save ``` ## Example This module will remove all duplicate rules from your stylesheets. It works on at rules, normal rules and declarations. Note that this module does not have any responsibility for normalising declarations, selectors or whitespace, so that it considers these two rules to be different: ```css h1, h2 { color: blue; } h2, h1 { color: blue; } ``` It has to assume that your rules have already been transformed by another processor, otherwise it would be responsible for too many things. ### Input ```css h1 { margin: 0 auto; margin: 0 auto } h1 { margin: 0 auto } ``` ### Output ```css h1 { margin: 0 auto } ``` ## Usage See the [PostCSS documentation](https://github.com/postcss/postcss#usage) for examples for your environment. ## Contributors See [CONTRIBUTORS.md](https://github.com/cssnano/cssnano/blob/master/CONTRIBUTORS.md). ## License MIT © [Ben Briggs](http://beneb.info) [postcss]: https://github.com/postcss/postcss # 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). # 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 # MDN data [https://github.com/mdn/data](https://github.com/mdn/data) Maintained by the [MDN team at Mozilla](https://wiki.mozilla.org/MDN). This repository contains general data for Web technologies. This data is used in MDN documentation, to build [information boxes](https://developer.mozilla.org/en-US/docs/Web/CSS/background) or [sidebar navigation](https://developer.mozilla.org/en-US/docs/Web/API/Window). External tools have started to make use of this data as well. For example, the [CSSTree](https://github.com/csstree/csstree/) CSS parser. [![NPM version](https://img.shields.io/npm/v/mdn-data.svg)](https://www.npmjs.com/package/mdn-data) [![Build Status](https://travis-ci.org/mdn/data.svg?branch=master)](https://travis-ci.org/mdn/data) ## Repository contents There's a top-level directory for each broad area covered: for example, "api", "css", "svg". Inside each of these directories is one or more JSON files containing the data. ### api Contains data about Web APIs: * API inheritance (interface inheritance and mixin implementations) ### css Contains data about: * CSS at-rules * CSS properties * CSS selectors * CSS syntaxes * CSS types * CSS units Read more about [CSS data](https://github.com/mdn/data/blob/master/css/readme.md) and the format of the files. ### l10n The l10n folder contains localization strings that are used in the various json files throughout this repository. ## Problems? If you find a problem, please [file an issue](https://github.com/mdn/data/issues/new). ## Contributing We're very happy to accept contributions to this data. Please familiarize yourself with the schema for the data you're editing, and send us a pull request. See also the [Contributing file](https://github.com/mdn/data/blob/master/CONTRIBUTING.md) for more information. ## See also * [https://github.com/mdn/browser-compat-data](https://github.com/mdn/browser-compat-data) for compatibility data for Web technologies. # 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._ # 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 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> # exec-sh [![NPM](https://nodei.co/npm/exec-sh.png)](https://nodei.co/npm/exec-sh/) [![NPM Downloads](https://img.shields.io/npm/dm/exec-sh.svg)](https://www.npmjs.com/package/exec-sh) [![Build Status](https://travis-ci.org/tsertkov/exec-sh.svg?branch=master)](https://travis-ci.org/tsertkov/exec-sh) [![Coverage Status](https://img.shields.io/coveralls/tsertkov/exec-sh.svg)](https://coveralls.io/r/tsertkov/exec-sh?branch=master) [![David Status](https://david-dm.org/tsertkov/exec-sh.png)](https://david-dm.org/tsertkov/exec-sh) > Execute shell command forwarding all stdio streams. ## Features exec-sh is a wrapper for [`child_process.spawn`](http://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options) with some improvements: - Cross platform command execution: - Windows: `cmd /C COMMAND` - others: `sh -c COMMAND` - Fowrards all stdio streams to current terminal (by default): - `execSh("bash")` - `execsh("echo -n Say: && read i && echo Said:$i")` - stdout and stderr are passed to callback when available - `execSh("pwd", console.log)` ## Showcase ```javascript // JavaScript execSh("echo hello exec-sh && bash", { cwd: "/home" }, function(err){ if (err) { console.log("Exit code: ", err.code); } }); ``` ```sh # Terminal output: interactive bash session hello exec-sh bash-3.2$ pwd /home bash-3.2$ exit 99 exit Exit code: 99 ``` ## Usage ```javascript var execSh = require("../"); // run interactive bash shell execSh("echo lorem && bash", { cwd: "/home" }, function(err){ if (err) { console.log("Exit code: ", err.code); return; } // collect streams output var child = execSh(["bash -c id", "echo lorem >&2"], true, function(err, stdout, stderr){ console.log("error: ", err); console.log("stdout: ", stdout); console.log("stderr: ", stderr); }); }); ``` ## Promise Interface ```javascript var execShPromise = require("exec-sh").promise; // run interactive bash shell const run = async () => { let out; try { out = await execShPromise('pwd', true); } catch (e) { console.log('Error: ', e); console.log('Stderr: ', e.stderr); console.log('Stdout: ', e.stdout); return e; } console.log('out: ', out.stdout, out.stderr); } run(); ``` ## Public API ### `execSh(command, [options], [callback])` Execute shell command forwarding all stdio. **Parameters:** - `command {String|Array}` - The command to run, or array of commands - `[options] {Object|TRUE}` - Options object passed directly to [`child_process.spawn`](http://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options), when `TRUE` then `{ stdio: null }` used - `[callback] {Function}` - `callback(err, stdout, stderr)` - `err {Error|NULL}` - Error object. Has `code` property containing last command exit code when available - `stdout {String|NULL}` - aggregated stdout or `NULL` if not available - `stderr {String|NULL}` - aggregated stderr or `NULL` if not available **Return Values:** Returns [ChildProcess](http://nodejs.org/api/child_process.html#child_process_class_childprocess) object. ## Private API Complete API Documentation including private and public methods is generated from source code by JSDoc tool and is [available here](https://s3.eu-central-1.amazonaws.com/tsertkov-artifacts/exec-sh/master/jsdoc/index.html). ## Code Coverage Code coverage report for all files is [available here](https://s3.eu-central-1.amazonaws.com/tsertkov-artifacts/exec-sh/master/coverage/index.html). ## Scripts - `npm test` - run tests - `npm run jsdoc` - build jsdoc - `npm run dev` - run tests continuously ## License The MIT License (MIT) # assemblyscript-json JSON encoder / decoder for AssemblyScript. Special thanks to https://github.com/MaxGraey/bignum.wasm for basic unit testing infra for AssemblyScript. # Limitations This is developed for use in smart contracts written in AssemblyScript for https://github.com/nearprotocol/nearcore. This imposes such limitations: - Float numbers not supported - We assume that memory never needs to be deallocated (cause these contracts are short-lived). Note that this mostly just defines the way it's currently implemented. Contributors are welcome to fix limitations. # Usage ## Encoding JSON ```ts // Make sure memory allocator is available import "allocator/arena"; // Import encoder import { JSONEncoder } from "path/to/module"; // 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.toString(); ``` ## Parsing JSON ```ts // Make sure memory allocator is available import "allocator/arena"; // Import decoder import { JSONDecoder, JSONHandler } from "path/to/module"; // 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: i32): 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()); // Let's assume JSON data is available in this variable let json: Uint8Array = ...; // Parse JSON decoder.deserialize(json); // This will send events to MyJSONEventsHandler ``` ## JSON namespace ```ts import { JSON } from "path/to/module"; // Can use JS parse api let jsonObj: JSON.Object = JSON.parse(`{"hello": "world"}`); // Can then use a key to read from the object if you know it's type let world = jsonObj.getString("hello"); // If you don't know what the type of the value let unknown = jsonObj.getValue("hello") unknown.isString // true; ``` 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/become_a_patron_button@2x.png" 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 `uglify-js@2.x`, 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 | - | | terser@3.7.5 mangle=false, compress=false | 316,600 | 85,245 | 0.82 | | terser@3.7.5 mangle=true, compress=false | 220,216 | 72,730 | 1.45 | | terser@3.7.5 mangle=true, compress=true | 212,046 | 70,954 | 5.87 | | babili@0.1.4 | 210,713 | 72,140 | 12.64 | | babel-minify@0.4.3 | 210,321 | 72,242 | 48.67 | | babel-minify@0.5.0-alpha.01eac1c3 | 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/become_a_patron_button@2x.png" 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) # near-sdk-as Collection of packages used in developing NEAR smart contracts in AssemblyScript including: - [`runtime`](./assembly/runtime) - AssemblyScript near runtime library - [`bindgen`](./bindgen) - AssemblyScript transformer that adds the bindings needed to (de)serialize input and outputs. - [`wasm-mock-vm`](https://github.com/nearprotocol/wasm-mock-vm) - Core of the NEAR VM compiled to WebAssembly used for writing unit tests. - [`VM Runtime`](./runtime) - A NearVM Simulator for making contract calls. - [`@as-pect/cli`](https://github.com/jtenner/as-pect) - AssemblyScript testing framework similar to jest. ## To Install ``` yarn add -D near-sdk-as ``` ## 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. # <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/ # <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/ # 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` ## 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') // defaults to BIP39 English word list // uses HEX strings for entropy var mnemonic = bip39.entropyToMnemonic('00000000000000000000000000000000') // => zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong // reversible bip39.mnemonicToEntropy(mnemonic) // => '133755ff' ``` # 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. # regexpu-core [![Build status](https://travis-ci.org/mathiasbynens/regexpu-core.svg?branch=main)](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 ES2015 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 ES2015 `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 ES2015 `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 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 [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 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 support for [named capture groups](https://github.com/tc39/proposal-regexp-named-groups). ```js rewritePattern('(?<name>.)\k<name>', '', { 'namedGroup': 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>', '', { 'namedGroup': 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 ES2015 `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. css-color-names =============== A JSON Object of css color names mapped to their hex value Usage ----- ``` js var csscolors = require('css-color-names'); console.dir(csscolors); ``` yields ``` json { "aqua": "#00ffff", "aliceblue": "#f0f8ff", "antiquewhite": "#faebd7", "black": "#000000", "blue": "#0000ff", ... } ``` How was this list generated? ---------------------------- In the Makefile you'll see a line like this: ./getcolors.sh | ./stringify.js > $(FILE) The first command scrapes a site for the list, and outputs the results separated by newlines. The second command creates the JSON object and outputs it to stdout, which then gets redirected into `css-color-names.json` Installation ------------ npm install css-color-names License ------- MIT # toidentifier [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Build Status][travis-image]][travis-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 [npm-image]: https://img.shields.io/npm/v/toidentifier.svg [npm-url]: https://npmjs.org/package/toidentifier [travis-image]: https://img.shields.io/travis/component/toidentifier/master.svg [travis-url]: https://travis-ci.org/component/toidentifier ## [npm]: https://www.npmjs.com/ [yarn]: https://yarnpkg.com/ # grapheme-breaker A JavaScript implementation of the Unicode grapheme cluster breaking algorithm ([UAX #29](http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries)) > It is important to recognize that what the user thinks of as a “character”—a basic unit of a writing system for a > language—may not be just a single Unicode code point. Instead, that basic unit may be made up of multiple Unicode > code points. To avoid ambiguity with the computer use of the term character, this is called a user-perceived character. > For example, “G” + acute-accent is a user-perceived character: users think of it as a single character, yet is actually > represented by two Unicode code points. These user-perceived characters are approximated by what is called a grapheme cluster, > which can be determined programmatically. ## Installation You can install via npm npm install grapheme-breaker ## Example ```javascript var GraphemeBreaker = require('grapheme-breaker'); // break a string into an array of grapheme clusters GraphemeBreaker.break('Z͑ͫ̓ͪ̂ͫ̽͏̴̙̤̞͉͚̯̞̠͍A̴̵̜̰͔ͫ͗͢L̠ͨͧͩ͘G̴̻͈͍͔̹̑͗̎̅͛́Ǫ̵̹̻̝̳͂̌̌͘!͖̬̰̙̗̿̋ͥͥ̂ͣ̐́́͜͞') // => ['Z͑ͫ̓ͪ̂ͫ̽͏̴̙̤̞͉͚̯̞̠͍', 'A̴̵̜̰͔ͫ͗͢', 'L̠ͨͧͩ͘', 'G̴̻͈͍͔̹̑͗̎̅͛́', 'Ǫ̵̹̻̝̳͂̌̌͘', '!͖̬̰̙̗̿̋ͥͥ̂ͣ̐́́͜͞'] // or just count the number of grapheme clusters in a string GraphemeBreaker.countBreaks('Z͑ͫ̓ͪ̂ͫ̽͏̴̙̤̞͉͚̯̞̠͍A̴̵̜̰͔ͫ͗͢L̠ͨͧͩ͘G̴̻͈͍͔̹̑͗̎̅͛́Ǫ̵̹̻̝̳͂̌̌͘!͖̬̰̙̗̿̋ͥͥ̂ͣ̐́́͜͞') // => 6 // use nextBreak and previousBreak to get break points starting // from anywhere in the string GraphemeBreaker.nextBreak('😜🇺🇸👍', 3) // => 6 GraphemeBreaker.previousBreak('😜🇺🇸👍', 3) // => 2 ``` ## Development Notes In order to use the library, you shouldn't need to know this, but if you're interested in contributing or fixing bugs, these things might be of interest. * The `src/classes.coffee` file is automatically generated from `GraphemeBreakProperty.txt` in the Unicode database by `src/generate_data.coffee`. It should be rare that you need to run this, but you may if, for instance, you want to change the Unicode version. * You can run the tests using `npm test`. They are written using `mocha`, and generated from `GraphemeBreakTest.txt` from the Unicode database, which is included in the repository for performance reasons while running them. ## License MIT # 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._ # 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. # 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. # 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 # 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>
NearSocial_social-db
CHANGELOG.md Cargo.toml README.md build_docker.sh build_local.sh contract Cargo.toml src account.rs api.rs legacy.rs lib.rs node.rs permission.rs shared_storage.rs storage_tracker.rs upgrade.rs utils.rs integration-tests Cargo.toml README.md build.rs src get_workspace_dir.rs set.rs migration migrate.js package.json rust-toolchain.toml test_local.sh
# Integration Tests This directory contains integration tests for the Social DB contract. The build script compiles the WASM contract automatically if there are changes in the contract source code. Run a specific integration test with: ```bash cargo run --example set_method ``` # Social DB ## Notes ### Testnet account ID Deployed at `v1.social08.testnet` https://explorer.testnet.near.org/accounts/v1.social08.testnet ### Mainnet account ID Deployed at `social.near` https://explorer.near.org/accounts/social.near ### About empty keys If a leaf value was originally string, e.g. `name` ```json { "alex.near": { "profile": { "name": "Alex" } } } ``` And later some value was added under `name`, the name will be transformed to a node, and the value will be moved to an empty key under this node. E.g. `name/foo = "bar"` is added. ```json { "alex.near": { "profile": { "name": { "": "Alex", "foo": "bar" } } } } ``` ## Changelog See [CHANGELOG.md](CHANGELOG.md) ## API ### Storing data The top level keys of the objects should be account IDs under which the data is stored. Those accounts are covering storage for the underlying data. The predecessor_id or the signer public key should have permission to write under those keys. If the predecessor_id matches the top level key, then it can write any data under that key, as long as it has a permission or at least 1 yoctoNEAR is attached. The attached deposit will be transferred to the first key. If the account doesn't exist, it will be created (the predecessor_id should match). ```rust #[payable] pub fn set(&mut self, data: Value); ``` Arguments: - `data` is an object to store. The leaf values should be strings or null values. String values will be added, while null values will be deleted. Examples: ```js set({ data: { "alex.near": { "profile": { "name": "Alex", "image": { "url": "https://gkfjklgdfjkldfg" } }, } } }) set({ data: { "alex.near": { "graph": { "follow": { "root.near": "", "bob.near": "", } } } } }) ``` ### Reading data Returns the data for a list of given key patterns. It takes one or more path patterns as arguments, and returns the matching data. The path pattern is a string that can contain wildcards. For example: - `alice.near/profile/**` will match the entire profile data of account `alice.near`. - `alice.near/profile/*` will match all the fields of the profile, but not the nested objects. - `alice.near/profile/name` will match only the name field of the profile. - `*/widget/*` will match all the widgets of all the accounts. ```rust pub struct GetOptions { pub with_block_height: Option<bool>, pub with_node_id: Option<bool>, pub return_deleted: Option<bool>, } pub fn get(self, keys: Vec<String>, options: Option<GetOptions>) -> Value; ``` Arguments: - `keys` - an array of key patterns to return. - `options` - optional argument to specify options. Options: - `with_block_height` - if true, for every value and a node will add the block height of the data with the key `:block`. - `with_node_id` - if true, for every node will add the node index with the key `:node`. - `return_deleted` - if true, will include deleted keys with the value `null`. Returns the aggregated JSON object. Examples: ```js get({keys: ["alex.near/profile/name"]}) get({keys: ["alex.near/profile/name", "root.near/profile/name"]}) get({keys: ["alex.near/profile/name", "alex.near/profile/description"]}) get({keys: ["alex.near/profile/tags/*"]}) get({keys: ["alex.near/profile/**"]}) get({keys: ["*/widget/*"]}) get({keys: ["alex.near/profile/tags/*"], options: {return_deleted: true}}) ``` ### Reading keys The `keys` method allows to get the list of keys that match the path pattern. It's useful for querying the data without reading values. It also has an additional `options` field that can be used to specify the return type and whether to return deleted keys. For example: - `alice.near/profile/*` will return the list of all the fields of the profile, but not the nested objects. - `*/profile/image/nft` will return the list of all the accounts that have an NFT image in their profile. - `alice.near/widget/*` with `return_deleted` option will return the list of all the widget names of the account, including the deleted ones. - `alice.near/widget/*` with `return_type` equal to `BlockHeight` will return the list of all the widget names of the account and the value will be the block height when the widget was last updated. - Note `**` is not supported by the `keys` method. ```rust pub enum KeysReturnType { True, BlockHeight, NodeId, } pub struct KeysOptions { pub return_type: Option<KeysReturnType>, pub return_deleted: Option<bool>, pub values_only: Option<bool>, } pub fn keys(self, keys: Vec<String>, options: Option<KeysOptions>) -> Value; ``` Arguments: - `keys` - an array of key patterns to return. - `options` - optional argument to specify options. Options: - `return_type` - if `BlockHeight`, will return the block height of the key instead of `true`, if `NodeId`, will return the node index of the key instead of `true`. - `return_deleted` - if true, will include deleted keys. - `values_only` - if `true`, only matches keys which value is not a node. It's needed to filter out deleted entries. Since a node can't be deleted right now. Returns the aggregated JSON object. Examples: ```js keys({keys: ["alex.near/profile/*"]}) keys({keys: ["*/profile/image/nft"]}) keys({keys: ["alex.near/widget/*"], options: {return_deleted: true}}) keys({keys: ["alex.near/widget/*"], options: {return_type: "BlockHeight", values_only: true}}) ``` ### Permissions See https://explorer.testnet.near.org/transactions/3c7h9da1z5Px4JumNDsRaJtCDQaZHG46dsc2SnAj5LHx\ ```rust #[payable] pub fn grant_write_permission( &mut self, predecessor_id: Option<AccountId>, public_key: Option<PublicKey>, keys: Vec<String>, ); ``` ```rust /// Returns true if the permission is granted for a given account ID or a given public_key to /// any prefix of the key. pub fn is_write_permission_granted( &self, predecessor_id: Option<AccountId>, public_key: Option<PublicKey>, key: String, ) -> bool; ``` ### Debugging ```bash export CONTRACT_ID=v1.social08.testnet export ACCOUNT_ID=eugenethedream # Full contract data near view $CONTRACT_ID get '{"keys":["**"]}' # Full account's data near view $CONTRACT_ID get '{"keys":["'$ACCOUNT_ID'/**"]}' ```
near_as-base58
.github ISSUE_TEMPLATE BOUNTY.yml .travis.yml README.md as-pect.config.js assembly __tests__ as-pect.d.ts roundtrip.spec.ts index.ts tsconfig.json package.json
# as-base58 Base58 encoder / decoder for AssemblyScript. Special thanks to https://github.com/cryptocoinjs/base-x for the javascript version. # Usage ```ts import { encode, decode } from "as-base58"; const input = "ABCD1234" assert(input = enocde(decode("ABCD1234")); ```
Panasthetik_near-supply-chain
README.md final_contract Cargo.toml build.bat build.sh src lib.rs models.rs utils.rs test.sh starter_files lib.rs models.rs utils.rs test_file test.rs
# near-supply-chain Near Protocol supply chain smart contract template in Rust for order tracking and administration. # Article / Tutorial This will be published on Medium as a web3 tutorial. # Adaptable The project can be adapted to your needs on Near Protocol, if you need a supply chain type contract to track orders, or a b2b application.
maxistyping_near-sdk-js-1
.github ISSUE_TEMPLATE bug.yml config.yml feature.yml pull_request_template.md workflows tests.yml CODE_OF_CONDUCT.md CONTRIBUTING.md README.md RELEASE.md SECURITY.md TOOLING.md benchmark README.md __tests__ test-deploy-contract.ava.js test-expensive-calc.ava.js test-highlevel-collection.ava.js test-highlevel-minimal.ava.js test-lowlevel-api.ava.js test-lowlevel-minimal.ava.js util.js example-outcome.json jsconfig.json package.json src deploy-contract.js expensive-calc.js highlevel-collection.js highlevel-minimal.js lowlevel-api.js lowlevel-minimal.js tsconfig.json examples __tests__ standard-nft test_approval.ava.js test_core.ava.js test_enumeration.ava.js test-clean-state.ava.js test-counter.ava.js test-cross-contract-call-loop.ava.js test-cross-contract-call.ava.js test-fungible-token-lockable.ava.js test-fungible-token.ava.js test-nested-collections.ava.js test-non-fungible-token.ava.js test-parking-lot.ava.js test-programmatic-update.ava.js test-status-message-collections.ava.js test-status-message.ava.js jsconfig.json package.json src clean-state.js counter-lowlevel.js counter.js counter.ts cross-contract-call-loop.js cross-contract-call.js fungible-token-helper.ts fungible-token-lockable.js fungible-token.ts log.ts nested-collections.ts non-fungible-token-receiver.js non-fungible-token.js parking-lot.ts programmatic-update-after.ts programmatic-update-before.ts standard-nft my-nft.ts test-approval-receiver.ts test-token-receiver.ts status-message-collections.js status-message.js tsconfig.json package.json packages near-contract-standards lib event.d.ts event.js index.d.ts index.js non_fungible_token approval approval_receiver.d.ts approval_receiver.js index.d.ts index.js core index.d.ts index.js receiver.d.ts receiver.js resolver.d.ts resolver.js enumeration index.d.ts index.js events.d.ts events.js impl.d.ts impl.js index.d.ts index.js metadata.d.ts metadata.js token.d.ts token.js utils.d.ts utils.js package.json src event.ts index.ts non_fungible_token approval approval_receiver.ts index.ts core index.ts receiver.ts resolver.ts enumeration index.ts events.ts impl.ts index.ts metadata.ts token.ts utils.ts tsconfig.json near-sdk-js README.md builder builder.c lib api.d.ts api.js cli abi.d.ts abi.js build-tools include-bytes.d.ts include-bytes.js near-bindgen-exporter.d.ts near-bindgen-exporter.js cli.d.ts cli.js 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 version.d.ts version.js package.json src api.ts cli abi.ts build-tools include-bytes.ts near-bindgen-exporter.ts cli.ts post-install.ts utils.ts collections index.ts lookup-map.ts lookup-set.ts unordered-map.ts unordered-set.ts vector.ts index.ts near-bindgen.ts promise.ts types account_id.ts collections.ts gas.ts index.ts primitives.ts public_key.ts vm_types.ts utils.ts version.ts tsconfig.json tests README.md __tests__ bytes.ava.js constructor_validation.ava.js decorators near_bindgen.ava.js payable.ava.js private.ava.js function-params.ava.js lookup-map.ava.js lookup-set.ava.js test-bigint-serialization.ava.js test-date-serialization.ava.js test-middlewares.ava.js test-public-key.ava.js test_context_api.ava.js test_highlevel_promise.ava.js test_log_panic_api.ava.js test_math_api.ava.js test_promise_api.ava.js test_storage_api.ava.js typescript.ava.js unordered-map.ava.js unordered-set.ava.js vector.ava.js jsconfig.json package.json src bigint-serialization.ts bytes.js constructor-validation 1-parameter-not-set-in-constructor.ts all-parameters-set-in-constructor.ts no-constructor.ts no-parameters-set-in-constructor.ts context_api.js date-serialization.ts decorators payable.ts private.ts require_init_false.ts require_init_true.ts function-params.js highlevel-promise.js log_panic_api.js lookup-map.js lookup-set.js math_api.js middlewares.ts model.js promise_api.js promise_batch_api.js public-key.js storage_api.js typescript.ts unordered-map.js unordered-set.js vector.js tsconfig.json turbo.json
> **Warning** > > This SDK is currently in **[`Alpha`](https://github.com/near/near-sdk-js/releases/)**. > > The JavaScript runtime has not been fully audited. For creating smart contracts that hold value please use [`near-sdk-rs`](https://github.com/near/near-sdk-rs). > > Help contribute! > > - [Report issues you encounter](https://github.com/near/near-sdk-js/issues) 🐞 > - [Provide suggestions or feedback](https://github.com/near/near-sdk-js/discussions) 💡 > - [Show us what you've built!](https://github.com/near/near-sdk-js/discussions/categories/show-and-tell) 💪 # 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) - [Programmatic Update After Locking The Contract](https://github.com/near/near-sdk-js/tree/develop/examples/src/programmatic-update.js) To build all examples, run `pnpm build` in `examples/`. To test all examples, run `pnpm test`. You can also build and test one specific example with `pnpm build:<example-name>` and `pnpm 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 ## Migrating from near-sdk-js 0.6.0 If you have a near-sdk-js 0.6.0 contract, you need to drop the `babel.config.json` because it is now inlined in near-sdk-js CLI. Also `Bytes` type in 0.6.0 is replaced with `string` and `Uint8Array`. Because `Bytes` was an alias to `string`, this doesn't affect all collection APIs and most low level APIs. Some low level APIs below now also comes with a raw version, which ends with `Raw` and takes `Uint8Array` instead of `string`, for example, `storageRead` vs `storageReadRaw`. Some low level APIs have more sense to use `Uint8Array` instead of `string`, such as `sha256` and arguments for a function call type of promise, these are **BREAKING** changes. Please refer to next section for details: look for functions with `Uint8Array` argument and return types. ## 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 pnpm 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. - For those API that takes or returns raw bytes, it is a JavaScript `Uint8Array`. You can use standard `Uint8Array` methods on it or decode it to string with `decode` or `str`. The differece between `decode` and `str` is: `decode` decode the array as UTF-8 sequence. `str` simply converts each Uint8 to one char with that char code. ### Context API ``` function currentAccountId(): string; function signerAccountId(): string; function signerAccountPk(): Uint8Array; function predecessorAccountId(): string; function inputRaw(): Uint8Array; function input(): string; 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(): Uint8Array; function sha256(value: Uint8Array): Uint8Array; function keccak256(value: Uint8Array): Uint8Array; function keccak512(value: Uint8Array): Uint8Array; function ripemd160(value: Uint8Array): Uint8Array; function ecrecover(hash: Uint8Array, sign: Uint8Array, v: bigint, malleability_flag: bigint): Uint8Array | null; ``` ### Miscellaneous API ``` function valueReturnRaw(value: Uint8Array); function valueReturn(value: string); function panic(msg?: string); function panicUtf8(msg: Uint8Array); function logUtf8(msg: Uint8Array); function logUtf16(msg: Uint8Array); function log(...params: unknown[]); ``` ### Promises API ``` function promiseCreate(account_id: string, method_name: string, arguments: Uint8Array, amount: bigint, gas: bigint): bigint; function promiseThen(promise_index: bigint, account_id: string, method_name: string, arguments: Uint8Array, 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: PromiseIndex); function promiseBatchActionDeployContract(promise_index: PromiseIndex, code: Uint8Array); function promiseBatchActionFunctionCall(promise_index: PromiseIndex, method_name: string, arguments: Uint8Array, amount: bigint, gas: bigint); function promiseBatchActionFunctionCallWeight(promise_index: PromiseIndex, method_name: string, arguments: Uint8Array, amount: bigint, gas: bigint, weight: bigint); function promiseBatchActionTransfer(promise_index: PromiseIndex, amount: bigint); function promiseBatchActionStake(promise_index: PromiseIndex, amount: bigint, public_key: Uint8Array); function promiseBatchActionAddKeyWithFullAccess(promise_index: PromiseIndex, public_key: Uint8Array, nonce: bigint); function promiseBatchActionAddKeyWithFunctionCall(promise_index: PromiseIndex, public_key: Uint8Array, nonce: bigint, allowance: bigint, receiver_id: string, method_names: string); function promiseBatchActionDeleteKey(promise_index: PromiseIndex, public_key: Uint8Array); function promiseBatchActionDeleteAccount(promise_index: PromiseIndex, beneficiary_id: string); ``` ### Promise API results ``` function promiseResultsCount(): bigint; function promiseResultRaw(result_idx: PromiseIndex): Uint8Array; function promiseResult(result_idx: PromiseIndex): string; function promiseReturn(promise_idx: PromiseIndex); ``` ### Storage API ``` function storageWriteRaw(key: Uint8Array, value: Uint8Array): boolean; function storageReadRaw(key: Uint8Array): Uint8Array | null; function storageRemoveRaw(key: Uint8Array): boolean; function storageHasKeyRaw(key: Uint8Array): boolean; function storageWrite(key: string, value: string): boolean; function storageRead(key: string): bigint; function storageRemove(key: string): bigint; function storageHasKey(key: string): bigint; ``` ### Validator API ``` function validatorStake(account_id: string): bigint; function validatorTotalStake(): bigint; ``` ### Alt BN128 ``` function altBn128G1Multiexp(value: Uint8Array): Uint8Array; function altBn128G1Sum(value: Uint8Array): Uint8Array; function altBn128PairingCheck(value: Uint8Array): boolean; ``` ### 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 `string`. #### 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 string 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 in `Uint8Array`. That's one byte to represent the curve type of the public key, either ed25519 (`0x0`), or secp256k1 (`0x1`), follows by the curve-specific public key data in bytes. Examples: ```js new PublicKey(near.signerAccountPk()); let pk = new PublicKey( new Uint8Array([ // CurveType.ED25519 = 0 0, // ED25519 PublicKey data 186, 44, 216, 49, 157, 48, 151, 47, 23, 244, 137, 69, 78, 150, 54, 42, 30, 248, 110, 26, 205, 18, 137, 154, 10, 208, 26, 183, 65, 166, 223, 18, ]) ); let pk = new PublicKey( new Uint8Array([ // CurveType.SECP256K1 = 1 1, // SECP256K1 PublicKey data 242, 86, 198, 230, 200, 11, 33, 63, 42, 160, 176, 23, 68, 35, 93, 81, 92, 89, 68, 53, 190, 101, 27, 21, 136, 58, 16, 221, 71, 47, 166, 70, 206, 98, 234, 243, 103, 13, 197, 203, 145, 0, 160, 202, 42, 85, 178, 193, 71, 193, 233, 163, 140, 228, 40, 135, 142, 125, 70, 225, 251, 113, 74, 153, ]) ); ``` 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`. ## How to use NEAR SDK JS on Windows You can develop smart contracts on Windows using Windows Subsystem for Linux (WSL2). In order to use WSL2, follow the next steps: - Run `PowerShell` as Administrator - Execute `wsl --install` to install Ubuntu and do additional setup automatically. Check more details [here](https://learn.microsoft.com/en-us/windows/wsl/install) - Restart your machine - `WSL2` will continue setup process on start. Setup your username and password when prompted. - Check [this](https://learn.microsoft.com/en-us/windows/dev-environment/javascript/nodejs-on-wsl) guide to setup `npm`, `node`, `npx`, `VSCode` and other tools of your choice in order to start developing. In case of any issues of setting up WSL2 make sure that: - Your Windows OS is up to date - Virtualisation is turned on in BIOS - `Windows Subsystem for Linux` and `Virtual Machine Platform` are turned on in `Windows Features` (Start -> Search -> Turn Windows Feature On or Off) # NEAR-SDK-JS Tests This tests the functionality of high level APIs of NEAR-SDK-JS. Currently, it directly tests all collections and indirectly tests all decorators, serialization/deserialization, utils, code generation and some important APIs. Majority of near-sdk-js can be seen as tested. # Run tests ``` pnpm install pnpm build pnpm test ``` # Add a new test Create a test contract that covers the API you want to test in `src/`. Add a build command in `build.sh`. Write ava test in `__tests__`. # NEAR JavaScript SDK <p> <a href="https://www.npmjs.com/package/near-sdk-js" target="_blank"> <img alt="Version" src="https://img.shields.io/npm/v/near-sdk-js.svg"> </a> <img src="https://img.shields.io/badge/node-%3E%3D14%20%3C16.6.0%20%7C%7C%20%3E16.6.0-blue.svg" /> <img src="https://img.shields.io/badge/pnpm-%3E%3D7-blue.svg" /> <a href="https://docs.near.org/sdk/js/introduction" target="_blank"> <img alt="Documentation" src="https://img.shields.io/badge/documentation-yes-brightgreen.svg" /> </a> <a href="https://github.com/near/near-sdk-js/blob/develop/LICENSE" target="_blank"> <img alt="License: LICENSE" src="https://img.shields.io/badge/License-MIT-yellow.svg" /> </a> <a href="https://github.com/near/near-sdk-js/blob/develop/LICENSE-APACHE" target="_blank"> <img alt="License: LICENSE" src="https://img.shields.io/badge/License-Apache-yellow.svg" /> </a> </p> A JavaScript library for writing NEAR smart contracts. > **Warning** > > This SDK is currently in **[`Alpha`](https://github.com/near/near-sdk-js/releases/)**. > > The JavaScript runtime has not been fully audited. For creating smart contracts that hold value please use [`near-sdk-rs`](https://github.com/near/near-sdk-rs). > > Help contribute! > > - [Report issues you encounter](https://github.com/near/near-sdk-js/issues) 🐞 > - [Provide suggestions or feedback](https://github.com/near/near-sdk-js/discussions) 💡 > - [Show us what you've built!](https://github.com/near/near-sdk-js/discussions/categories/show-and-tell) 💪 ## Prerequisites - node >=14 <16.6.0 || >16.6.0 - pnpm >=7 ## 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 😎 ## Documentation - [Learn how to use](https://docs.near.org/sdk/js/introduction) the library in your project - Check our [detailed examples and tutorials](https://docs.near.org/tutorials/welcome) - Find [source code examples](./examples) with common use cases - 🏠 Learn more about NEAR on our [Documentation website](https://docs.near.org/) ## Contributing If you are interested in contributing, please look at the [contributing guidelines](CONTRIBUTING.md). - [Report issues you encounter](https://github.com/near/near-sdk-js/issues) 🐞 - [Provide suggestions or feedback](https://github.com/near/near-sdk-js/discussions) 💡 - [Show us what you've built!](https://github.com/near/near-sdk-js/discussions/categories/show-and-tell) 💪 ## License This repository is distributed under the terms of both the [MIT license](https://github.com/near/near-sdk-js/blob/develop/LICENSE) and the [Apache License](https://github.com/near/near-sdk-js/blob/develop/LICENSE-APACHE) (Version 2.0). See [LICENSE](LICENSE) and [LICENSE-APACHE](LICENSE-APACHE) for details. # Gas and size benchmark compare to NEAR-SDK-RS ## Summary NEAR-SDK-JS bundles a bytecode VM with the contract bytecode to a wasm file. Currently, the bytecode VM is the QuickJS runtime with interface to NEAR and the contract bytecode is compiled from JavaScript source code with QuickJS Compiler (QJSC). This results in: - Size of a minimal contract is 500K, which is also the size of the bytecode VM. - Bytecode is more compact than wasm. Complex contract in JS adds less bytes to the equivalent wasm compiled from Rust, but due to the initial 500K size, the result contract is still bigger and within same order of magnitude: several hundred KB. - For contract that bottlenecks at calling the host functions are using similar gas in JS and Rust. - For contract that does a lot of computation in JS, the JS bytecode uses significantly more gas. - For a real world contract, if it doesn't including complex logic in JavaScript, it's usually sufficient, consider the complexity of the near contract standards. - For more complex logic, We suggest to bench the most expensive contract call, including most complex path of cross contract calls, to determine whether it fits 300T Gas limit. ## Detailed gas benchmark ### A minimal contract - RS lowlevel minimal contract - Gas used to convert transaction to receipt: 2.43T - Gas used to execute the receipt (actual contract call): 2.43T - CONTRACT_LOADING_BASE : 0.00004T - CONTRACT_LOADING_BYTES : 0.00005T - Gas used to refund unused gas: 0.22318T - Total gas used: 5.08T - JS lowlevel minimal contract - Gas used to convert transaction to receipt: 2.43T - Gas used to execute the receipt (actual contract call): 7.07T - CONTRACT_LOADING_BASE : 0.00004T - CONTRACT_LOADING_BYTES : 0.11132T - WASM_INSTRUCTION : 4.53T - Gas used to refund unused gas: 0.22318T - Total gas used: 9.72T In the very minimal contract the JS adds about `1.8T` gas. The major difference is loading the QuickJS VM and near-sdk-js uses 4.53T Gas. The 500K contract loading just adds 0.1T Gas. ### A highlevel minimal contract (using nearbindgen) - highlevel-minimal.ava › RS highlevel minimal contract - Gas used to convert transaction to receipt: 2.43T - Gas used to execute the receipt (actual contract call): 2.63T - BASE : 0.79G - CONTRACT_LOADING_BASE : 0.04G - CONTRACT_LOADING_BYTES : 35.46G - READ_CACHED_TRIE_NODE : 4.56G - READ_MEMORY_BASE : 7.83G - READ_MEMORY_BYTE : 0.04G - STORAGE_READ_BASE : 56.36G - STORAGE_READ_KEY_BYTE : 0.15G - STORAGE_WRITE_BASE : 64.2G - STORAGE_WRITE_KEY_BYTE : 0.35G - TOUCHING_TRIE_NODE : 32.2G - WASM_INSTRUCTION : 0.46G - WRITE_MEMORY_BASE : 2.8G - WRITE_MEMORY_BYTE : 0.04G - Gas used to refund unused gas: 223.18G - Total gas used: 5.28T - highlevel-minimal.ava › JS highlevel minimal contract - Gas used to convert transaction to receipt: 2.43T - Gas used to execute the receipt (actual contract call): 8.39T - BASE : 1.59G - CONTRACT_LOADING_BASE : 0.04G - CONTRACT_LOADING_BYTES : 112.03G - READ_CACHED_TRIE_NODE : 6.84G - READ_MEMORY_BASE : 7.83G - READ_MEMORY_BYTE : 0.05G - READ_REGISTER_BASE : 2.52G - READ_REGISTER_BYTE : 0G - STORAGE_READ_BASE : 56.36G - STORAGE_READ_KEY_BYTE : 0.15G - STORAGE_WRITE_BASE : 64.2G - STORAGE_WRITE_KEY_BYTE : 0.35G - STORAGE_WRITE_VALUE_BYTE : 0.06G - TOUCHING_TRIE_NODE : 48.31G - WASM_INSTRUCTION : 5.66T - WRITE_MEMORY_BASE : 5.61G - WRITE_MEMORY_BYTE : 0.05G - WRITE_REGISTER_BASE : 2.87G - WRITE_REGISTER_BYTE : 0.01G - Gas used to refund unused gas: 223.18G - Total gas used: 11.05T JS `@NearBindgen` is more expensive, the major difference is in `WASM_INSTRUCTION`, because `@NearBindgen` does some class, object manipulation work, but Rust `near_bindgen` is a compile time code generation macro. Deduct the 4.5T loading VM and near-sdk-js, it's about 1T gas overhead. ### Low level API - RS lowlevel API contract - Gas used to convert transaction to receipt: 2.43T - Gas used to execute the receipt (actual contract call): 2.53T - BASE : 0.00026T - CONTRACT_LOADING_BASE : 0.00004T - CONTRACT_LOADING_BYTES : 0.00008T - READ_MEMORY_BASE : 0.00522T - READ_MEMORY_BYTE : 0.00008T - STORAGE_WRITE_BASE : 0.0642T - STORAGE_WRITE_KEY_BYTE : 0.0007T - STORAGE_WRITE_VALUE_BYTE : 0.00031T - TOUCHING_TRIE_NODE : 0.0322T - WASM_INSTRUCTION : 0.00002T - Gas used to refund unused gas: 0.22318T - Total gas used: 5.18T - JS lowlevel API contract - Gas used to convert transaction to receipt: 2.43T - Gas used to execute the receipt (actual contract call): 7.8T - BASE : 0.00026T - CONTRACT_LOADING_BASE : 0.00004T - CONTRACT_LOADING_BYTES : 0.11119T - READ_MEMORY_BASE : 0.00522T - READ_MEMORY_BYTE : 0.00008T - STORAGE_WRITE_BASE : 0.0642T - STORAGE_WRITE_EVICTED_BYTE : 0.00032T - STORAGE_WRITE_KEY_BYTE : 0.0007T - STORAGE_WRITE_VALUE_BYTE : 0.00031T - TOUCHING_TRIE_NODE : 0.09661T - WASM_INSTRUCTION : 5.09T - WRITE_REGISTER_BASE : 0.00287T - WRITE_REGISTER_BYTE : 0.00004T - Gas used to refund unused gas: 0.22318T - Total gas used: 10.45T - JS lowlevel API contract, call many - Gas used to convert transaction to receipt: 2.43T - Gas used to execute the receipt (actual contract call): 8.47T - BASE : 0.00265T - CONTRACT_LOADING_BASE : 0.00004T - CONTRACT_LOADING_BYTES : 0.11119T - READ_MEMORY_BASE : 0.0522T - READ_MEMORY_BYTE : 0.00076T - STORAGE_WRITE_BASE : 0.64197T - STORAGE_WRITE_EVICTED_BYTE : 0.00289T - STORAGE_WRITE_KEY_BYTE : 0.00705T - STORAGE_WRITE_VALUE_BYTE : 0.0031T - TOUCHING_TRIE_NODE : 0.04831T - WASM_INSTRUCTION : 5.14T - WRITE_REGISTER_BASE : 0.02579T - WRITE_REGISTER_BYTE : 0.00034T - Gas used to refund unused gas: 0.22318T - Total gas used: 11.12T In this case, JS lowlevel API contract uses same gas in the storage write API part (`STORAGE_WRITE_BASE` / `STORAGE_WRITE_KEY_BYTE` / `STORAGE_WRITE_VALUE_BYTE` ). The major excessive gas is due to the overhead of initialize QuickJS VM and loading near-sdk-js. We can see this more obviously by calling storage write for 10 times ("call many tests" in above). ### Highlevel collection - RS highlevel collection contract - Gas used to convert transaction to receipt: 2.43T - Gas used to execute the receipt (actual contract call): 3.32T - BASE : 3.18G - CONTRACT_LOADING_BASE : 0.04G - CONTRACT_LOADING_BYTES : 70.94G - READ_CACHED_TRIE_NODE : 95.76G - READ_MEMORY_BASE : 26.1G - READ_MEMORY_BYTE : 1.87G - READ_REGISTER_BASE : 5.03G - READ_REGISTER_BYTE : 0.03G - STORAGE_READ_BASE : 112.71G - STORAGE_READ_KEY_BYTE : 3.44G - STORAGE_READ_VALUE_BYTE : 0.19G - STORAGE_WRITE_BASE : 256.79G - STORAGE_WRITE_EVICTED_BYTE : 1.09G - STORAGE_WRITE_KEY_BYTE : 9.23G - STORAGE_WRITE_VALUE_BYTE : 7.75G - TOUCHING_TRIE_NODE : 257.63G - WASM_INSTRUCTION : 16.36G - WRITE_MEMORY_BASE : 8.41G - WRITE_MEMORY_BYTE : 0.74G - WRITE_REGISTER_BASE : 8.6G - WRITE_REGISTER_BYTE : 1.1G - Gas used to refund unused gas: 223.18G - Total gas used: 5.97T - JS highlevel collection contract - Gas used to convert transaction to receipt: 2.43T - Gas used to execute the receipt (actual contract call): 10.06T - BASE : 2.91G - CONTRACT_LOADING_BASE : 0.04G - CONTRACT_LOADING_BYTES : 113.46G - READ_CACHED_TRIE_NODE : 72.96G - READ_MEMORY_BASE : 20.88G - READ_MEMORY_BYTE : 2G - READ_REGISTER_BASE : 5.03G - READ_REGISTER_BYTE : 0.03G - STORAGE_READ_BASE : 112.71G - STORAGE_READ_KEY_BYTE : 3.31G - STORAGE_READ_VALUE_BYTE : 0.53G - STORAGE_WRITE_BASE : 192.59G - STORAGE_WRITE_EVICTED_BYTE : 3.02G - STORAGE_WRITE_KEY_BYTE : 7.96G - STORAGE_WRITE_VALUE_BYTE : 9.49G - TOUCHING_TRIE_NODE : 209.33G - WASM_INSTRUCTION : 6.86T - WRITE_MEMORY_BASE : 8.41G - WRITE_MEMORY_BYTE : 0.9G - WRITE_REGISTER_BASE : 8.6G - WRITE_REGISTER_BYTE : 1.55G - Gas used to refund unused gas: 223.18G - Total gas used: 12.71T JS SDK's collection has about 1T overhead, deduct the 4.5T VM/near-sdk-js loading and 1T `@NearBindgen`. Note this benches the most complicated `UnorderedMap`, which gas usage is strictly greater than the other collections. And the gas used in actual writing the collection to storage is similar (`STORAGE_WRITE_BASE` / `STORAGE_WRITE_KEY_BYTE` / `STORAGE_WRITE_VALUE_BYTE` ). ### Computational expensive contract - JS expensive contract, iterate 20000 times - Gas used to convert transaction to receipt: 2.43T - Gas used to execute the receipt (actual contract call): 123.26T - BASE : 1.85G - CONTRACT_LOADING_BASE : 0.04G - CONTRACT_LOADING_BYTES : 112.09G - READ_CACHED_TRIE_NODE : 4.56G - READ_MEMORY_BASE : 10.44G - READ_MEMORY_BYTE : 0.07G - READ_REGISTER_BASE : 2.52G - READ_REGISTER_BYTE : 0G - STORAGE_READ_BASE : 56.36G - STORAGE_READ_KEY_BYTE : 0.15G - STORAGE_WRITE_BASE : 64.2G - STORAGE_WRITE_KEY_BYTE : 0.35G - STORAGE_WRITE_VALUE_BYTE : 0.06G - TOUCHING_TRIE_NODE : 32.2G - WASM_INSTRUCTION : 120.54T - WRITE_MEMORY_BASE : 5.61G - WRITE_MEMORY_BYTE : 0.07G - WRITE_REGISTER_BASE : 2.87G - WRITE_REGISTER_BYTE : 0.04G - Gas used to refund unused gas: 223.18G - Total gas used: 125.91T - RS expensive contract. iterate 20000 times - Gas used to convert transaction to receipt: 2.43T - Gas used to execute the receipt (actual contract call): 3.01T - BASE : 1.85G - CONTRACT_LOADING_BASE : 0.04G - CONTRACT_LOADING_BYTES : 67.77G - READ_CACHED_TRIE_NODE : 6.84G - READ_MEMORY_BASE : 10.44G - READ_MEMORY_BYTE : 0.06G - READ_REGISTER_BASE : 2.52G - READ_REGISTER_BYTE : 0G - STORAGE_READ_BASE : 56.36G - STORAGE_READ_KEY_BYTE : 0.15G - STORAGE_WRITE_BASE : 64.2G - STORAGE_WRITE_KEY_BYTE : 0.35G - TOUCHING_TRIE_NODE : 48.31G - WASM_INSTRUCTION : 315.17G - WRITE_MEMORY_BASE : 5.61G - WRITE_MEMORY_BYTE : 0.07G - WRITE_REGISTER_BASE : 2.87G - WRITE_REGISTER_BYTE : 0.04G - Gas used to refund unused gas: 223.18G - Total gas used: 5.66T - RS expensive contract. iterate 10000 times - Gas used to convert transaction to receipt: 2.43T - Gas used to execute the receipt (actual contract call): 2.9T - BASE : 2.38G - CONTRACT_LOADING_BASE : 0.04G - CONTRACT_LOADING_BYTES : 67.77G - READ_CACHED_TRIE_NODE : 13.68G - READ_MEMORY_BASE : 10.44G - READ_MEMORY_BYTE : 0.06G - READ_REGISTER_BASE : 5.03G - READ_REGISTER_BYTE : 0G - STORAGE_READ_BASE : 56.36G - STORAGE_READ_KEY_BYTE : 0.15G - STORAGE_WRITE_BASE : 64.2G - STORAGE_WRITE_KEY_BYTE : 0.35G - TOUCHING_TRIE_NODE : 80.51G - WASM_INSTRUCTION : 158.89G - WRITE_MEMORY_BASE : 8.41G - WRITE_MEMORY_BYTE : 0.07G - WRITE_REGISTER_BASE : 8.6G - WRITE_REGISTER_BYTE : 0.04G - Gas used to refund unused gas: 223.18G - Total gas used: 5.56T - RS expensive contract. iterate 100 times - Gas used to convert transaction to receipt: 2.43T - Gas used to execute the receipt (actual contract call): 2.75T - BASE : 2.38G - CONTRACT_LOADING_BASE : 0.04G - CONTRACT_LOADING_BYTES : 67.77G - READ_CACHED_TRIE_NODE : 13.68G - READ_MEMORY_BASE : 10.44G - READ_MEMORY_BYTE : 0.05G - READ_REGISTER_BASE : 5.03G - READ_REGISTER_BYTE : 0G - STORAGE_READ_BASE : 56.36G - STORAGE_READ_KEY_BYTE : 0.15G - STORAGE_WRITE_BASE : 64.2G - STORAGE_WRITE_KEY_BYTE : 0.35G - TOUCHING_TRIE_NODE : 80.51G - WASM_INSTRUCTION : 4.02G - WRITE_MEMORY_BASE : 8.41G - WRITE_MEMORY_BYTE : 0.07G - WRITE_REGISTER_BASE : 8.6G - WRITE_REGISTER_BYTE : 0.03G - Gas used to refund unused gas: 223.18G - Total gas used: 5.4T - JS expensive contract, iterate 100 times - Gas used to convert transaction to receipt: 2.43T - Gas used to execute the receipt (actual contract call): 9.09T - BASE : 2.38G - CONTRACT_LOADING_BASE : 0.04G - CONTRACT_LOADING_BYTES : 112.09G - READ_CACHED_TRIE_NODE : 13.68G - READ_MEMORY_BASE : 10.44G - READ_MEMORY_BYTE : 0.06G - READ_REGISTER_BASE : 5.03G - READ_REGISTER_BYTE : 0G - STORAGE_READ_BASE : 56.36G - STORAGE_READ_KEY_BYTE : 0.15G - STORAGE_READ_VALUE_BYTE : 0.01G - STORAGE_WRITE_BASE : 64.2G - STORAGE_WRITE_EVICTED_BYTE : 0.06G - STORAGE_WRITE_KEY_BYTE : 0.35G - STORAGE_WRITE_VALUE_BYTE : 0.06G - TOUCHING_TRIE_NODE : 80.51G - WASM_INSTRUCTION : 6.3T - WRITE_MEMORY_BASE : 8.41G - WRITE_MEMORY_BYTE : 0.07G - WRITE_REGISTER_BASE : 8.6G - WRITE_REGISTER_BYTE : 0.05G - Gas used to refund unused gas: 223.18G - Total gas used: 11.75T - JS expensive contract, iterate 10000 times - Gas used to convert transaction to receipt: 2.43T - Gas used to execute the receipt (actual contract call): 65.94T - BASE : 2.38G - CONTRACT_LOADING_BASE : 0.04G - CONTRACT_LOADING_BYTES : 112.09G - READ_CACHED_TRIE_NODE : 13.68G - READ_MEMORY_BASE : 10.44G - READ_MEMORY_BYTE : 0.06G - READ_REGISTER_BASE : 5.03G - READ_REGISTER_BYTE : 0G - STORAGE_READ_BASE : 56.36G - STORAGE_READ_KEY_BYTE : 0.15G - STORAGE_READ_VALUE_BYTE : 0.01G - STORAGE_WRITE_BASE : 64.2G - STORAGE_WRITE_EVICTED_BYTE : 0.06G - STORAGE_WRITE_KEY_BYTE : 0.35G - STORAGE_WRITE_VALUE_BYTE : 0.06G - TOUCHING_TRIE_NODE : 80.51G - WASM_INSTRUCTION : 63.15T - WRITE_MEMORY_BASE : 8.41G - WRITE_MEMORY_BYTE : 0.08G - WRITE_REGISTER_BASE : 8.6G - WRITE_REGISTER_BYTE : 0.06G - Gas used to refund unused gas: 223.18G - Total gas used: 68.59T In this case, JS uses much more gas. Because JS Number is object and that's a lot of overhead compare to native integer arithmetic. It's even a lot of overhead compare to native float arithmetic. Also in QuickJS there's no JIT. If your contract does a lot of calculation or complex algorithm in JavaScript, it'd be better to do a similar benchmark. ### Deploy and cross contract call - JS promise batch deploy contract and call - Gas used to convert transaction to receipt: 2.43T - Gas used to execute the receipt (actual contract call): 25.86T - CREATE_ACCOUNT : 0.09961T - DEPLOY_CONTRACT : 3.71T - FUNCTION_CALL : 2.32T - NEW_RECEIPT : 0.10806T - TRANSFER : 0.11512T - BASE : 0.00159T - CONTRACT_LOADING_BASE : 0.00004T - CONTRACT_LOADING_BYTES : 0.22386T - PROMISE_RETURN : 0.00056T - READ_MEMORY_BASE : 0.01566T - READ_MEMORY_BYTE : 1.97T - UTF8_DECODING_BASE : 0.00311T - UTF8_DECODING_BYTE : 0.00525T - WASM_INSTRUCTION : 14.86T - Gas used to execute the cross contract call: 41.9T - BASE : 0.00344T - CONTRACT_LOADING_BASE : 0.00004T - CONTRACT_LOADING_BYTES : 0.11228T - READ_MEMORY_BASE : 0.00261T - READ_MEMORY_BYTE : 0.0005T - READ_REGISTER_BASE : 0.01007T - READ_REGISTER_BYTE : 0T - WASM_INSTRUCTION : 5.47T - WRITE_MEMORY_BASE : 0.01122T - WRITE_MEMORY_BYTE : 0.00014T - WRITE_REGISTER_BASE : 0.01146T - WRITE_REGISTER_BYTE : 0.00019T - Gas used to refund unused gas for cross contract call: 0.22318T - Gas used to refund unused gas: 0.22318T - Total gas used: 70.63T - RS promise batch deploy contract and call - Gas used to convert transaction to receipt: 2.43T - Gas used to execute the receipt (actual contract call): 10.89T - CREATE_ACCOUNT : 0.09961T - DEPLOY_CONTRACT : 3.71T - FUNCTION_CALL : 2.32T - NEW_RECEIPT : 0.10806T - TRANSFER : 0.11512T - BASE : 0.00159T - CONTRACT_LOADING_BASE : 0.00004T - CONTRACT_LOADING_BYTES : 0.11283T - PROMISE_RETURN : 0.00056T - READ_MEMORY_BASE : 0.01566T - READ_MEMORY_BYTE : 1.97T - UTF8_DECODING_BASE : 0.00311T - UTF8_DECODING_BYTE : 0.00525T - WASM_INSTRUCTION : 0.00038T - Gas used to execute the cross contract call: 41.9T - BASE : 0.00344T - CONTRACT_LOADING_BASE : 0.00004T - CONTRACT_LOADING_BYTES : 0.11228T - READ_MEMORY_BASE : 0.00261T - READ_MEMORY_BYTE : 0.0005T - READ_REGISTER_BASE : 0.01007T - READ_REGISTER_BYTE : 0T - WASM_INSTRUCTION : 5.47T - WRITE_MEMORY_BASE : 0.01122T - WRITE_MEMORY_BYTE : 0.00014T - WRITE_REGISTER_BASE : 0.01146T - WRITE_REGISTER_BYTE : 0.00019T - Gas used to refund unused gas for cross contract call: 0.22318T - Gas used to refund unused gas: 0.22318T - Total gas used: 55.67T In this test, we use a JS contract and RS contract to both deploy a JS contract and cross contract call this newly deployed contract. We can see the gas to do the cross contract call is the same. JS SDK has a `~10T` overhead to parse a `~500K` contract in byte. This is because JS, either represent code in Uint8Array or string has some overhead while rust compiler can directly turn it into data section in wasm. In practice, a 10T overhead for a one time contract deploy is not a big deal. ## Tips to do your own benchmark If the above cases don't cover use case or you have a complex algorithm to implement in JavaScript, it's a good idea to benchmark your specific algorithm before choose near-sdk-js for your project. You don't have to implement the exact algorithm to estimate the gas usage. Instead, you can find out the most expensive execution path of the algorithm, and estimate it by using the upper bound. For example, store the biggest possible objects into the collection and iterate for most possible times. Then goes to write the benchmark and the total gas cannot be more than 300T to be a valid contract. Also, if it has cross contract call, make sure the total gas, that's a sum of all cross contract calls, is less than 300T. To add your benchmark, write a one function contract of your most expensive operation. And write a test to call this function. If it doesn't involve cross contract call or promises, creating such test is simple. You can refer to `bench/src/expensive-calc.js` and `bench/__tests__/test-expensive-calc.ava.js` on how to write such test and print the gas breakdown. If it involves create promises or cross contract calls, printing the gas breakdown is a little bit more complex, you can refer to `bench/__tests__/test-deploy-contract.ava.js` for the recipe. ## Details of size benchmark ### JS Contract ``` -rwxrwxr-x 1 bo bo 1009K Feb 9 10:49 ./build/deploy-contract.wasm -rwxrwxr-x 1 bo bo 506K Feb 8 12:11 ./build/expensive-calc.wasm -rwxrwxr-x 1 bo bo 512K Feb 7 15:57 ./build/highlevel-collection.wasm -rwxrwxr-x 1 bo bo 505K Feb 7 10:53 ./build/highlevel-minimal.wasm -rwxrwxr-x 1 bo bo 502K Feb 10 11:32 ./build/lowlevel-api.wasm -rwxrwxr-x 1 bo bo 502K Feb 10 11:47 ./build/lowlevel-minimal.wasm ``` ### Rust Contract ``` -rwxrwxr-x 1 bo bo 509K Feb 10 10:02 ./res/deploy_contract.wasm -rwxrwxr-x 1 bo bo 306K Feb 8 12:18 ./res/expensive_calc.wasm -rwxrwxr-x 1 bo bo 320K Feb 8 11:26 ./res/highlevel_collection.wasm -rwxrwxr-x 1 bo bo 160K Feb 7 10:51 ./res/highlevel_minimal.wasm -rwxrwxr-x 1 bo bo 387 Feb 7 11:56 ./res/lowlevel_api.wasm -rwxrwxr-x 1 bo bo 219 Feb 7 10:33 ./res/lowlevel_minimal.wasm ``` ## Appendix - Source code of the rust benchmark: https://github.com/near/sdk-rs-gas-benchmark
mehmetlevent_near_todo-crud
README.md asconfig.json assembly as_types.d.ts index.ts model.ts tsconfig.json index.html package.json tests index.js
# near_todo-crud patika.dev
gnoblin_roketo-hackathon-deblockle
Assets DampedSpringMotionCopier Code DampedSpringMotionCopier.Utils.cs DampedSpringMotionCopier.cs TooltipAttribute.cs Docs Html DampedSpringMotionCopier.html Scripts ActionProcessors CubeAction.cs DiagonalMoveAction.cs SideMoveAction.cs CubeActionsPack.cs CubeDataPack.cs CubePlacer.cs Gameplay ActionType.cs CubeRotator.cs GameCube.cs ServerDataCubeRotator.cs Managers FieldProcessor.cs GameProvider.cs InputManager.cs JSBackend.cs JSFunctions.cs UI EnterScreen.cs GameScreen.cs InputScreen.cs SwipeInfo.cs README.md frontend Build Builds.framework.js Builds.loader.js TemplateData style.css css styles.css index2.html js index.js
# roketo-hackathon-deblockle Unity3d webgl client for Deblockle game (based on awesome https://github.com/uz0/lab2-vdikan-near-deblockle smart-contracts) Video (showing the fresh version of the gameplay): https://user-images.githubusercontent.com/639995/188195681-000b0e63-94b3-4222-aa54-0778eac70a67.mp4 Presentation: https://docs.google.com/presentation/d/1nQ_HPZU5ApasSOPYZY3grBk6u4I-cAoiqVNeKhRLluY/edit?usp=sharing Demo: no public demo yet :) (something broke down in unity<->web integration and more time was needed to debug) Todo: 1. find the bug why the build stopped working. 2. fix the list of external assets so the whole project can be open sourced.
near_near-abi-client-rs
.github workflows release-plz.yml test.yml CHANGELOG.md Cargo.toml README.md examples delegator-generation Cargo.toml build.rs src adder.json lib.rs tests mod.rs delegator-macro Cargo.toml src adder.json lib.rs tests mod.rs near-abi-client-impl CHANGELOG.md Cargo.toml README.md src lib.rs near-abi-client-macros CHANGELOG.md Cargo.toml README.md src lib.rs near-abi-client CHANGELOG.md Cargo.toml README.md src lib.rs tests adder.json mod.rs res adder.json
<!-- markdownlint-disable MD014 --> <div align="center"> <h1><code>near-abi-client-rs</code></h1> <p> <strong>Library to generate Rust client code with <a href="https://github.com/near/workspaces-rs">workspaces-rs</a> from <a href="https://github.com/near/abi">ABI schemas</a> on NEAR</strong> </p> <p> <a href="https://github.com/near/near-abi-client-rs/actions/workflows/test.yml?query=branch%3Amain"><img src="https://github.com/near/near-abi-client-rs/actions/workflows/test.yml/badge.svg" alt="Github CI Build" /></a> <a href="https://crates.io/crates/near-abi-client"><img src="https://img.shields.io/crates/v/near-abi-client.svg?style=flat-square" alt="Crates.io version" /></a> <a href="https://crates.io/crates/near-abi-client"><img src="https://img.shields.io/crates/d/near-abi-client.svg?style=flat-square" alt="Downloads" /></a> </p> </div> ## Release notes **Release notes and unreleased changes can be found in the [CHANGELOG](CHANGELOG.md)** ## Usage This crate supports two sets of APIs for users with different needs: * **Macro-driven**. Gives you a client in a single macro invocation. * **Generation-based**. Gives you more control and is transparent about what code you end up using, but requires more setup. ### Macro API Checkout the [`delegator-macro`](https://github.com/near/near-abi-client-rs/tree/main/examples/delegator-macro) example for a standalone project using macro API to get a client and use it. To generate a struct named `ClientName` based on ABI located at `path/to/abi.json` (relative to the current file's directory): ```rust mod mymod { near_abi_client::generate!(ClientName for "path/to/abi.json"); } ``` Placing the macro invocation inside a `mod` section is optional, but helps reducing unexpected behaviors such as name clashes. Now, assuming you have a `contract: near_workspaces::Contract` deployed, you can make a call like this: ```rust let contract = mymod::ClientName { contract }; let res = contract .my_method_name(arg1, arg2) .await?; ``` ### Generation API Checkout the [`delegator-generation`](https://github.com/near/near-abi-client-rs/tree/main/examples/delegator-generation) example for a standalone project using generation API to generate a client and use it. First, we need our package to have a `build.rs` file that runs the generation step. The following snippet will generate the client in `abi.rs` under `path/to/out/dir`: ```rust fn main() -> anyhow::Result<()> { near_abi_client::Generator::new("path/to/out/dir".into()) .file("path/to/abi.json") .generate()?; Ok(()) } ``` The resulting file, however, is not included in your source set by itself. You have to include it manually; the recommended way is to create a mod with a custom path: ``` #[path = "path/to/out/dir/abi.rs"] mod mymod; ``` Now, assuming you have a `contract: near_workspaces::Contract` deployed, you can make a call like this: ```rust let contract = mymod::AbiClient { contract }; let res = contract .my_method_name(arg1, arg2) .await?; ``` Feel free to explore what other methods `Generator` has to customize the resulting code (e.g. client struct name). ## Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as below, without any additional terms or conditions. ## License Licensed under either of * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>) * MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>) at your option. <!-- markdownlint-disable MD014 --> <div align="center"> <h1><code>near-abi-client-rs</code></h1> <p> <strong>Library to generate Rust client code with <a href="https://github.com/near/workspaces-rs">workspaces-rs</a> from <a href="https://github.com/near/abi">ABI schemas</a> on NEAR</strong> </p> <p> <a href="https://github.com/near/near-abi-client-rs/actions/workflows/test.yml?query=branch%3Amain"><img src="https://github.com/near/near-abi-client-rs/actions/workflows/test.yml/badge.svg" alt="Github CI Build" /></a> <a href="https://crates.io/crates/near-abi-client"><img src="https://img.shields.io/crates/v/near-abi-client.svg?style=flat-square" alt="Crates.io version" /></a> <a href="https://crates.io/crates/near-abi-client"><img src="https://img.shields.io/crates/d/near-abi-client.svg?style=flat-square" alt="Downloads" /></a> </p> </div> ## Release notes **Release notes and unreleased changes can be found in the [CHANGELOG](CHANGELOG.md)** ## Usage This crate supports two sets of APIs for users with different needs: * **Macro-driven**. Gives you a client in a single macro invocation. * **Generation-based**. Gives you more control and is transparent about what code you end up using, but requires more setup. ### Macro API Checkout the [`delegator-macro`](https://github.com/near/near-abi-client-rs/tree/main/examples/delegator-macro) example for a standalone project using macro API to get a client and use it. To generate a struct named `ClientName` based on ABI located at `path/to/abi.json` (relative to the current file's directory): ```rust mod mymod { near_abi_client::generate!(ClientName for "path/to/abi.json"); } ``` Placing the macro invocation inside a `mod` section is optional, but helps reducing unexpected behaviors such as name clashes. Now, assuming you have a `contract: near_workspaces::Contract` deployed, you can make a call like this: ```rust let contract = mymod::ClientName { contract }; let res = contract .my_method_name(arg1, arg2) .await?; ``` ### Generation API Checkout the [`delegator-generation`](https://github.com/near/near-abi-client-rs/tree/main/examples/delegator-generation) example for a standalone project using generation API to generate a client and use it. First, we need our package to have a `build.rs` file that runs the generation step. The following snippet will generate the client in `abi.rs` under `path/to/out/dir`: ```rust fn main() -> anyhow::Result<()> { near_abi_client::Generator::new("path/to/out/dir".into()) .file("path/to/abi.json") .generate()?; Ok(()) } ``` The resulting file, however, is not included in your source set by itself. You have to include it manually; the recommended way is to create a mod with a custom path: ``` #[path = "path/to/out/dir/abi.rs"] mod mymod; ``` Now, assuming you have a `contract: near_workspaces::Contract` deployed, you can make a call like this: ```rust let contract = mymod::AbiClient { contract }; let res = contract .my_method_name(arg1, arg2) .await?; ``` Feel free to explore what other methods `Generator` has to customize the resulting code (e.g. client struct name). ## Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as below, without any additional terms or conditions. ## License Licensed under either of * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>) * MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>) at your option. <!-- markdownlint-disable MD014 --> <div align="center"> <h1><code>near-abi-client-rs</code></h1> <p> <strong>Library to generate Rust client code with <a href="https://github.com/near/workspaces-rs">workspaces-rs</a> from <a href="https://github.com/near/abi">ABI schemas</a> on NEAR</strong> </p> <p> <a href="https://github.com/near/near-abi-client-rs/actions/workflows/test.yml?query=branch%3Amain"><img src="https://github.com/near/near-abi-client-rs/actions/workflows/test.yml/badge.svg" alt="Github CI Build" /></a> <a href="https://crates.io/crates/near-abi-client"><img src="https://img.shields.io/crates/v/near-abi-client.svg?style=flat-square" alt="Crates.io version" /></a> <a href="https://crates.io/crates/near-abi-client"><img src="https://img.shields.io/crates/d/near-abi-client.svg?style=flat-square" alt="Downloads" /></a> </p> </div> ## Release notes **Release notes and unreleased changes can be found in the [CHANGELOG](CHANGELOG.md)** ## Usage This crate supports two sets of APIs for users with different needs: * **Macro-driven**. Gives you a client in a single macro invocation. * **Generation-based**. Gives you more control and is transparent about what code you end up using, but requires more setup. ### Macro API Checkout the [`delegator-macro`](https://github.com/near/near-abi-client-rs/tree/main/examples/delegator-macro) example for a standalone project using macro API to get a client and use it. To generate a struct named `ClientName` based on ABI located at `path/to/abi.json` (relative to the current file's directory): ```rust mod mymod { near_abi_client::generate!(ClientName for "path/to/abi.json"); } ``` Placing the macro invocation inside a `mod` section is optional, but helps reducing unexpected behaviors such as name clashes. Now, assuming you have a `contract: near_workspaces::Contract` deployed, you can make a call like this: ```rust let contract = mymod::ClientName { contract }; let res = contract .my_method_name(arg1, arg2) .await?; ``` ### Generation API Checkout the [`delegator-generation`](https://github.com/near/near-abi-client-rs/tree/main/examples/delegator-generation) example for a standalone project using generation API to generate a client and use it. First, we need our package to have a `build.rs` file that runs the generation step. The following snippet will generate the client in `abi.rs` under `path/to/out/dir`: ```rust fn main() -> anyhow::Result<()> { near_abi_client::Generator::new("path/to/out/dir".into()) .file("path/to/abi.json") .generate()?; Ok(()) } ``` The resulting file, however, is not included in your source set by itself. You have to include it manually; the recommended way is to create a mod with a custom path: ``` #[path = "path/to/out/dir/abi.rs"] mod mymod; ``` Now, assuming you have a `contract: near_workspaces::Contract` deployed, you can make a call like this: ```rust let contract = mymod::AbiClient { contract }; let res = contract .my_method_name(arg1, arg2) .await?; ``` Feel free to explore what other methods `Generator` has to customize the resulting code (e.g. client struct name). ## Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as below, without any additional terms or conditions. ## License Licensed under either of * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>) * MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>) at your option. <!-- markdownlint-disable MD014 --> <div align="center"> <h1><code>near-abi-client-rs</code></h1> <p> <strong>Library to generate Rust client code with <a href="https://github.com/near/workspaces-rs">workspaces-rs</a> from <a href="https://github.com/near/abi">ABI schemas</a> on NEAR</strong> </p> <p> <a href="https://github.com/near/near-abi-client-rs/actions/workflows/test.yml?query=branch%3Amain"><img src="https://github.com/near/near-abi-client-rs/actions/workflows/test.yml/badge.svg" alt="Github CI Build" /></a> <a href="https://crates.io/crates/near-abi-client"><img src="https://img.shields.io/crates/v/near-abi-client.svg?style=flat-square" alt="Crates.io version" /></a> <a href="https://crates.io/crates/near-abi-client"><img src="https://img.shields.io/crates/d/near-abi-client.svg?style=flat-square" alt="Downloads" /></a> </p> </div> ## Release notes **Release notes and unreleased changes can be found in the [CHANGELOG](CHANGELOG.md)** ## Usage This crate supports two sets of APIs for users with different needs: * **Macro-driven**. Gives you a client in a single macro invocation. * **Generation-based**. Gives you more control and is transparent about what code you end up using, but requires more setup. ### Macro API Checkout the [`delegator-macro`](https://github.com/near/near-abi-client-rs/tree/main/examples/delegator-macro) example for a standalone project using macro API to get a client and use it. To generate a struct named `ClientName` based on ABI located at `path/to/abi.json` (relative to the current file's directory): ```rust mod mymod { near_abi_client::generate!(ClientName for "path/to/abi.json"); } ``` Placing the macro invocation inside a `mod` section is optional, but helps reducing unexpected behaviors such as name clashes. Now, assuming you have a `contract: near_workspaces::Contract` deployed, you can make a call like this: ```rust let contract = mymod::ClientName { contract }; let res = contract .my_method_name(arg1, arg2) .await?; ``` ### Generation API Checkout the [`delegator-generation`](https://github.com/near/near-abi-client-rs/tree/main/examples/delegator-generation) example for a standalone project using generation API to generate a client and use it. First, we need our package to have a `build.rs` file that runs the generation step. The following snippet will generate the client in `abi.rs` under `path/to/out/dir`: ```rust fn main() -> anyhow::Result<()> { near_abi_client::Generator::new("path/to/out/dir".into()) .file("path/to/abi.json") .generate()?; Ok(()) } ``` The resulting file, however, is not included in your source set by itself. You have to include it manually; the recommended way is to create a mod with a custom path: ``` #[path = "path/to/out/dir/abi.rs"] mod mymod; ``` Now, assuming you have a `contract: near_workspaces::Contract` deployed, you can make a call like this: ```rust let contract = mymod::AbiClient { contract }; let res = contract .my_method_name(arg1, arg2) .await?; ``` Feel free to explore what other methods `Generator` has to customize the resulting code (e.g. client struct name). ## Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as below, without any additional terms or conditions. ## License Licensed under either of * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>) * MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>) at your option.
mmurat_new_simple
README.md asconfig.json assembly index.ts tsconfig.json index.js package.json tests index.js
hdriqi_piece-app
README.md babel.config.js package.json postcss.config.js src App.js assets how-it-works.svg components Activity.js Footer.js ImgCrop.js Loading.js Nav.js ProfileCard.js config.js index.html index.js near.js pages Explore.js Home.js Login.js Profile.js ProfileBalance.js ProfileEdit.js ProfileReward.js skynet.js store.js styles index.css tailwind.css utils.js tailwind.config.js
Piece Interface ================== The interface for Piece Protocol, An incentivized protocol both for creators and supporters. Piece Protocol is built on top of NEAR blockchain and Sia decentralized storage. [Try Piece on Sia](https://siasky.net/_AUBQQJF4mYSB2iqUx30ZA6U4iAMmezZDFeVMERZXXAXZQ) Video Demo ========== [<img src="https://i.ibb.co/TtDZfms/5f7324b0dd22apiece-thumbnail.png">](https://www.loom.com/share/af2f558cdd2b43e9a8dae1a5d968447f) 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 start` (see `package.json` for a full list of `scripts` you can run with `yarn`) Smart Contract ============== The smart contract was deployed at [dev-v1.piece.testnet](https://explorer.testnet.near.org/accounts/dev-v1.piece.testnet). You can read the source code for the smart contract [here](https://github.com/hdriqi/piece-protocol).
Mrquinnd_nfnft
401.html README.md backup.html counter.html css normalize.css spamnft.webflow.css webflow.css div.css documents angry_face.json idx.html imageClick.js images elon.json index.html js webflow.js
# nfnft - non-functional-non-fungible-token Counter component using JS + Jquery to perform asynchronous updates of an NFT infection counter.
lawcia_near-sweet-nfts
README.md contract Cargo.toml README.md build.sh src approval.rs enumeration.rs internal.rs lib.rs metadata.rs mint.rs nft_core.rs royalty.rs frontend README.md package.json public index.html manifest.json robots.txt src App.css components Banner.css Gallery.css Login.css Traits.css constants.ts index.css model.ts near config.ts react-app-env.d.ts reportWebVitals.ts setupTests.ts utils.ts tsconfig.json
# RUST Contract ## Scripts Assumes you have a bash terminal - Build the contract `sh build.sh` or `bash build.sh` # NEAR Sweet NFTs Challenge 2: NEAR NFT Smart Contract This website is a gallery for the Sweet NFTs on NEAR. Hosted on Netlify: https://sweet-nfts-testnet-near.netlify.app/ Users can login using their NEAR Wallet, then they will be directed to see a list of NFTs. They can select an NFT to Mint. Minted NFTs will then become disabled, preventing the user from minting. After navigating to https://wallet.testnet.near.org/?tab=collectibles, the user should then see their newly minted NFT in their collection. This contract has been deployed on the testnet ## Tech Stack - React - Rust - NEAR API # 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/).
near_jsonrpc-benchmark
.github ISSUE_TEMPLATE BOUNTY.yml README.md benchmark.yml run.sh view_access_key_list.yml view_account.yml view_call.yml view_state.yml
# NEAR JSON RPC benchmark ## Install [`drill`](https://github.com/fcsonline/drill) with dependencies and run the benchmark * Install [`cargo`](https://doc.rust-lang.org/cargo/getting-started/installation.html) ```bash $ curl https://sh.rustup.rs -sSf | sh $ source $HOME/.cargo/env ``` * Install dependencies ```bash $ sudo apt install -y build-essential pkg-config libssl-dev ``` * Clone this repo ```bash $ git clone https://github.com/near/jsonrpc-benchmark ``` * Navigate to the folder and run `drill` ```bash $ cd jsonrpc-benchmark/ $ chmod a+x run.sh $ URL="http://localhost:3030" ./run.sh # to run each method sequentially $ drill --benchmark benchmark.yml --stats # to run the methods concurrently ``` ## Reasoning for chosen methods to benchmark For the benchmarking we decided to go with `testnet`. We have spin up the node on GCP `e2-standard-8` (which is recommended machine type for the rpc nodes). Before writing a drill config we've investigated (manually) the logs of nginx on a few nodes to find out what kind of methods are the most frequent. Despite the "easy" methods (like `block`, `chunk`) there were some `query` view calls: * `view_state` * `view_account` * `view_access_key_list` It was decided to go with those three. Also we've added `view_call` to call view method of some contract. We choose an existing account with contract and small (not empty) state. During the benchmark we're sending each of the four query requests and **the main metric currently is requests per second (rps)** ## Benchmark results we've got ### Request sent from another machine in the same region ``` View call method Total requests 3000 View call method Successful requests 3000 View call method Failed requests 0 View call method Median time per request 16ms View call method Average time per request 20ms View call method Sample standard deviation 8ms Time taken for tests 15.7 seconds Total requests 3000 Successful requests 3000 Failed requests 0 Requests per second 191.18 [#/sec] Median time per request 16ms Average time per request 20ms Sample standard deviation 8ms Concurrency 4 Iterations 3000 Rampup 5 Base URL http://34.91.236.50:3030 View access key list Total requests 3000 View access key list Successful requests 3000 View access key list Failed requests 0 View access key list Median time per request 9ms View access key list Average time per request 9ms View access key list Sample standard deviation 6ms Time taken for tests 7.6 seconds Total requests 3000 Successful requests 3000 Failed requests 0 Requests per second 393.99 [#/sec] Median time per request 9ms Average time per request 9ms Sample standard deviation 6ms Concurrency 4 Iterations 3000 Rampup 5 Base URL http://34.91.236.50:3030 View account Total requests 3000 View account Successful requests 3000 View account Failed requests 0 View account Median time per request 8ms View account Average time per request 9ms View account Sample standard deviation 2ms Time taken for tests 7.5 seconds Total requests 3000 Successful requests 3000 Failed requests 0 Requests per second 398.99 [#/sec] Median time per request 8ms Average time per request 9ms Sample standard deviation 2ms Concurrency 4 Iterations 3000 Rampup 5 Base URL http://34.91.236.50:3030 View state Total requests 3000 View state Successful requests 3000 View state Failed requests 0 View state Median time per request 9ms View state Average time per request 9ms View state Sample standard deviation 6ms Time taken for tests 7.9 seconds Total requests 3000 Successful requests 3000 Failed requests 0 Requests per second 380.32 [#/sec] Median time per request 9ms Average time per request 9ms Sample standard deviation 6ms ``` ### Request sent from the same machine (locally) ``` View call method Total requests 3000 View call method Successful requests 3000 View call method Failed requests 0 View call method Median time per request 8ms View call method Average time per request 8ms View call method Sample standard deviation 2ms Time taken for tests 7.1 seconds Total requests 3000 Successful requests 3000 Failed requests 0 Requests per second 419.84 [#/sec] Median time per request 8ms Average time per request 8ms Sample standard deviation 2ms Concurrency 4 Iterations 3000 Rampup 5 Base URL http://127.0.0.1:3030 View access key list Total requests 3000 View access key list Successful requests 3000 View access key list Failed requests 0 View access key list Median time per request 1ms View access key list Average time per request 1ms View access key list Sample standard deviation 1ms Time taken for tests 1.6 seconds Total requests 3000 Successful requests 3000 Failed requests 0 Requests per second 1894.98 [#/sec] Median time per request 1ms Average time per request 1ms Sample standard deviation 1ms Concurrency 4 Iterations 3000 Rampup 5 Base URL http://127.0.0.1:3030 View account Total requests 3000 View account Successful requests 3000 View account Failed requests 0 View account Median time per request 1ms View account Average time per request 1ms View account Sample standard deviation 1ms Time taken for tests 1.4 seconds Total requests 3000 Successful requests 3000 Failed requests 0 Requests per second 2079.54 [#/sec] Median time per request 1ms Average time per request 1ms Sample standard deviation 1ms Concurrency 4 Iterations 3000 Rampup 5 Base URL http://127.0.0.1:3030 View state Total requests 3000 View state Successful requests 3000 View state Failed requests 0 View state Median time per request 1ms View state Average time per request 1ms View state Sample standard deviation 1ms Time taken for tests 1.8 seconds Total requests 3000 Successful requests 3000 Failed requests 0 Requests per second 1680.33 [#/sec] Median time per request 1ms Average time per request 1ms Sample standard deviation 1ms ```
mhassanist_nftizer-nft-minter-smart-contract-near-protocol
Cargo.toml README.md src lib.rs
# NFTizer | NFT Minter on NEAR Protocol This is a ready-to-use smart contract for minting NFTs on NEAR blockchain. Below is hwo you may use it. I'm assuming you already familiar with NEAR and have installed Rust blockchain and near-cli. ## Smart Contract Sample Usage ### Build ``` env 'RUSTFLAGS=-C link-arg=-s' cargo build --target wasm32-unknown-unknown --release ``` ### Deploy ``` $ near deploy --wasmFile target/wasm32-unknown-unknown/release/near_spring_nft.wasm --accountId nftizer.mhassanist.testnet ``` ### Intialize the contract (call one time only) ``` $ near call nftizer.mhassanist.testnet new_default_meta '{"owner_id": "'mhassanist.testnet'"}' --accountId mhassanist.testnet ``` ### Minting The `receiver_id` param is the account that this minted NFT goes to. ``` near call nftizer.mhassanist.testnet nft_mint '{"token_id": "Yom3", "receiver_id": "'msaudi.testnet'", "token_metadata": { "title": "KidPhotos3", "description": "Beautiful Kids NFTs", "media": "https://bafybeiab33alpecxhqr4bciie7jfgwcgbc7yj27utdrcfa7uzx46mjff5q.ipfs.nftstorage.link/", "copies": 1}}' --accountId mhassanist.testnet --deposit 0.1 ```
midou10_Near_Token_Contract
.gitpod.yml README.md as-pect.config.js asconfig.js assembly __tests__ as-pect.d.ts context.json main.spec.ts as_types.d.ts main.ts model.ts tsconfig.json babel.config.json dist gray_near_logo.f4fe4645.svg index.html logo.b37d81ec.svg near.45fb95a6.svg src.e31bb0bc.css package.json src App.css App.js App.prev.css App.prev.js App.test.js __mocks__ fileMock.js assets gray_near_logo.svg logo.svg near.svg config.js context Auth.js data.js index.html index.js jest.init.js main.test.js utils api.js wallet login index.html
## Near decentralized app: token delegation app ### Requirements ##### IMPORTANT: Make sure you have the latest version of NEAR Shell and Node Version > 10.x 1. [Node.js](https://nodejs.org/en/download/package-manager/) 2. (optional) near-shell ``` npm i -g near-shell ``` ### To run on NEAR testnet ```bash npm install && npm dev ``` with yarn: ```bash yarn && yarn dev ``` Navigate to http://localhost:1234 NOTE: Both contract and client-side code will auto-reload once you change source files.
happy-zhangbo_near-status-one
.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 integration-tests rs Cargo.toml src tests.rs ts main.ava.ts package.json src lib.rs
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 ```
NEAR-BRASIL_ref
.vscode launch.json README.md backend .eslintrc.js docker-compose.db.yml docker-compose.migrate.yml docker-compose.studio.yml docker-compose.yml near_cli_examples croncat.sh ref-finance.sh nest-cli.json package-lock.json package.json prisma migrations 20210825064539_init migration.sql 20210825075802_token migration.sql 20210825080946_token2 migration.sql 20210825100231_token_icon migration.sql 20210825100746_pool migration.sql 20210825110408_pool2 migration.sql 20210825120632_shares migration.sql 20210825203311_symbol_in_tokenpool migration.sql 20210825205757_constrains migration.sql 20210826052733_volume migration.sql 20210830124958_decimals_in_pool migration.sql 20210831042116_liquidity migration.sql 20210831044217_chain_updates migration.sql 20210831044616_chain_updates migration.sql 20210831045947_new_chain_update_type migration.sql 20210831111604_timestamp migration.sql 20210831122328_decimals migration.sql 20210831124711_big_int migration.sql 20210831132704_datetime migration.sql 20210831132956_private_key migration.sql 20210901040902_timestamp_as_string migration.sql 20210901113804_created_at migration.sql 20210901114857_removed_shares migration.sql 20210902044444_history migration.sql 20210902050627_amounts_history migration.sql 20210903043950_farms01 migration.sql 20210903121621_farms01 migration.sql 20210906072545_tvl migration.sql migration_lock.toml seed.ts src app app.controller.spec.ts app.controller.ts app.module.ts app.service.spec.ts app.service.ts chain chain.module.ts chain.service.ts near indexer indexer.module.ts indexer.service.ts near.module.ts near.service.ts near.utils.ts ref.finance config.ts ref.module.ts ref.service.ts types.ts prisma prisma.module.ts prisma.service.ts tasks cron.module.ts cron.service.ts discord.service.ts tasks.module.ts tasks.service.ts configs config.interface.ts config.ts console-apps console-scripts.ts main.ts request-validation.pipe.ts standalone.ts utils.ts test app.e2e-spec.ts app.resolver.e2e-spec.ts jest-e2e.json userful-files polkadot-scripts-snippets.js polkastats.sql tsconfig.build.json tsconfig.json Just in case of auth Ref Finance Tokens Ref Finance Pools FARMS liquidity cron finished tokens cron finished pools cron finished farms cron finished method args events cicd acme.json config.yml docker-compose.yml traefik.yml deploy.sh frontend README.md docker-compose.yml package-lock.json package.json public index.html manifest.json robots.txt src App.css App.js App.test.js AuthProvider.js chain ChainProvider.js hooks useDebounce.js index.css index.js layout appBar.js components charts.js chimp.js index.js index.js layout.js login.js menu.js submenu.js logo.svg pages about.js accounts index.js status components components.js depositsGrid.js farmsGrid.js liquidityGrid.js poolsGrid.js index.js status.js utils.js admin.js change-log.js configuration.js dashboard dashboard.js index.js validators-history.js value-bar.js welcome.js index.js links.js system.js redux actions.js api.js reducers.js sagas.js reportWebVitals.js resources farms.js liquidity.js pools.js tokens.js routes.js setupTests.js utils.js
# Overview Ref Status Explorer and Community Application The application runs at https://ref.nearchaintools.com and is connected to NEAR blockchain mainnet data. Project page with the To-Do section and collected feedback from the community could be found [here](https://imiroslav.notion.site/NearTools-com-for-Ref-Finance-a0ea6c5e68dd4a88acf1c2203e7bcef4) # Instructions ## Backend Installation ### Install Dependencies Install the dependencies for the application: ```bash npm install ``` ### PostgreSQL with Docker Setup a development PostgreSQL with Docker. Follow `.env` which sets the required environments for PostgreSQL such as `POSTGRES_USER`, `POSTGRES_PASSWORD` and `POSTGRES_DB`. Update the variables as you wish and select a strong password. Start the PostgreSQL database ```bash docker-compose -f docker-compose.db.yml up -d # or npm run docker:db ``` ### Prisma Migrate [Prisma Migrate](https://github.com/prisma/prisma2/tree/master/docs/prisma-migrate) is used to manage the schema and migration of the database. Prisma datasource requires an environment variable `DATABASE_URL` for the connection to the PostgreSQL database. It takes variables from [.env](./.env) file which is also used by Prisma Migrate and for seeding the database. You can use [.env.example](./.env.example) to start with. Use Prisma Migrate in your [development environment](https://www.prisma.io/blog/prisma-migrate-preview-b5eno5g08d0b#evolving-the-schema-in-development) to 1. Creates `migration.sql` file 2. Updates Database Schema 3. Generates Prisma Client ```bash npx prisma migrate dev # or npm run migrate:dev ``` If you like to customize your `migration.sql` file run the following command. After making your customizations run `npx prisma migrate dev` to apply it. ```bash npx prisma migrate dev --create-only # or npm run migrate:dev:create ``` If you are happy with your database changes you want to deploy those changes to your [production database](https://www.prisma.io/blog/prisma-migrate-preview-b5eno5g08d0b#applying-migrations-in-production-and-other-environments). Use `prisma migrate deploy` to apply all pending migrations, can also be used in CI/CD pipelines as it works without prompts. ```bash npx prisma migrate deploy # or npm run migrate:deploy ``` ### Seed the database data with this script Execute the script with this command: ```bash npm run seed ``` ### Prisma: Prisma Schema Development Update the Prisma schema `prisma/schema.prisma` and after that run the following two commands: ```bash npx prisma generate # or in watch mode npx prisma generate --watch # or npm run prisma:generate npm run prisma:generate:watch ``` ### Prisma: Prisma Client JS [Prisma Client JS](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client/api) is a type-safe database client auto-generated based on the data model. It could be used for futher development Generate Prisma Client JS by running > **Note**: Every time you update [schema.prisma](prisma/schema.prisma) re-generate Prisma Client JS ```bash npx prisma generate # or npm run prisma:generate ``` ### Start NestJS Server In case you would like to run API , you should deal with NestJS application. ## Docker Nest server is a Node.js application and it is easily [dockerized](https://nodejs.org/de/docs/guides/nodejs-docker-webapp/). See the [Dockerfile](./Dockerfile) on how to build a Docker image of your Nest server. Now to build a Docker image of your own Nest server simply run: ```bash # give your docker image a name docker build -t <your username>/nest-prisma-server . # for example docker build -t nest-prisma-server . ``` After Docker build your docker image you are ready to start up a docker container running the nest server: ```bash docker run -d -t -p 3000:3000 --env-file .env nest-prisma-server ``` Now open up [localhost:3000](http://localhost:3000) to verify that your nest server is running. When you run your NestJS application in a Docker container update your [.env](.env) file ```diff - DB_HOST=localhost # replace with name of the database container + DB_HOST=postgres # Prisma database connection + DATABASE_URL=postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${DB_HOST}:${DB_PORT}/${POSTGRES_DB}?schema=${DB_SCHEMA}&sslmode=prefer ``` If `DATABASE_URL` is missing in the root `.env` file, which is loaded into the Docker container, the NestJS application will exit with the following error: ```bash (node:19) UnhandledPromiseRejectionWarning: Error: error: Environment variable not found: DATABASE_URL. --> schema.prisma:3 | 2 | provider = "postgresql" 3 | url = env("DATABASE_URL") ``` ### Docker Compose You can also setup a the database and Nest application with the docker-compose First prepare `.env.production` file then run ```bash # building new NestJS docker image docker-compose build # or npm run docker:build # start docker-compose docker-compose up -d # or npm run docker ``` **[⬆ back to top](#overview)** # 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)
haardikk21_learnweb3-junior-ceramic
.eslintrc.json README.md next.config.js package-lock.json package.json pages _app.js api hello.js index.js public vercel.svg styles Home.module.css globals.css
# Ceramic ![](https://i.imgur.com/etCAEZi.png) Ceramic is a decentralized data network, that allows for building composable Web3 applications. Since Ceramic decentralizes application databases, application developers can reuse data across applications and make them automatically interoperable. In the course of this article, we will dig deeper into what those statements actually mean, and why decentralized data is important in the first place. ## Web3 and Data In the past few years, we have seen Web3 trends like DeFi, NFTs, and more recently DAOs blow up. Smart contract platforms like Ethereum have shown us that dApps which act as legos, and can be composed together with other dApps to build entirely new dApps have a lot of value. This is particularly highlighted with tokens that build on top of other tokens, DeFi protocols which utilize other DeFi protocols, etc. Ceramic allows you to bring that same type of composability to data on the internet. This can be any kind of data. Profiles, social connections, blog posts, identities, reputation, game assets, etc. This is an abstract concept, and it is a bit tricky to try and define Ceramic Network as a single thing. Similar to Ethereum, which by itself is hard to define (what does it even mean to be a smart contract plaform?), it is easier to understand if we look at specific use cases that Ceramic can enable and examples of a vision for the future. Ethereum is much easier to understand when we look at exact examples like DeFi protocols, NFTs, DAOs etc - the same thinking can be applied while attempting to understand Ceramic. ## Lack of data in Web3 The web3 market right now is mainly comprised of financial applications. Things to do with tokens and digital assets. This is somewhat due to design. Smart contracts are inherently limited in how much data can be stored in them, and there's only so much data functionality that can be built. As we progress and dApps mature, the market demand for building more data-rich applications is increasing. Trends like decentralized social medias, decentralized reputation platforms, decentralized blogs, etc. is taking off, with a lot of technical approaches being taken, but lacking in one aspect or the other. In Web2, these platforms were built as data silos. Your Twitter posts and social connections are locked into the Twitter platform - you cannot transfer your social connections on Twitter to Facebook, you cannot transfer your Twitter posts to Facebook, etc. They are all built as silos. This will change. Ceramic is betting on interoperable applications and interoperable ecosystems being able to outcompete these siloed platforms. ## So... What does Ceramic do? Ceramic is building: 1. A generalized data protocol 2. where data can be modified only by the owner 3. with high volume data processing 4. with global data availability and consistency 5. with support for fast querying 6. with interoperable data across applications 7. and community governance This is a lot. This is also why Ceramic can be tricky to define on it's own. After all, just like Ethereum, it is a generalized protocol, albeit for data. To achieve the true scale and vision of Ceramic, a lot of breakthroughs need to be achieved. If Ceramic is to become the decentralized database of the web, it needs to be able to scale massively - more than any centralized database today as none of them are storing data from the entire internet. Data also needs to be made globally available, and it needs to be ensured that Ceramic node runners make that data available for the rest of the world and don't hijack it. Additionally, not just storage, Ceramic also needs to be fast to query and retrieve data from. Users typically read much more data than they write, so fast reads and queries are extremely important for Ceramic to work at scale. All of this while maintaining a high level of security and privacy over data, and ensuring that it doesn't come crashing down one day. It is helpful to look at specific use cases that can be enabled by Ceramic today and the benefits of having a mutable, decentralized, general purpose data protocol. ## Ceramic Use Cases ### Decentralized Reputation Reputation is highly tied into a person's identity. On Twitter, it's followers and likes. On Instagram, it is the hearts. On Reddit, it's Karma, and on StackOverflow, it's points. In the web3 ecosystem today, dApps can hardly do better than centralized reputation systems like the above examples, with each platform having it's own reputation system. This is largely because storing large amounts of decentralized data that can change over time was not viable. And even if Ethereum Layer 2's were to reduce storage costs massively, what about non-Ethereum chains? What happens to your reputation when you switch to NEAR or Flow or Solana? Enter Ceramic. dApps can use Ceramic's data protocol to build standardized multi-chain reputation systems. A user can connect multiple wallets to their decentralized identity, belong from different blockchains, and data can be written to and updated from the user's decentralized data store on Ceramic. Therefore, regardless of what chain and dApp the user is using, they can carry around their reputation system with them. ### Social Graphs Similar to reputation, your social graph is also heavily centralized in today's world. Your Twitter followers, Facebook friends, LinkedIn connections, and Snapchat buddies are all differently siloed. With censorship increasing on centralized social medias over time, and since social media companies are the biggest in the world with some of them having enough power to manipulate entire national elections, the need for decentralized social media has never been more. However, if we are building decentralized social media, let's try to do better than the old systems. Instead of locking users into a platform, we can actually allow for interoperability and optionality. dApps can follow standardized data models to store posts and social graphs. These social graphs are carried by the user to whatever dApp they want to use. This means products compete on which offers the best experience, not who has the most vendor lock-in. This also allows for smaller players and startups with better products to achieve easier market penetration. They can utilize the underlying data that already exists, and when users sign up on their platform all their data is carried along with them. For bigger players, there can be financial incentives for providing a large amount of data for that datamodel. ### Multi-Wallet and Multi-Chain Identity You could extrapolate the decentralized reputation use case to achieve generalized multi-wallet and multi-chain identity for users. Instead of tying up data in smart contracts or offchain based on wallet addresses, data can be tied up to a user's decentralized identity which can be controlled by multiple wallets across multiple chains. This way, multi-chain dApps can have a decentralized, yet single, source of truth for a user's data. ## Ceramic's Multi Chain Architecture At the lowest level, there is a decentralized identity. The most common approach to decentralized identities on Ceramic is something called a **3ID** (Three ID) - named after the team behind Ceramic Network called 3Box Labs. A user can link multiple wallets from multiple chains to a single 3ID. Currently, Ceramic supports more than 10 blockchains, and is continually adding support for more. 3ID's can own data on Ceramic Network. Data on Ceramic is referred to as **Streams**. Each stream therefore has an owner (or multiple owners). Streams have unique **StreamID**'s, which remain the same over the lifetime of the stream. 3ID's can modify and update the contents of a Stream that they have ownership on. Streams have a **genesis** state, which is the initial data the Stream was created with. Following the genesis state, users can create **commits** on Streams, which represent modifications to the data. The latest state of a Stream can be computed by starting from the genesis state and applying all the commits one by one. The latest state is also referred to as the **tip** of a stream. ## Using Ceramic Ceramic provides a suite of high-level and low-level libraries and SDK's to work with, depending on the use case. For common use cases, developers can use the high-level SDK - Self.ID - which abstracts away most of the complexities of working with 3ID's and Streams. For complex or customized use cases, developers can work with a lower-level Ceramic HTTP Client, which connects to a Ceramic node they can run on their own (or the public nodes), and manage 3ID's and Stream data manually. For the purposes of this tutorial, we will stick with the Self.ID high-level SDK, as otherwise this tutorial will become extremely large. If you're interested in digging deeper, do check out the *Recommended Resources* section below. ### Self.ID Self.ID is a single, high level, library that encapsulates 3ID accounts, creating and setting up a 3ID, underlying calls to Ceramic nodes, all in a single package optimized to work in a browser. The SDK also includes popular use cases like multi-chain user profiles built in, which makes it very easy for developers to retrieve and store multi-chain data linked to a 3ID. ## BUIDL We will create a simple Next.js application, which uses Self.ID. It will allow users to login to the website using their wallet of choice, which will be linked to their 3ID. Then, we will allow the user to write some data to their decentralized profile, and be able to retrieve it from the Ceramic Network. For verification of this level, we will ask you to enter your profile's StreamID at the end. - Let's get started by creating a new `next` app. Run the following command to create a new Next.js application inside a folder named `Ceramic-Tutorial` ```bash npx create-next-app@latest Ceramic-Tutorial ``` and press `Enter` for all the question prompts. This should create the `Ceramic-Tutorial` folder and setup the `next` app inside it. It will also initialize a git repository you can push to GitHub after making changes. - Let's now install the Self.ID npm packages to get started. From inside the `Ceramic-Tutorial` folder, run the following in your terminal ```bash npm install @self.id/react @self.id/web ``` - Let's also install the `ethers` and `web3modal` packages that we will be using to support wallet connections ```bash npm install ethers web3modal ``` - Open up the `Ceramic-Tutorial` folder in your text editor of choice, and let's get to coding. - The first thing we need to do is add Self.ID's Provider to the application. The SDK exposes a `Provider` component that needs to be added to the root of your web app. This initiatalizes the Self.ID instance, connects to the Ceramic Network, and makes Ceramic-related functionality available all across your app. - To do this, note in your `pages` folder Next.js automatically created a file called `_app.js`. This is the root of your web-app, and all other pages you create are rendered according to the configuration present in this file. By default, it does nothing special, and just renders your page directly. In our case, we want to wrap every component of ours with the Self.ID provider. - First, let's import the `Provider` from Self.ID. Add the following line at the top of `_app.js` ```js import { Provider } from '@self.id/react'; ``` - Next, change the `MyApp` function in that file to return the `Component` wrapped inside a `Provider` ```js function MyApp({ Component, pageProps }) { return ( <Provider client={{ ceramic: "testnet-clay" }}> <Component {...pageProps} />; </Provider> ); } ``` We also specified a configuration option for the Provider. Specifically, we said that we want the Provider to connect to the Clay Test Network for Ceramic. - Let's make sure everything is working fine so far. Run the following in your terminal ```bash npm run dev ``` Your website should be up and running at `http://localhost:3000`. - Lastly, before we start writing code for the actual application, replace the CSS in `styles/Home.module.css` with the following: ```css .main { min-height: 100vh; } .navbar { height: 10%; width: 100%; display: flex; flex-direction: row; justify-content: space-between; padding-top: 1%; padding-bottom: 1%; padding-left: 2%; padding-right: 2%; background-color: orange; } .content { height: 80%; width: 100%; padding-left: 5%; padding-right: 5%; display: flex; flex-direction: column; align-items: center; } .flexCol { display: flex; flex-direction: column; align-items: center; } .connection { margin-top: 2%; } .mt2 { margin-top: 2%; } .subtitle { font-size: 20px; font-weight: 400; } .title { font-size: 24px; font-weight: 500; } .button { background-color: azure; padding: 0.5%; border-radius: 10%; border: 0px; font-size: 16px; cursor: pointer; } .button:hover { background-color: beige; } ``` Since this is not a CSS tutorial, we will not be diving deep into these CSS properties, though you should be able to understand what these properties mean if you would like to dive deeper. - Alright, open up `pages/index.js` and remove everything currently present inside the `function Home() {...}`. We will replace the contents of that function with our code. - We will start by first initializing Web3Modal related code, as connecting a wallet is the first step. - Let's first import `Web3Provider` from `ethers`. ```jsx import { Web3Provider } from "@ethersproject/providers" ``` - As before, let's create a reference using the `useRef` react hook to a Web3Modal instance, and create a helper function to get the Provider. ```jsx const web3ModalRef = useRef(); const getProvider = async () => { const provider = await web3ModalRef.current.connect(); const wrappedProvider = new Web3Provider(provider); return wrappedProvider; } ``` This function will prompt the user to connect their Ethereum wallet, if not already connected, and then return a Web3Provider. However, if you try running it right now, it will fail because we have not yet initialized web3Modal. - Before we initialize Web3Modal, we will setup a React Hook provided to us by the Self.ID SDK. Self.ID provides a hook called `useViewerConnection` which gives us an easy way to connect and disconnect to the Ceramic Network. Add the following import ```jsx import { useViewerConnection } from "@self.id/react"; ``` And now in your `Home` function, do the following to initialize the hook ```jsx const [connection, connect, disconnect] = useViewerConnection(); ``` - Now that we have this, we can initialize Web3Modal. Add the following `useEffect` React Hook to your `Home` function. ```jsx useEffect(() => { if (connection.status !== "connected") { web3ModalRef.current = new Web3Modal({ network: "rinkeby", providerOptions: {}, disableInjectedProvider: false, }); } }, [connection.status]); ``` We have seen this code before many times. The only difference is the conditional here. We are checking that if the user has not yet been connected to Ceramic, we are going to initialize the web3Modal. - The last thing we need to be able to connect to the Ceramic Network is something called an `EthereumAuthProvider`. It is a class exported by the Self.ID SDK which takes an Ethereum provider and an address as an argument, and uses it to connect your Ethereum wallet to your 3ID. - To set that up, let us first import it ```jsx import { EthereumAuthProvider } from "@self.id/web"; ``` and then add the following helper functions ```jsx const connectToSelfID = async () => { const ethereumAuthProvider = await getEthereumAuthProvider(); connect(ethereumAuthProvider); }; const getEthereumAuthProvider = async () => { const wrappedProvider = await getProvider(); const signer = wrappedProvider.getSigner(); const address = await signer.getAddress(); return new EthereumAuthProvider(wrappedProvider.provider, address); }; ``` `getEthereumAuthProvider` creates an instance of the `EthereumAuthProvider`. You may be wondering why we are passing it `wrappedProvider.provider` instead of `wrappedProvider` directly. It's because `ethers` abstracts away the low level provider calls with helper functions so it's easier for developers to use, but since not everyone uses ethers.js, Self.ID maintains a generic interface to actual provider specification, isntead of the `ethers` wrapped version. We can access the actual provider instance through the `provider` property on `wrappedProvider`. `connectToSelfID` takes this Ethereum Auth Provider, and calls the `connect` function that we got from the `useViewerConnection` hook which takes care of everything else for us. - Now, getting to the frontend a bit. - Add the following code to the end of your `Home` function ```jsx return ( <div className={styles.main}> <div className={styles.navbar}> <span className={styles.title}>Ceramic Demo</span> {connection.status === "connected" ? ( <span className={styles.subtitle}>Connected</span> ) : ( <button onClick={connectToSelfID} className={styles.button} disabled={connection.status === "connecting"} > Connect </button> )} </div> <div className={styles.content}> <div className={styles.connection}> {connection.status === "connected" ? ( <div> <span className={styles.subtitle}> Your 3ID is {connection.selfID.id} </span> <RecordSetter /> </div> ) : ( <span className={styles.subtitle}> Connect with your wallet to access your 3ID </span> )} </div> </div> </div> ) ``` For the explanation, here's what's happening. In the top right of the page, we conditionally render a button `Connect` that connects you to SelfID, or if you are already connected, it just says `Connected`. Then, in the main body of the page, if you are connected, we display your 3ID, and render a component called `RecordSetter` that we haven't yet created (we will soon). If you are not connected, we render some text asking you to connect your wallet first. - So far, we can connect to Ceramic Network through Self.ID, but what about actually storing and retrieving data on Ceramic? - We will consider the use case of building a decentralized profile on Ceramic. Thankfully, it is such a common use case that Self.ID comes with built in suport for creating and editing your profile. For the purposes of this tutorial, we will only set a Name to your 3ID and update it, but you can extend it to include all sorts of other properties like an avatar image, your social media links, a description, your age, gender, etc. - For readability, we will divide this into a second React component. This is the `RecordSetter` component we used above. - Start by creating a new component in the same file. Outside your `Home` function, create a new function like this ```jsx function RecordSetter() { } ``` - We are going to use another hook provided to us by Self.ID called `useViewerRecord` which allows storing and retrieving profile information on Ceramic Network. Let's first import it ```jsx import { useViewerRecord } from "@self.id/react"; ``` - Now, let's use this hook in the `RecordSetter` component. ```jsx const record = useViewerRecord("basicProfile"); const updateRecordName = async (name) => { await record.merge({ name: name, }); }; ``` We also created a helper function to update the name stored in our record (data on Ceramic). It takes a parameter `name` and updates the record. - Lastly, let's also create a state variable for `name` that you can type out to update your record ```jsx const [name, setName] = useState(""); ``` - For the frontend part, add the following at the end of your `RecordSetter` function ```jsx return ( <div className={styles.content}> <div className={styles.mt2}> {record.content ? ( <div className={styles.flexCol}> <span className={styles.subtitle}> Hello {record.content.name}! </span> <span> The above name was loaded from Ceramic Network. Try updating it below. </span> </div> ) : ( <span> You do not have a profile record attached to your 3ID. Create a basic profile by setting a name below. </span> )} </div> <input type="text" placeholder="Name" value={name} onChange={(e) => setName(e.target.value)} className={styles.mt2} /> <button onClick={() => updateRecordName(name)}>Update</button> </div> ); ``` This code basically renders a message `Hi ${name}` if you have set a name on your Ceramic profile record, otherwise it tells you that you do not have a profile set up yet and you can create one. You can create or update the profile by inputting text in the textbox and clicking the update button - We should be good to go at this point! Run ```bash npm run dev ``` in your terminal, or refresh your webpage if you already had it running, and you should be able to connect to Ceramic Network through your Metamask wallet and set a name on your decentralized profile, and update it as well! --- To look at the final code for what we have built, you can visit [Github](https://github.com/LearnWeb3DAO/Ceramic). Hopefully this article could give you a sneak peek into how to use Ceramic, and help you gain an understanding of why Ceramic is important. For verification of this level, copy your entire `did:3id:...` string from the webpage and paste it below into the verification box. Show off your website on Discord in the showcase channel, and as always, feel free to ask any questions!
ketyung_tm_collections_contract
Cargo.toml LICENSE.md build.sh readme.md src collections_manage.rs collections_view.rs ext.rs lib.rs tests.rs ticket_mint.rs term_tests1.txt
lflozano_NCD---Near
.idea misc.xml modules.xml vcs.xml README.md as-pect.config.js asconfig.json 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
```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":"2022-06-16"}' --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: '2022-06-16', 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":"2022-06-16"}' --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: '2022-06-16', 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":"2022-06-16"}' --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: '2022-06-16', 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 ```
NEARBuilders_Wallets
features.md |
pseudo-exchange_nym-spec
.travis.yml Cargo.toml README.md USER_STORIES.md package-lock.json package.json src lib.rs util.rs
Nym.Near ============== A name auction for Near. See [User Stories](./USER_STORIES.md) for detailed interaction info. ## Prerequisite Ensure `near-cli` is installed by running: ``` near --version ``` If needed, install `near-cli`: ``` npm install near-cli -g ``` ## 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 ``` ## Using this contract ### 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/nym_near.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_thing` method: ```bash near call $CONTRACT_NAME set_thing '{"msg": "aloha!"}' --accountId $CONTRACT_NAME ``` To retrieve the message from the contract, call `get_thing` with the following: ```bash near view $CONTRACT_NAME get_thing '{"account_id": "'$CONTRACT_NAME'"}' ``` ### Standard deploy In this second 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.nearprotocol.com). In the project root, login with `near-cli` by following the instructions after this command: ``` near login ``` Deploy the contract: ```bash near deploy --wasmFile res/nym_near.wasm --accountId YOUR_ACCOUNT_NAME ``` ## Testing To test run: ```bash cargo test --package status-message -- --nocapture ``` ## Cool Commands: ``` // create account for the contract near create-account nym.t.testnet --masterAccount t.testnet --initialBalance 100 near create-account escrowbar.t.testnet --masterAccount t.testnet --initialBalance 100 near create-account auction.t.testnet --masterAccount t.testnet --initialBalance 100 // no account creation, just use testnet autogen account NEAR_ENV=testnet near deploy --accountId t.testnet --wasmFile res/nym_near.wasm --initFunction new --initArgs '{"escrow_account_id":"t.testnet","escrow_public_key":"ed25519:4cKe5SWR4QTwc7MTLrzNuC633gLzFg9FgiygPVzKYvb1"}' NEAR_ENV=testnet near call t.testnet create '{"asset": "tc", "owner_beneficiary": "t.testnet", "auction_start_bid_amount": 100, "auction_close_block": null}' --accountId t.testnet // deploy to created contract account near deploy --wasmFile res/nym_near.wasm --accountId v0.nym.t.testnet --masterAccount nym.t.testnet // call function on deployed account, only call for things that change state near call dev-1606630107890-6675680 create '{"asset": "thank god its friday"}' --accountId t.testnet near call dev-1606630107890-6675680 create '{"asset": "tc", "owner_beneficiary": "t.testnet", "auction_start_bid_amount": 100, "auction_close_block": null}' --accountId t.testnet "auction_close_block": "", // view state via view function call with params near view dev-1606630107890-6675680 get_auction_by_id '{"id":"1234"}' --accountId t.testnet // call more things with diff params #yay near call dev-1606630107890-6675680 place_bid '{"auction_id": "1234"}' --accountId t.testnet // call more things with diff params #yay #youGetThePicture near call dev-1606630107890-6675680 cancel_auction '{"auction_id": "1234"}' --accountId t.testnet ```
mrlasdt_go-crypto-market-making
clock clock.go command start.go config config.go exchange exchange.go gateio.go order.go uniswap.go gateway .eslintrc.js Changelog.md README.md bin docker-start.sh conf avalanche.yml binance-smart-chain.yml cronos.yml database.yml defikingdoms.yml defira.yml ethereum-gas-station.yml ethereum.yml harmony.yml logging.yml mad_meerkat.yml near.yml openocean.yml pancakeswap.yml pangolin.yml perp.yml polygon.yml quickswap.yml ref.yml root.yml serum.yml server.yml solana.yml ssl.yml sushiswap.yml telemetry.yml traderjoe.yml uniswap.yml vvs.yml dist integration-test clob clob.controllers.test.js clob.routes.test.js connector serum reset.test.js serum.controllers.test.js serum.routes.test.js src amm amm.controllers.js amm.requests.js amm.routes.js amm.validators.js app.js chains avalanche avalanche.js avalanche.validators.js binance-smart-chain binance-smart-chain.js cronos cronos.js ethereum balancer balancer.config.js ethereum.config.js ethereum.controllers.js ethereum.js ethereum.requests.js ethereum.validators.js harmony harmony.config.js harmony.js harmony.validators.js near near.abi.json near.base.js near.config.js near.controllers.js near.js near.requests.js near.routes.js near.validators.js polygon polygon.js polygon.validators.js solana solana-middlewares.js solana.config.js solana.constants.js solana.controllers.js solana.js solana.requests.js solana.routes.js solana.validators.js clob clob.controllers.js clob.requests.js clob.routes.js connectors connectors.routes.js cronos-base cronos-base-uniswapish-connector.config.js cronos-base-uniswapish-connector.js defikingdoms defikingdoms.config.js defikingdoms.js defikingdoms_router_abi.json defira defira.config.js defira.js defira_v2_router_abi.json mad_meerkat abi.json mad_meerkat.config.js mad_meerkat.js openocean openocean.config.js openocean.js pancakeswap pancakeswap.config.js pancakeswap.js pancakeswap_router_abi.json pangolin IPangolinRouter.json pangolin.config.js pangolin.js perp perp.config.js perp.controllers.js perp.js quickswap quickswap.config.js quickswap.js ref ref.config.js ref.controllers.js ref.helper.js ref.js serum extensions json.js market.js serum.config.js serum.constants.js serum.controllers.js serum.convertors.js serum.helpers.js serum.js serum.middlewares.js serum.requests.js serum.routes.js serum.types.js serum.validators.js sushiswap sushiswap.config.js sushiswap.js sushiswap_router.json traderjoe IJoeRouter02.json traderjoe.config.js traderjoe.js uniswap uniswap.config.js uniswap.controllers.js uniswap.js uniswap.lp.helper.js uniswap.lp.interfaces.js uniswap.lp.js uniswap_v2_router_abi.json vvs abi.json vvs.config.js vvs.js evm evm.requests.js evm.routes.js https.js index.js network network.controllers.js network.requests.js network.routes.js paths.js services base.js common-interfaces.js config-manager-cert-passphrase.js config-manager-types.js config-manager-v2.js config-migration migrations.js config config.requests.js config.routes.js config.validators.js connection-manager.js error-handler.js ethereum-base.js ethereum.abi.json evm.nonce.js evm.tx-storage.js local-storage.js logger.js refcounting-closeable.js schema configuration-root-schema.json cronos-connector-schema.json database-schema.json defikingdoms-schema.json defira-schema.json ethereum-gas-station-schema.json ethereum-schema.json harmony-schema.json logging-schema.json openocean-schema.json pangolin-schema.json perp-schema.json quickswap-schema.json ref-schema.json serum-schema.json server-schema.json solana-schema.json ssl-schema.json sushiswap-schema.json telemetry-schema.json traderjoe-schema.json uniswap-schema.json swagger-manager.js telemetry-transport.js validators.js wallet wallet.controllers.js wallet.requests.js wallet.routes.js wallet.validators.js templates avalanche.yml binance-smart-chain.yml cronos.yml database.yml defikingdoms.yml defira.yml ethereum-gas-station.yml ethereum.yml harmony.yml logging.yml mad_meerkat.yml near.yml openocean.yml pancakeswap.yml pangolin.yml perp.yml polygon.yml quickswap.yml ref.yml root.yml serum.yml server.yml solana.yml ssl.yml sushiswap.yml telemetry.yml traderjoe.yml uniswap.yml vvs.yml test amm amm.validators.test.js app.test.js chains avalanche avalanche.routes.test.js avalanche.test.js avalanche.validators.test.js openocean openocean.routes.test.js openocean.test.js pangolin pangolin.routes.test.js pangolin.test.js traderjoe traderjoe.test.js binance-smart-chain binance-smart-chain.routes.test.js pancakeswap pancakeswap.routes.test.js pancakeswap.test.js cronos cronos.routes.test.js mad_meerkat mad-meerkat.routes.test.js mad-meerkat.test.js vvs vvs.routes.test.js vvs.test.js ethereum ethereum.controllers.test.js ethereum.routes.test.js ethereum.validators.test.js evm.nonce.test.js fixtures transaction-out-of-gas-receipt.json transaction-out-of-gas.json transaction-succesful-receipt.json transaction-succesful.json perp perp.routes.test.js perp.test.js sushiswap sushiswap.routes.test.js sushiswap.test.js uniswap uniswap.lp.routes.test.js uniswap.lp.test.js uniswap.routes.test.js uniswap.test.js harmony defikingdoms defikingdoms.routes.test.js defikingdoms.test.js defira defira.routes.test.js defira.test.js harmony.controllers.test.js harmony.routes.test.js harmony.test.js harmony.validators.test.js near fixtures getTokenList.json getTransaction.json near.controllers.test.js near.routes.test.js near.validators.test.js ref ref.route.test.js ref.test.js polygon polygon.test.js polygon.validators.test.js quickswap quickswap.route.test.js quickswap.test.js solana fixtures getOrCreateAssociatedTokenAccount.js getSolanaConfig.js getTokenAccount.js getTokenList.json getTransaction.json serum fixtures config.js helpers.js patches data.js patches.js serum.controllers.test.js serum.routes.test.js solana.controllers.test.js solana.routes.test.js solana.validators.test.js clob clob.controllers.test.js clob.routes.test.js config.util.js connectors connectors.routes.test.js evm.nonce.mock.js network network.routes.test.js services base.test.js config-manager-cert-passphrase.test.js config-manager-v2.test.js config-validators.test.js data config-manager-v2 test1 ethereum.yml invalid-defira.yml invalid-root-2.yml invalid-root-3.yml invalid-root-4.yml invalid-root-defira.yml invalid-root.yml invalid-ssl.yml root.yml root2.yml ssl.yml telemetry.yml error-handler.test.js evm.nonce.test.js evm.tx-storage.test.js local-storage.test.js logger.test.js patch.js patch.test.js refcounting-closeable.test.js swagger-manager.test.js validators.test.js wallet wallet.controllers.test.js wallet.routes.test.js wallet.validators.test.js setup.js teardown.js docs swagger amm-liquidity-routes.yml amm-routes.yml clob-routes.yml connectors-routes.yml definitions.yml evm-routes.yml main-routes.yml near-routes.yml network-routes.yml serum-routes.yml solana-routes.yml swagger.yml wallet-routes.yml testing.md hooks README.md integration-test clob clob.controllers.test.ts clob.routes.test.ts connector serum reset.test.ts serum.controllers.test.ts serum.routes.test.ts jest.config.js manual-tests curl.sh requests add_avalanche_key.json add_bsc_key.json add_cronos_key.json add_ethereum_key.json add_near_key.json avalanche_approve.json avalanche_nonce.json avalanche_traderjoe_allowances.json avalanche_traderjoe_trade.json bsc_approve.json bsc_balances.json bsc_nonce.json bsc_pancakeswap_trade.json bsc_sushiswap_trade.json clob_delete_orders.json clob_get_filled_orders.json clob_get_markets.json clob_get_open_orders.json clob_get_order_books.json clob_get_orders.json clob_get_root.json clob_get_tickers.json clob_post_orders.json clob_post_settle_funds.json config_update.json cronos_approve.json cronos_balances.json cronos_mmf_trade.json cronos_nonce.json cronos_vvs_trade.json eth_allowances.json eth_approve.json eth_approve_with_fees.json eth_approve_with_nonce.json eth_balances.json eth_nonce.json eth_perp_approve.json eth_poll.json eth_remove_allowance.json eth_uniswap_add_liquidity.json eth_uniswap_pool_price.json eth_uniswap_position.json eth_uniswap_price.json eth_uniswap_trade.json eth_uniswap_trade_with_fees.json harmony_dfk_trade.json harmony_testnet_defira_trade.json mmf_cronos_mainnet_allowance.json near_mainnet_ref_trade.json near_network_balances.json near_post_poll.json network_balances.json network_poll.json perp_position.json perp_prices.json perp_trade_open.json price_bsc_pancakeswap.json price_defira.json price_dfk.json price_mad_meerkat.json price_pangolin.json price_ref.json price_traderjoe.json price_uniswap.json price_vvs.json remove_avalanche_key.json remove_bsc_key.json remove_cronos_key.json remove_ethereum_key.json remove_near_key.json serum_delete_orders.json serum_get_filled_orders.json serum_get_markets.json serum_get_open_orders.json serum_get_order_books.json serum_get_orders.json serum_get_root.json serum_get_tickers.json serum_post_orders.json serum_post_settle_funds.json solana_get_balances.json solana_get_root.json solana_get_token.json solana_post_poll.json solana_post_token.json status_request.json nodemon.json package.json setup generate_conf.sh src @types buffer-layout.d.ts cycle.d.ts amm amm.controllers.ts amm.requests.ts amm.routes.ts amm.validators.ts app.ts chains avalanche avalanche.ts avalanche.validators.ts avalanche_tokens_fuji.json binance-smart-chain bep20_tokens_mainnet.json bep20_tokens_testnet.json binance-smart-chain.ts cronos cronos.ts mainnet_beta.json testnet.json ethereum balancer balancer.config.ts erc20_tokens_goerli.json erc20_tokens_kovan.json erc20_tokens_ropsten.json ethereum.config.ts ethereum.controllers.ts ethereum.requests.ts ethereum.ts ethereum.validators.ts harmony harmony.config.ts harmony.ts harmony.validators.ts harmony_tokens_defira.json harmony_tokens_defira_testnet.json harmony_tokens_sushiswap.json harmony_tokens_sushiswap_testnet.json near near.abi.json near.base.ts near.config.ts near.controllers.ts near.requests.ts near.routes.ts near.ts near.validators.ts polygon polygon.ts polygon.validators.ts polygon_tokens_mainnet.json polygon_tokens_mumbai.json solana solana-middlewares.ts solana.config.ts solana.constants.ts solana.controllers.ts solana.requests.ts solana.routes.ts solana.ts solana.validators.ts clob clob.controllers.ts clob.requests.ts clob.routes.ts connectors connectors.routes.ts cronos-base cronos-base-uniswapish-connector.config.ts cronos-base-uniswapish-connector.ts defikingdoms defikingdoms.config.ts defikingdoms.ts defikingdoms_router_abi.json defira defira.config.ts defira.ts defira_v2_router_abi.json mad_meerkat abi.json mad_meerkat.config.ts mad_meerkat.ts openocean openocean.config.ts openocean.ts pancakeswap pancakeswap.config.ts pancakeswap.ts pancakeswap_router_abi.json pangolin IPangolinRouter.json pangolin.config.ts pangolin.ts perp perp.config.ts perp.controllers.ts perp.ts quickswap quickswap.config.ts quickswap.ts ref ref.config.ts ref.controllers.ts ref.helper.ts ref.ts serum extensions json.ts market.ts serum.config.ts serum.constants.ts serum.controllers.ts serum.convertors.ts serum.helpers.ts serum.middlewares.ts serum.requests.ts serum.routes.ts serum.ts serum.types.ts serum.validators.ts sushiswap sushiswap.config.ts sushiswap.ts sushiswap_router.json traderjoe IJoeRouter02.json traderjoe.config.ts traderjoe.ts uniswap uniswap.config.ts uniswap.controllers.ts uniswap.lp.helper.ts uniswap.lp.interfaces.ts uniswap.lp.ts uniswap.ts uniswap_v2_router_abi.json vvs abi.json vvs.config.ts vvs.ts evm evm.requests.ts evm.routes.ts https.ts index.ts network network.controllers.ts network.requests.ts network.routes.ts paths.ts services base.ts common-interfaces.ts config-manager-cert-passphrase.ts config-manager-types.ts config-manager-v2.ts config-migration migrations.ts config config.requests.ts config.routes.ts config.validators.ts connection-manager.ts error-handler.ts ethereum-base.ts ethereum.abi.json evm.nonce.ts evm.tx-storage.ts local-storage.ts logger.ts refcounting-closeable.ts schema configuration-root-schema.json cronos-connector-schema.json database-schema.json defikingdoms-schema.json defira-schema.json ethereum-gas-station-schema.json ethereum-schema.json harmony-schema.json logging-schema.json openocean-schema.json pangolin-schema.json perp-schema.json quickswap-schema.json ref-schema.json serum-schema.json server-schema.json solana-schema.json ssl-schema.json sushiswap-schema.json telemetry-schema.json traderjoe-schema.json uniswap-schema.json swagger-manager.ts telemetry-transport.ts validators.ts wallet wallet.controllers.ts wallet.requests.ts wallet.routes.ts wallet.validators.ts templates avalanche.yml binance-smart-chain.yml cronos.yml database.yml defikingdoms.yml defira.yml ethereum-gas-station.yml ethereum.yml harmony.yml logging.yml mad_meerkat.yml near.yml openocean.yml pancakeswap.yml pangolin.yml perp.yml polygon.yml quickswap.yml ref.yml root.yml serum.yml server.yml solana.yml ssl.yml sushiswap.yml telemetry.yml traderjoe.yml uniswap.yml vvs.yml startup.sh test-scripts README.md ethereum.test.base.ts harmony.test.ts solana.test.ts test.base.ts uniswap.v2.test.ts test amm amm.validators.test.ts app.test.ts chains avalanche avalanche.routes.test.ts avalanche.test.ts avalanche.validators.test.ts openocean openocean.routes.test.ts openocean.test.ts pangolin pangolin.routes.test.ts pangolin.test.ts traderjoe traderjoe.test.ts binance-smart-chain binance-smart-chain.routes.test.ts pancakeswap pancakeswap.routes.test.ts pancakeswap.test.ts cronos cronos.routes.test.ts mad_meerkat mad-meerkat.routes.test.ts mad-meerkat.test.ts vvs vvs.routes.test.ts vvs.test.ts ethereum ethereum.controllers.test.ts ethereum.routes.test.ts ethereum.validators.test.ts evm.nonce.test.ts fixtures transaction-out-of-gas-receipt.json transaction-out-of-gas.json transaction-succesful-receipt.json transaction-succesful.json perp perp.routes.test.ts perp.test.ts sushiswap sushiswap.routes.test.ts sushiswap.test.ts uniswap uniswap.lp.routes.test.ts uniswap.lp.test.ts uniswap.routes.test.ts uniswap.test.ts harmony defikingdoms defikingdoms.routes.test.ts defikingdoms.test.ts defira defira.routes.test.ts defira.test.ts harmony.controllers.test.ts harmony.routes.test.ts harmony.test.ts harmony.validators.test.ts near fixtures getTokenList.json getTransaction.json near.controllers.test.ts near.routes.test.ts near.validators.test.ts ref ref.route.test.ts ref.test.ts polygon polygon.test.ts polygon.validators.test.ts quickswap quickswap.route.test.ts quickswap.test.ts solana fixtures getOrCreateAssociatedTokenAccount.ts getSolanaConfig.ts getTokenAccount.ts getTokenList.json getTransaction.json serum fixtures config.ts helpers.ts patches data.ts patches.ts serum.controllers.test.ts serum.routes.test.ts solana.controllers.test.ts solana.routes.test.ts solana.validators.test.ts clob clob.controllers.test.ts clob.routes.test.ts config.util.ts connectors connectors.routes.test.ts evm.nonce.mock.ts network network.routes.test.ts postman collections EthereumV2.postman_collection.json Openocean-GatewayV2.postman_collection.json Uniswap-GatewayV2.postman_collection.json enviroments GatewayV2.postman_environment.json services base.test.ts config-manager-cert-passphrase.test.ts config-manager-v2.test.ts config-validators.test.ts data config-manager-v2 test1 ethereum.yml invalid-defira.yml invalid-root-2.yml invalid-root-3.yml invalid-root-4.yml invalid-root-defira.yml invalid-root.yml invalid-ssl.yml root.yml root2.yml ssl.yml telemetry.yml error-handler.test.ts evm.nonce.test.ts evm.tx-storage.test.ts local-storage.test.ts logger.test.ts patch.test.ts patch.ts refcounting-closeable.test.ts swagger-manager.test.ts validators.test.ts wallet wallet.controllers.test.ts wallet.routes.test.ts wallet.validators.test.ts setup.ts setupTests.js teardown.ts tsconfig.json | iterator iterator.go main.go strategy simplePmm.go strategy.go uniswapV3LP.go utils utils.go
![Hummingbot](https://i.ibb.co/X5zNkKw/blacklogo-with-text.png) # Hummingbot Gateway --- Hummingbot Gateway is a REST API that exposes connections to various blockchains (wallet, node & chain interaction) and decentralized exchanges (pricing, trading & liquidity provision). It is written in Typescript and takes advantage of existing blockchain and DEX SDKs. The advantage of using gateway is it provideds a programming language agnostic approach to interacting with blockchains and DEXs. Gateway may be used alongside the main Hummingbot client to enable trading on DEXs, or as a standalone module by external developers. ## Connectors This is a list of DEX connections currently supported by Gateway. | Connector | Blockchain | Trading Interface | | ----------- | ------------------- | ----------------- | | UniswapV2 | Ethereum | AMM | | Sushiswap | Ethereum | AMM | | UniswapV3 | Ethereum | EVM_Range_AMM | | Pangolin | Avalanche | AMM | | PancakeSwap | Binance Smart Chain | AMM | | Traderjoe | Avalanche | AMM | | Quickswap | Polygon | AMM | | Perp | Ethereum | EVM_Perpetual | | Serum | Solana | CLOB | | Mad Meerkat | Cronos | AMM | | VVS | Cronos | AMM | ## Contributing There are a number of ways to contribute to gateway. - Add a new blockchain. - Add a new connector/DEX. - Fix a bug. - File an issue at [hummingbot issues](https://github.com/hummingbot/hummingbot/issues) - Make a PR for anything useful on [hummingbot](https://github.com/hummingbot/hummingbot/). - Vote on a snapshot proposal: [Hummingbot PRP](https://snapshot.org/#/hbot-prp.eth), [Hummingbot Foundation - HGP](https://snapshot.org/#/hbot.eth), [Hummingbot Improvement Proposals](https://snapshot.org/#/hbot-ip.eth). ## Configuration Before running gateway, you need to setup some configs. You can start by copying all of the yml files from [src/templates](./src/templates) to [conf](./conf). The format of this files are dictated by [src/services/config-manager-v2.ts](./src/services/config-manager-v2.ts) and the corresponding schema files in [src/services/schema](./src/services/schema) . ### Useful configuration options - If you want to turn off `https`, set `unsafeDevModeWithHTTP` to `true` in [conf/server.yml](./conf/server.yml). - If you gateway to log to standard out, set `logToStdOut` to `true` in [conf/logging.yml](./conf/logging.yml). - Edit the path to the SSL files in [conf/ssl.yml](./conf/ssl.yml). This can be generated by hummingbot with `gateway generate-certs`. The hummingbot client is also able to edit this config files. ## Install and run locally Compile the Typescript code with `npm` or `yarn` . ```bash yarn yarn build yarn dev --passphrase=<ssl-files-passphrase> # the passphrase can be anything if unsafeDevModeWithHTTP is true ``` ## Documentation The API is documented using swagger: [gateway swagger docs](./docs/swagger). You can run the gateway swagger UI by starting gateway and visiting [localhost:8080](localhost:8080). You can follow details about [trading interfaces](https://hummingbot.notion.site/Gateway-v2-Trading-Interfaces-482e2684d48c450ebcfff5401ba806aa) Also, we maintain docs on the official website about gateway [here](https://hummingbot.org/protocols/gateway/). ### Files to read Here are some files we recommend you look at in order to get familiar with the gateway code base. - [src/services/ethereum-base.ts](./src/services/ethereum-base.ts) is a base class for EVM chains. - [src/connectors/uniswap/uniswap.ts](./src/connectors/uniswap/uniswap.ts) has functionality for interacting with Uniswap V2. - [src/services/validator.ts](./src/services/validator.ts) defines functions for validating request payloads. ### Testing When making a PR, there are unit test coverage requirements. Look at our [github workflow](../.github/workflows/workflow.yml) for the exact definition. There are some more #### Unit tests Read this document for more details about how to write unit test in gateway: [How we write unit tests for gateway](./docs/testing.md). Run all unit tests. ```bash yarn test:unit ``` Run an individual test file. ```bash yarn jest test/app.test.ts ``` #### Manual tests We have found it is useful to test individual endpoints with `curl` commands. We have a collection of prepared curl calls. POST bodies are stored in JSON files. Take a look at the [curl calls for gateway](./manual-tests/curl.sh). Note that some environment variables are expected. ## Linting This repo uses `eslint` and `prettier`. When you run `git commit` it will trigger the `pre-commit` hook. This will run `eslint` on the `src` and `test` directories. You can lint before committing with: ```bash yarn run lint ``` You can run the prettifier before committing with: ```bash yarn run prettier ``` # Docker Autobuild Hooks This folder containers hooks for docker autobuild. [Hummingbot builds](https://hub.docker.com/r/coinalpha/hummingbot/builds) # gateway test scripts Make sure to properly setup your config files and add a wallet to use for testing. Then set the environment variable `ETH_PUBLIC_KEY` to an added wallet. Start a local instance of the gateway API with `yarn start`, and run the test script with `yarn test:scripts`.
luciotato_simple-rust-parser
.vscode tasks.json README.md build.js package-lock.json package.json res test expected staking-pool.js rust-samples declaration.rs outer-tests.rs test1-full.rs test1-start.rs staking-pool src lib.rs src index.ts lib Lexer Lexer.ts Parser ASTBase.ts CodeWriter.ts Grammar.ts Parser.ts Producer AssemblyScriptProducer.ts D3Visualization.ts create-contract-cli-producer.ts util ControlledError.ts String.extensions.ts UTF8FileReader.ts UTF8FileWriter.ts color.ts logger.ts mkPath.ts test expect.ts test.AssemblyScript.ts test.Tokenizer.ts test.ts START TESTS END TESTS tsconfig.json z-old test_OLD Test.TokenizeDeclaration.ts UnitTest1.ts tests-ccc model hand-coded-tom .vscode tasks.json ContractAPI.ts package-lock.json package.json tom.ts tsconfig.json util CommandLineArgs.ts CommonCLIOptions.ts ShowHelpPage.ts SpawnNearCli.ts test.ts
# Simple Rust Parser This a simple hand-coded PEG parser for a subset of Rust, it is aimed to parse the subset of Rust used for writing smart contracts for the Near Blockchain
JoaquimLey_link3
client-web README.md package.json postcss.config.js public index.html manifest.json robots.txt src App.js App.test.js copy_icon.svg github_logo.svg index.css index.js link3_logo.svg near config.js near_logo.svg setupTests.js tailwind.config.js contracts Cargo.toml build.sh src item.rs lib.rs link3.rs utils counter.rs keyvalue.rs simple_default.rs
# 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)
hermes1108_near-coinflip-frontend
README.md package.json public index.html manifest.json robots.txt src App.css App.js App.test.js common config.js components FundModal.js HelpModal.js index.css index.js logo.svg page Main.js coin.css 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)
Markeljan_swapguard
.vscode settings.json README.md dex-app README.md const details.ts next.config.js package-lock.json package.json pages api hello.ts public next.svg thirteen.svg vercel.svg styles Home.module.css globals.css tsconfig.json dex-contracts README.md deployArgs.json hardhat.config.js package-lock.json package.json foundry README.md foundry.toml package.json scaffold-eth .github ISSUE_TEMPLATE bug_report.yml config.yml pull_request_template.md .lintstagedrc.js .yarnrc.yml CONTRIBUTING.md README.md package.json packages hardhat .eslintrc.json .prettierrc.json deploy 00_deployMultiDEX.ts 01_deployTokens.ts 02_deployWETH.ts 03_deployUSDC.ts 04_deployFrontRunner.ts 99_generateTsAbis.ts deployments coston2 FrontRunner.json MultiDEX.json USDC.json WETH.json solcInputs 1a9cb6e99411acb453ab0d9acd1e67b6.json 2a3603bd4ff6f465642ba11cc0f67779.json 2cd8a4f954700d33a473d7e84335e86d.json 34763a34a83e96a47640037a4be290cf.json 64b969127ab1e88602aa4020bc65b903.json 6564edc1e5f1ca711141ab1ea88b125d.json 77908fc2fda08d3213ee986e8c5a838e.json 8959186d9735f863b166a2649432283f.json 8a59004299167595109b829221f6fa62.json 94039dc7aa9a1df2f66ae05811b96619.json a44cc90bef3c96c73078661dc7667072.json a58df7263434e503682954fc327092f3.json a77560ac51121517909662fcdc4730bf.json c3a38bb134f7e411fd5f53d24e29b457.json e452b631bbea39c41bc19985a7312220.json f9049ccea05241a3c7bb43802c5fffb6.json localhost MultiDEX.json solcInputs f4c33a2fbef6d9851d324a649fe9bb23.json hardhat.config.ts package.json scripts configureTokens.ts generateAccount.ts listAccount.ts tasks frontRunAttack.ts frontRunAttackSim.ts tsconfig.json nextjs .eslintrc.json .prettierrc.json components scaffold-eth Input index.ts utils.ts generated deployedContracts.ts hooks scaffold-eth index.ts useAccountBalance.ts useAnimationConfig.ts useAutoConnect.ts useBurnerWallet.ts useContractLogs.ts useDeployedContractInfo.ts useFetchBlocks.ts useNativeCurrencyPrice.ts useNetworkColor.ts useOutsideClick.ts useScaffoldContract.ts useScaffoldContractRead.ts useScaffoldContractWrite.ts useScaffoldEventHistory.ts useScaffoldEventSubscriber.ts next-env.d.ts next.config.js package.json postcss.config.js public flaredex.svg logo.svg manifest.json readme diagram.svg sponsors.svg swapguard.svg scaffold.config.ts services store store.ts web3 wagmi-burner BurnerConnector.ts BurnerConnectorErrors.ts BurnerConnectorTypes.ts burnerWalletConfig.ts styles globals.css tailwind.config.js tsconfig.json types abitype abi.d.ts utils scaffold-eth block.ts common.ts contract.ts contractNames.ts decodeTxData.ts fetchPriceFromUniswap.ts index.ts networks.ts
# DEX contracts > **Warning:** This code is not audited. Use at your own risk. This contracts in this repository can be used with the [DEX app repository](https://github.com/thirdweb-example/dex-app). ## Compiling the contract Use the following command to compile the contract: ```bash npx thirdweb build ``` ## Deploying the contract Use the following command to deploy the contract to any EVM chain: ```bash npx thirdweb deploy ``` ## Conclusion If you need support, feel free to join our [Discord server](https://discord.gg/thirdweb). For any feedback related to thirdweb, please leave them on our [feedback board](https://feedback.thirdweb.com). # DEX app Create your own DEX for your ERC-20 token. Find the related contracts in the [dex-contracts repository](https://github.com/thirdweb-example/dex-contracts). ## Installation After cloning this repository, install the dependencies using the following command: ```bash # npm npm install # yarn yarn install ``` ## Adding details Make sure you deploy the contracts specified in the dex-contracts repository and add the contract details in the `const/details.ts` file. ## Running the app Use the following command to start the development server: ```bash # npm npm run dev # yarn yarn dev ``` ## Conclusion If you need any support, feel free to join our [Discord server](https://discord.gg/thirdweb) and ask us. If you have any feedback related to thirdweb, please leave it on our [feedback board](https://feedback.thirdweb.com). ![SwapGuard](/scaffold-eth/packages/nextjs/public/readme/swapguard.svg) # Price-Protected Trading on Flare Network - inspired by EIP-7265 [Video Demo](https://www.youtube.com/watch?v=CiVqfb8Ow7U) [NEAR BOS Frontend](https://near.org/near/widget/ComponentDetailsPage?src=markeljan.near/widget/SwapGuard) ## What is SwapGuard **SwapGuard** is a Smart Contract Module aimed at improving the UX and security of trading on DEXes, especially in terms of ensuring fair prices and preventing adverse trade conditions. To demonstrate SwapGuard's functionality, we have built the: ### First Price-Protected DEX on the Flare Network **Offering a price guarantee on all trades, powered by native price feeds on Flare Network.** ## Eliminating Price Manipulations - **Slippage** -> _swap-guarded_ - **Front Running** -> _swap-guarded_ - **Low Liquidity** -> _swap-guarded_ - **Oracle Manipulation** -> _swap-guarded_ ## How it Works ![Diagram](/scaffold-eth/packages/nextjs/public/readme/diagram.svg) Users send transactions via a decentralized frontend built with NEAR BOS. The system checks prices between the oracle and the liquidity pool. If the price is good, the transaction is executed; otherwise, it's rejected. # NEAR BOS Component <img width="800" alt="image" src="https://github.com/Markeljan/swapguard/assets/12901349/fdd9a2b5-9099-4bcb-a745-005ad7659ff6"> ## Credits to Flare Network Before Flare Network's FTSO, gas-efficient circuit breakers were challenging. In relation to our work on EIP-7265 and implementations on other networks, circuit breakers usually had significant gas implications. Flare's native on-chain price feeds resolve this issue, making circuit breakers a prominent use case that highlights the USPs of Flare. sponsored tech stacK: ![DEX Image](/scaffold-eth/packages/nextjs/public/readme/sponsors.svg) ## Foundry **Foundry is a blazing fast, portable and modular toolkit for Ethereum application development written in Rust.** Foundry consists of: - **Forge**: Ethereum testing framework (like Truffle, Hardhat and DappTools). - **Cast**: Swiss army knife for interacting with EVM smart contracts, sending transactions and getting chain data. - **Anvil**: Local Ethereum node, akin to Ganache, Hardhat Network. - **Chisel**: Fast, utilitarian, and verbose solidity REPL. ## Documentation https://book.getfoundry.sh/ ## Usage ### Build ```shell $ forge build ``` ### Test ```shell $ forge test ``` ### Format ```shell $ forge fmt ``` ### Gas Snapshots ```shell $ forge snapshot ``` ### Anvil ```shell $ anvil ``` ### Deploy ```shell $ forge script script/Counter.s.sol:CounterScript --rpc-url <your_rpc_url> --private-key <your_private_key> ``` ### Cast ```shell $ cast <subcommand> ``` ### Help ```shell $ forge --help $ anvil --help $ cast --help ``` # 🏗 Scaffold-ETH 2 🧪 An open-source, up-to-date toolkit for building decentralized applications (dapps) on the Ethereum blockchain. It's designed to make it easier for developers to create and deploy smart contracts and build user interfaces that interact with those contracts. ⚙️ Built using NextJS, RainbowKit, Hardhat, Wagmi, and Typescript. - ✅ **Contract Hot Reload**: Your frontend auto-adapts to your smart contract as you edit it. - 🔥 **Burner Wallet & Local Faucet**: Quickly test your application with a burner wallet and local faucet. - 🔐 **Integration with Wallet Providers**: Connect to different wallet providers and interact with the Ethereum network. ## Contents - [Requirements](#requirements) - [Quickstart](#quickstart) - [Deploying your Smart Contracts to a Live Network](#deploying-your-smart-contracts-to-a-live-network) - [Deploying your NextJS App](#deploying-your-nextjs-app) - [Interacting with your Smart Contracts: SE-2 Custom Hooks](#interacting-with-your-smart-contracts-se-2-custom-hooks) - [Disabling Type & Linting Error Checks](#disabling-type-and-linting-error-checks) - [Disabling commit checks](#disabling-commit-checks) - [Deploying to Vercel without any checks](#deploying-to-vercel-without-any-checks) - [Disabling Github Workflow](#disabling-github-workflow) - [Contributing to Scaffold-ETH 2](#contributing-to-scaffold-eth-2) ## Requirements Before you begin, you need to install the following tools: - [Node (v18 LTS)](https://nodejs.org/en/download/) - Yarn ([v1](https://classic.yarnpkg.com/en/docs/install/) or [v2+](https://yarnpkg.com/getting-started/install)) - [Git](https://git-scm.com/downloads) ## Quickstart To get started with Scaffold-ETH 2, follow the steps below: 1. Clone this repo & install dependencies ``` git clone https://github.com/scaffold-eth/scaffold-eth-2.git cd scaffold-eth-2 yarn install ``` 2. Run a local network in the first terminal: ``` yarn chain ``` This command starts a local Ethereum network using Hardhat. The network runs on your local machine and can be used for testing and development. You can customize the network configuration in `hardhat.config.ts`. 3. On a second terminal, deploy the test contract: ``` yarn deploy ``` This command deploys a test smart contract to the local network. The contract is located in `packages/hardhat/contracts` and can be modified to suit your needs. The `yarn deploy` command uses the deploy script located in `packages/hardhat/deploy` to deploy the contract to the network. You can also customize the deploy script. 4. On a third terminal, start your NextJS app: ``` yarn start ``` Visit your app on: `http://localhost:3000`. You can interact with your smart contract using the contract component or the example ui in the frontend. You can tweak the app config in `packages/nextjs/scaffold.config.ts`. Run smart contract test with `yarn hardhat:test` - Edit your smart contract `YourContract.sol` in `packages/hardhat/contracts` - Edit your frontend in `packages/nextjs/pages` - Edit your deployment scripts in `packages/hardhat/deploy` ## Deploying your Smart Contracts to a Live Network Once you are ready to deploy your smart contracts, there are a few things you need to adjust. 1. Select the network By default, `yarn deploy` will deploy the contract to the local network. You can change the defaultNetwork in `packages/hardhat/hardhat.config.ts.` You could also simply run `yarn deploy --network target_network` to deploy to another network. Check the `hardhat.config.ts` for the networks that are pre-configured. You can also add other network settings to the `hardhat.config.ts file`. Here are the [Alchemy docs](https://docs.alchemy.com/docs/how-to-add-alchemy-rpc-endpoints-to-metamask) for information on specific networks. Example: To deploy the contract to the Sepolia network, run the command below: ``` yarn deploy --network sepolia ``` 2. Generate a new account or add one to deploy the contract(s) from. Additionally you will need to add your Alchemy API key. Rename `.env.example` to `.env` and fill the required keys. ``` ALCHEMY_API_KEY="", DEPLOYER_PRIVATE_KEY="" ``` The deployer account is the account that will deploy your contracts. Additionally, the deployer account will be used to execute any function calls that are part of your deployment script. You can generate a random account / private key with `yarn generate` or add the private key of your crypto wallet. `yarn generate` will create a random account and add the DEPLOYER_PRIVATE_KEY to the .env file. You can check the generated account with `yarn account`. 3. Deploy your smart contract(s) Run the command below to deploy the smart contract to the target network. Make sure to have some funds in your deployer account to pay for the transaction. ``` yarn deploy --network network_name ``` 4. Verify your smart contract You can verify your smart contract on Etherscan by running: ``` yarn verify --network network_name ``` ## Deploying your NextJS App **Hint**: We recommend connecting your GitHub repo to Vercel (through the Vercel UI) so it gets automatically deployed when pushing to `main`. If you want to deploy directly from the CLI, run `yarn vercel` and follow the steps to deploy to Vercel. Once you log in (email, github, etc), the default options should work. It'll give you a public URL. If you want to redeploy to the same production URL you can run `yarn vercel --prod`. If you omit the `--prod` flag it will deploy it to a preview/test URL. **Make sure your `packages/nextjs/scaffold.config.ts` file has the values you need.** ## Interacting with your Smart Contracts: SE-2 Custom Hooks Scaffold-ETH 2 provides a collection of custom React hooks designed to simplify interactions with your deployed smart contracts. These hooks are wrappers around `wagmi`, automatically loading the necessary contract ABI and address. They offer an easy-to-use interface for reading from, writing to, and monitoring events emitted by your smart contracts. To help developers get started with smart contract interaction using Scaffold-ETH 2, we've provided the following custom hooks: - [useScaffoldContractRead](#usescaffoldcontractread): for reading public variables and getting data from read-only functions of your contract. - [useScaffoldContractWrite](#usescaffoldcontractwrite): for sending transactions to your contract to write data or perform an action. - [useScaffoldEventSubscriber](#usescaffoldeventsubscriber): for subscribing to your contract events and receiving real-time updates when events are emitted. - [useScaffoldEventHistory](#usescaffoldeventhistory): for retrieving historical event logs for your contract, providing past activity data. - [useDeployedContractInfo](#usedeployedcontractinfo): for fetching details from your contract, including the ABI and address. - [useScaffoldContract](#usescaffoldcontract): for obtaining a contract instance that lets you interact with the methods of your deployed smart contract. These hooks offer a simplified and streamlined interface for interacting with your smart contracts. If you need to interact with external contracts, you can use `wagmi` directly, or add external contract data to your `deployedContracts.ts` file. ### useScaffoldContractRead: Use this hook to read public variables and get data from read-only functions of your smart contract. ```ts const { data: totalCounter } = useScaffoldContractRead({ contractName: "YourContract", functionName: "getGreeting", args: ["ARGUMENTS IF THE FUNCTION ACCEPTS ANY"], }); ``` This example retrieves the data returned by the `getGreeting` function of the `YourContract` smart contract. If the function accepts any arguments, they can be passed in the args array. The retrieved data is stored in the `data` property of the returned object. ### useScaffoldContractWrite: Use this hook to send a transaction to your smart contract to write data or perform an action. ```ts const { writeAsync, isLoading, isMining } = useScaffoldContractWrite({ contractName: "YourContract", functionName: "setGreeting", args: ["The value to set"], // For payable functions, expressed in ETH value: "0.01", // The number of block confirmations to wait for before considering transaction to be confirmed (default : 1). blockConfirmations: 1, // The callback function to execute when the transaction is confirmed. onBlockConfirmation: (txnReceipt) => { console.log("Transaction blockHash", txnReceipt.blockHash); }, }); ``` To send the transaction, you can call the `writeAsync` function returned by the hook. Here's an example usage: ```ts <button className="btn btn-primary" onClick={writeAsync}> Send TX </button> ``` This example sends a transaction to the `YourContract` smart contract to call the `setGreeting` function with the arguments passed in `args`. The `writeAsync` function sends the transaction to the smart contract, and the `isLoading` and `isMining` properties indicate whether the transaction is currently being processed by the network. ### useScaffoldEventSubscriber: Use this hook to subscribe to events emitted by your smart contract, and receive real-time updates when these events are emitted. ```ts useScaffoldEventSubscriber({ contractName: "YourContract", eventName: "GreetingChange", // The listener function is called whenever a GreetingChange event is emitted by the contract. // It receives the parameters emitted by the event, for this example: GreetingChange(address greetingSetter, string newGreeting, bool premium, uint256 value); listener: (greetingSetter, newGreeting, premium, value) => { console.log(greetingSetter, newGreeting, premium, value); }, }); ``` This example subscribes to the `GreetingChange` event emitted by the `YourContract` smart contract, and logs the parameters emitted by the event to the console whenever it is emitted. The `listener` function accepts the parameters emitted by the event, and can be customized according to your needs. ### useScaffoldEventHistory: Use this hook to retrieve historical event logs for your smart contract, providing past activity data. ```ts const { data: events, isLoading: isLoadingEvents, error: errorReadingEvents, } = useScaffoldEventHistory({ contractName: "YourContract", eventName: "GreetingChange", // Specify the starting block number from which to read events, this is a bigint. fromBlock: 31231n, blockData: true, // Apply filters to the event based on parameter names and values { [parameterName]: value }, filters: { premium: true } // If set to true it will return the transaction data for each event (default: false), transactionData: true, // If set to true it will return the receipt data for each event (default: false), receiptData: true }); ``` This example retrieves the historical event logs for the `GreetingChange` event of the `YourContract` smart contract, starting from block number 31231 and filtering events where the premium parameter is true. The data property of the returned object contains an array of event objects, each containing the event parameters and (optionally) the block, transaction, and receipt data. The `isLoading` property indicates whether the event logs are currently being fetched, and the `error` property contains any error that occurred during the fetching process (if applicable). ### useDeployedContractInfo: Use this hook to fetch details about a deployed smart contract, including the ABI and address. ```ts // ContractName: name of the deployed contract const { data: deployedContractData } = useDeployedContractInfo(contractName); ``` This example retrieves the details of the deployed contract with the specified name and stores the details in the deployedContractData object. ### useScaffoldContract: Use this hook to get your contract instance by providing the contract name. It enables you interact with your contract methods. For reading data or sending transactions, it's recommended to use `useScaffoldContractRead` and `useScaffoldContractWrite`. ```ts const { data: yourContract } = useScaffoldContract({ contractName: "YourContract", }); // Returns the greeting and can be called in any function, unlike useScaffoldContractRead await yourContract?.greeting(); // Used to write to a contract and can be called in any function import { useWalletClient } from "wagmi"; const { data: walletClient } = useWalletClient(); const { data: yourContract } = useScaffoldContract({ contractName: "YourContract", walletClient, }); const setGreeting = async () => { // Call the method in any function await yourContract?.setGreeting("the greeting here"); }; ``` This example uses the `useScaffoldContract` hook to obtain a contract instance for the `YourContract` smart contract. The data property of the returned object contains the contract instance that can be used to call any of the smart contract methods. ## Disabling type and linting error checks > **Hint** > Typescript helps you catch errors at compile time, which can save time and improve code quality, but can be challenging for those who are new to the language or who are used to the more dynamic nature of JavaScript. Below are the steps to disable type & lint check at different levels ### Disabling commit checks We run `pre-commit` [git hook](https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks) which lints the staged files and don't let you commit if there is an linting error. To disable this, go to `.husky/pre-commit` file and comment out `yarn lint-staged --verbose` ```diff - yarn lint-staged --verbose + # yarn lint-staged --verbose ``` ### Deploying to Vercel without any checks By default, Vercel runs types and lint checks before building your app. The deployment will fail if there are any types or lint errors. To ignore these checks while deploying from the CLI, use: ```shell yarn vercel:yolo ``` If your repo is connected to Vercel, you can set `NEXT_PUBLIC_IGNORE_BUILD_ERROR` to `true` in a [environment variable](https://vercel.com/docs/concepts/projects/environment-variables). ### Disabling Github Workflow We have github workflow setup checkout `.github/workflows/lint.yaml` which runs types and lint error checks every time code is **pushed** to `main` branch or **pull request** is made to `main` branch To disable it, **delete `.github` directory** ## Contributing to Scaffold-ETH 2 We welcome contributions to Scaffold-ETH 2! Please see [CONTRIBUTING.MD](https://github.com/scaffold-eth/scaffold-eth-2/blob/main/CONTRIBUTING.md) for more information and guidelines for contributing to Scaffold-ETH 2.
ligebit_spring_near_guest_book
.eslintrc.yml .github dependabot.yml workflows deploy.yml tests.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 App.js config.js index.html index.js tests integration App-integration.test.js ui App-ui.test.js
Challenge #4 https://ligebit.github.io/spring_near_guest_book/ sub account contract - guest_book.near_spring.testnet
kuutamolabs_rapid-gossip-sync-server
.github workflows build.yml Cargo.toml LICENSE-APACHE.md LICENSE-MIT.md LICENSE.md README.md docker-compose.yml src config.rs downloader.rs hex_utils.rs lib.rs lookup.rs main.rs persistence.rs serialization.rs snapshot.rs tests mod.rs tracking.rs types.rs verifier.rs
# rapid-gossip-sync-server This is a server that connects to peers on the Lightning network and calculates compact rapid sync gossip data. These are the components it's comprised of. ## Modules ### config A config file where the Postgres credentials and Lightning peers can be adjusted. Most adjustments can be made by setting environment variables, whose usage is as follows: | Name | Default | Description | |:-------------------------------------------|:--------------------|:-----------------------------------------------------------------------------------------------------------| | RAPID_GOSSIP_SYNC_SERVER_DB_HOST | localhost | Domain of the Postgres database | | RAPID_GOSSIP_SYNC_SERVER_DB_USER | alice | Username to access Postgres | | RAPID_GOSSIP_SYNC_SERVER_DB_PASSWORD | _None_ | Password to access Postgres | | RAPID_GOSSIP_SYNC_SERVER_DB_NAME | ln_graph_sync | Name of the database to be used for gossip storage | | RAPID_GOSSIP_SYNC_SERVER_NETWORK | mainnet | Network to operate in. Possible values are mainnet, testnet, signet, regtest | | RAPID_GOSSIP_SYNC_SERVER_SNAPSHOT_INTERVAL | 10800 | The interval in seconds between snapshots | | BITCOIN_REST_DOMAIN | 127.0.0.1 | Domain of the [bitcoind REST server](https://github.com/bitcoin/bitcoin/blob/master/doc/REST-interface.md) | | BITCOIN_REST_PORT | 8332 | HTTP port of the bitcoind REST server | | BITCOIN_REST_PATH | /rest/ | Path infix to access the bitcoind REST endpoints | | LN_PEERS | _Wallet of Satoshi_ | Comma separated list of LN peers to use for retrieving gossip | ### downloader The module responsible for initiating the scraping of the network graph from its peers. ### persistence The module responsible for persisting all the downloaded graph data to Postgres. ### snapshot The snapshotting module is responsible for calculating and storing snapshots. It's started up as soon as the first full graph sync completes, and then keeps updating the snapshots at a configurable interval with a 3-hour-default. ### lookup The lookup module is responsible for fetching the latest data from the network graph and Postgres, and reconciling it into an actionable delta set that the server can return in a serialized format. It works by collecting all the channels that are currently in the network graph, and gathering announcements as well as updates for each of them. For the updates specifically, the last update seen prior to the given timestamp, the latest known updates, and, if necessary, all intermediate updates are collected. Then, any channel that has only had an announcement but never an update is dropped. Additionally, every channel whose first update was seen after the given timestamp is collected alongside its announcement. Finally, all channel update transitions are evaluated and collected into either a full or an incremental update. ## License [Apache 2.0](LICENSE-APACHE.md) or [MIT](LICENSE-MIT.md), [at your option](LICENSE.md).
gspindev_bcapps
.gitpod.yml README.md near-blockvote blockvote .gitpod.yml README.md babel.config.js contract Cargo.toml 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 package-lock.json package.json src lib.rs target .rustc_info.json debug .fingerprint Inflector-f35c64bdcc83a85c lib-inflector.json autocfg-5eed84e18ea4d38d lib-autocfg.json borsh-derive-761b64255590aa8b lib-borsh-derive.json borsh-derive-internal-a0b35acc7193a1d0 lib-borsh-derive-internal.json borsh-schema-derive-internal-9f37d535db6c4ee3 lib-borsh-schema-derive-internal.json byteorder-4e4f329b09aeb3fd build-script-build-script-build.json convert_case-04564bf453e861d8 lib-convert_case.json derive_more-566efde9e14e316d lib-derive_more.json generic-array-bec72fe46df5bb50 build-script-build-script-build.json hashbrown-42f79a9088e90730 lib-hashbrown.json hashbrown-500377f64ca2c366 run-build-script-build-script-build.json hashbrown-59f80045d7236bc4 build-script-build-script-build.json indexmap-1f3eccbb1f1b3fcd build-script-build-script-build.json indexmap-5fbed610fb2dc724 run-build-script-build-script-build.json indexmap-dc7cadd029b47868 lib-indexmap.json itoa-63cf47e13d3db781 lib-itoa.json memchr-67a2ff728556da01 build-script-build-script-build.json near-rpc-error-core-2a45664b5ee46cf1 lib-near-rpc-error-core.json near-rpc-error-macro-adaa389a95c4c64d lib-near-rpc-error-macro.json near-sdk-core-046688a20778ab0c lib-near-sdk-core.json near-sdk-macros-bf97191d7917f968 lib-near-sdk-macros.json num-bigint-52ecb3e36d449c07 build-script-build-script-build.json num-integer-71fdd49567fe1141 build-script-build-script-build.json num-rational-caea7e28069930f5 build-script-build-script-build.json num-traits-b7d192d6afcd3dde build-script-build-script-build.json proc-macro-crate-3bf1cd013445ff64 lib-proc-macro-crate.json proc-macro2-2367cc8cea2612ce run-build-script-build-script-build.json proc-macro2-395b943ebbf040f9 lib-proc-macro2.json proc-macro2-b648b70837f1c6f4 build-script-build-script-build.json quote-54f9d5620c49c274 lib-quote.json ryu-52f1bb91b4882a97 build-script-build-script-build.json ryu-ce84462a99e7adbd run-build-script-build-script-build.json ryu-f8178accb5946406 lib-ryu.json serde-36a08739de5d3f86 lib-serde.json serde-473481d18b5ff63a build-script-build-script-build.json serde-835d15f265575fe4 run-build-script-build-script-build.json serde_derive-1e873dceb097610e lib-serde_derive.json serde_derive-2086cae8fa2c1432 build-script-build-script-build.json serde_derive-bfa500c2eadb07be run-build-script-build-script-build.json serde_json-2c194e4afdebdac8 run-build-script-build-script-build.json serde_json-4317fae4e2dcf266 lib-serde_json.json serde_json-a63a4500f066a2d2 build-script-build-script-build.json syn-56a5bf88b05722f8 run-build-script-build-script-build.json syn-7c765a4c08ca1842 build-script-build-script-build.json syn-c9ee3dc821cbeb4b lib-syn.json toml-bd2b444908e77606 lib-toml.json typenum-1c3be606d652c4ef build-script-build-script-main.json unicode-xid-bee6a97a0e141568 lib-unicode-xid.json version_check-255985b2dd15b66b lib-version_check.json wee_alloc-e93d2ce325a73164 build-script-build-script-build.json release .fingerprint Inflector-b1f6533151e7be62 lib-inflector.json autocfg-735fbe8c5dbf71b9 lib-autocfg.json borsh-derive-7d59e150cdb518c0 lib-borsh-derive.json borsh-derive-internal-2d78bb3d30492957 lib-borsh-derive-internal.json borsh-schema-derive-internal-85e7e315ba312ee7 lib-borsh-schema-derive-internal.json byteorder-81302f6bfc5eb31f build-script-build-script-build.json convert_case-d9acb4e6c727fc39 lib-convert_case.json derive_more-8d1bb25cd5020356 lib-derive_more.json generic-array-d6c13f53da57eaab build-script-build-script-build.json hashbrown-07494e18ba19bf78 run-build-script-build-script-build.json hashbrown-83b09df10dd1e41a build-script-build-script-build.json hashbrown-d7a8c4c4bbc55cd6 lib-hashbrown.json indexmap-777ecb07eb7c653b build-script-build-script-build.json indexmap-c1b64f93eeed18e9 lib-indexmap.json indexmap-fdbd2f59d739307d run-build-script-build-script-build.json itoa-bb11e9a682f4a0a3 lib-itoa.json memchr-59f60882f3a6fdc4 build-script-build-script-build.json near-rpc-error-core-87cd92434b55bc20 lib-near-rpc-error-core.json near-rpc-error-macro-988344ce9064fcf8 lib-near-rpc-error-macro.json near-sdk-core-2289a4a8c4b53ccd lib-near-sdk-core.json near-sdk-macros-c0403bcb04e8a0ea lib-near-sdk-macros.json num-bigint-74134c594c8b09e4 build-script-build-script-build.json num-integer-982480eb0675b6e4 build-script-build-script-build.json num-rational-ee02237c4a087c84 build-script-build-script-build.json num-traits-9155197deb68bde0 build-script-build-script-build.json proc-macro-crate-e11d07896b88a341 lib-proc-macro-crate.json proc-macro2-4a41766285ae3b71 lib-proc-macro2.json proc-macro2-9508761ff3b2ceb3 run-build-script-build-script-build.json proc-macro2-dff7675cc3d539cf build-script-build-script-build.json quote-af2ffbfaeb05cf39 lib-quote.json ryu-03d8d14e187b80dd build-script-build-script-build.json ryu-8aabbea4a072ce32 run-build-script-build-script-build.json ryu-b58a78f25485d0d7 lib-ryu.json serde-43577858555c1f0e lib-serde.json serde-d041d925dd72a9a7 build-script-build-script-build.json serde-f0856918557b9658 run-build-script-build-script-build.json serde_derive-2fda46d22992ac7e run-build-script-build-script-build.json serde_derive-34c1264feee50417 lib-serde_derive.json serde_derive-ec64f90e16c9291e build-script-build-script-build.json serde_json-314108b27f235f7e build-script-build-script-build.json serde_json-d24cdaf20879683a lib-serde_json.json serde_json-d2ee8bb4d740eab8 run-build-script-build-script-build.json syn-54daadb1bc6d3c9c lib-syn.json syn-5eff70ac5a70f6e0 run-build-script-build-script-build.json syn-e12e1ce835e719c1 build-script-build-script-build.json toml-832b9f05674868c2 lib-toml.json typenum-979d1ff71f05660b build-script-build-script-main.json unicode-xid-2b21b505d13ab61a lib-unicode-xid.json version_check-e88a35665327f85d lib-version_check.json wee_alloc-7ac7d6f4e423032d build-script-build-script-build.json wasm32-unknown-unknown debug .fingerprint ahash-eb636ec8915dddf7 lib-ahash.json aho-corasick-a71edad06bb68cab lib-aho_corasick.json base64-0ae58e1dbffe7e84 lib-base64.json block-buffer-20af8d642b837847 lib-block-buffer.json block-buffer-85b17d9b8595e159 lib-block-buffer.json block-padding-095fc83b1607738a lib-block-padding.json borsh-bf7950abe3f09d4c lib-borsh.json bs58-286532934081eba1 lib-bs58.json byte-tools-b7ac364c6d558430 lib-byte-tools.json byteorder-0cd1ed356486674f lib-byteorder.json byteorder-f5dc4b4e48bded04 run-build-script-build-script-build.json cfg-if-4d8a2758c80889c0 lib-cfg-if.json cfg-if-a77a3c4e042d055d lib-cfg-if.json digest-72529d28ecf61488 lib-digest.json digest-d4124ab6c18e79e5 lib-digest.json generic-array-0ecce5cce49dcea1 run-build-script-build-script-build.json generic-array-a51a241793992f40 lib-generic_array.json generic-array-f88c74110034607c lib-generic_array.json greeter-98ace302c5fafa12 lib-greeter.json hashbrown-88c4fd68d369e204 lib-hashbrown.json hashbrown-c79eeed063cebff2 lib-hashbrown.json hashbrown-d08c50da5660759f run-build-script-build-script-build.json hex-ed3e76e456925cba lib-hex.json indexmap-5c193501167d8447 run-build-script-build-script-build.json indexmap-b28a5ce6ad124174 lib-indexmap.json itoa-8131ef3e89947368 lib-itoa.json keccak-fec8796739ce5fde lib-keccak.json lazy_static-4d5361ccf5b352f5 lib-lazy_static.json memchr-25b196f1bd4b2ecc lib-memchr.json memchr-d7d50b3eb5e79daf run-build-script-build-script-build.json memory_units-27c0630f88317c76 lib-memory_units.json near-primitives-core-1dbb5cc6733d750e lib-near-primitives-core.json near-runtime-utils-2fc656fcfaaacd29 lib-near-runtime-utils.json near-sdk-ee3ca4da10262bbf lib-near-sdk.json near-vm-errors-979533521df46ffd lib-near-vm-errors.json near-vm-logic-4713d4cfd3563cc5 lib-near-vm-logic.json num-bigint-a7776bc10849fa10 lib-num-bigint.json num-bigint-cf5799adc943a33e run-build-script-build-script-build.json num-integer-1354f87f88c7c4b3 lib-num-integer.json num-integer-c1d009c0dcda2b1a run-build-script-build-script-build.json num-rational-8a750fca4189c112 run-build-script-build-script-build.json num-rational-9191d276205b351e lib-num-rational.json num-traits-2fa84436ba59c6a5 lib-num-traits.json num-traits-b827cec4781ff7ef run-build-script-build-script-build.json opaque-debug-9a055071732a2e05 lib-opaque-debug.json opaque-debug-ce59ec0a8ef85c91 lib-opaque-debug.json regex-180ae6db84ef7c43 lib-regex.json regex-syntax-64d72df1a7a24eed lib-regex-syntax.json ryu-cee8a9e3ef551249 run-build-script-build-script-build.json ryu-f5f5279d17e4558f lib-ryu.json serde-454350dad00c836f lib-serde.json serde-9c4e68c7bafb97ab run-build-script-build-script-build.json serde_json-89e9633a411c631e lib-serde_json.json serde_json-99a433b6f05242fb run-build-script-build-script-build.json sha2-f58f5f9043003f37 lib-sha2.json sha3-e89a3e3ea208ff02 lib-sha3.json typenum-5bdf061afe46b05e run-build-script-build-script-main.json typenum-5eb09d9567c7402c lib-typenum.json wee_alloc-87427b00e2478ff4 run-build-script-build-script-build.json wee_alloc-adb071298af20a95 lib-wee_alloc.json build num-bigint-cf5799adc943a33e out radix_bases.rs typenum-5bdf061afe46b05e out consts.rs op.rs tests.rs wee_alloc-87427b00e2478ff4 out wee_alloc_static_array_backend_size_bytes.txt release .fingerprint ahash-5733d2af5ab642f9 lib-ahash.json aho-corasick-358cd9fc49fc208f lib-aho_corasick.json base64-0ed85d98192b35cb lib-base64.json block-buffer-1e4e2337592206e5 lib-block-buffer.json block-buffer-c54763f257b15dd1 lib-block-buffer.json block-padding-c555c563296295f4 lib-block-padding.json borsh-beb3e822996c2cb4 lib-borsh.json bs58-41d69aa5ea2113ca lib-bs58.json byte-tools-fb87ed39c08375ce lib-byte-tools.json byteorder-0c3b7b13740da921 lib-byteorder.json byteorder-405f574730de3eef run-build-script-build-script-build.json cfg-if-b071a0b2275e82e2 lib-cfg-if.json cfg-if-d5346bc0bf7330e8 lib-cfg-if.json digest-0d4237bf4d9c1a6a lib-digest.json digest-adac54607d80ee38 lib-digest.json generic-array-217ce918508d02cd run-build-script-build-script-build.json generic-array-e67b0eb4308d514e lib-generic_array.json generic-array-f16946a2302dd633 lib-generic_array.json greeter-98ace302c5fafa12 lib-greeter.json hashbrown-2ec52ed5ef7e8301 run-build-script-build-script-build.json hashbrown-8c8841b45faaaabd lib-hashbrown.json hashbrown-ae7cd6c71d752e9a lib-hashbrown.json hex-7df3a25827098668 lib-hex.json indexmap-499bc4cee6a96e5a lib-indexmap.json indexmap-cb04952586968012 run-build-script-build-script-build.json itoa-809e1c13e2b226d3 lib-itoa.json keccak-8f1f086e7e9699d2 lib-keccak.json lazy_static-972e121ee292811f lib-lazy_static.json memchr-137fa0863f905d2c run-build-script-build-script-build.json memchr-e48956fbf149470d lib-memchr.json memory_units-6d9926a0d4bb6989 lib-memory_units.json near-primitives-core-c1d94f159e4a2fcc lib-near-primitives-core.json near-runtime-utils-a3cb73bd60125da8 lib-near-runtime-utils.json near-sdk-425250cb7ccbf675 lib-near-sdk.json near-vm-errors-8abc13bf4c874e4c lib-near-vm-errors.json near-vm-logic-27a1fbe8540f5631 lib-near-vm-logic.json num-bigint-5f3184d31ccdc4aa lib-num-bigint.json num-bigint-edd88df40ad0adeb run-build-script-build-script-build.json num-integer-3caf5a2e1cd3ffa6 run-build-script-build-script-build.json num-integer-80774b99740e0f81 lib-num-integer.json num-rational-461cc94cc1251d94 run-build-script-build-script-build.json num-rational-9439f578daeff963 lib-num-rational.json num-traits-542afd3e0b9f4731 run-build-script-build-script-build.json num-traits-d764c2a26c748628 lib-num-traits.json opaque-debug-e7c6e45d0f6dbcbc lib-opaque-debug.json opaque-debug-fbd12b4a5adf74d4 lib-opaque-debug.json regex-c45e85a87d9d3aa2 lib-regex.json regex-syntax-4308c62ce412d750 lib-regex-syntax.json ryu-17d9881e571cdd4b lib-ryu.json ryu-6c0eafb381d8ef83 run-build-script-build-script-build.json serde-8cfb315b6ee116ce lib-serde.json serde-a8f4a3c392c64d21 run-build-script-build-script-build.json serde_json-c74861dd6cf40b64 run-build-script-build-script-build.json serde_json-dd836d1a69b1c32b lib-serde_json.json sha2-e06d4e2ca3f7096b lib-sha2.json sha3-7e8ddc190e555192 lib-sha3.json typenum-4acd3ba97586d824 lib-typenum.json typenum-55ff30b9565f0355 run-build-script-build-script-main.json wee_alloc-2b2eac064dc92512 run-build-script-build-script-build.json wee_alloc-c61199675b501834 lib-wee_alloc.json build num-bigint-edd88df40ad0adeb out radix_bases.rs typenum-55ff30b9565f0355 out consts.rs op.rs tests.rs wee_alloc-2b2eac064dc92512 out wee_alloc_static_array_backend_size_bytes.txt package.json src App.js Home.js __mocks__ fileMock.js assets logo-black.svg logo-white.svg components NewPoll.js PollingStation.js config.js global.css index.html index.js jest.init.js main.test.js utils.js wallet login index.html package-lock.json package.json
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 blockvote 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 # bcapps
Lightency_nearcon-hackathon-lightency
.gitpod.yml README.md contract Cargo.toml README.md neardev dev-account.env src lib.rs dao_contract Cargo.toml README.md build.sh deploy.sh src lib.rs energy_pool_contract Cargo.toml README.md build.sh deploy.sh neardev dev-account.env src lib.rs frontend App.js Routes.js assets css global.css img index.js logo-black.svg logo-white.svg swaps Etoro_logo.svg components dao createProposal.js dashboards.js proposals.js governance charts chart1.js forms createDao.js tables daoList.js layouts Reusables LineChart.js layout.js styles.js shared Clock Clock.js Loading loader2.js loading.js styles.js Navbar navbar.js style.js Sidebar sidebar.js styles.js config.js dist Etoro_logo.ba873066.svg auto.0965e03f.js index.1afa09c0.css index.html primeicons.cdbe9e7f.svg index.html index.js near-api.js near-config.js package-lock.json package.json pages BondPage.js DaoPage.js GovernancePage.js HomePage.js OnDevelopmentModPage.js StakePage.js StakingPoolPage.js SwapPage.js VotingPage.js styles globalStyles.js theme.js variables.js ui-components.js utils.js utils timeConverter.js ft Cargo.toml build.sh src lib.rs fundmanager Cargo.toml README.md build.sh deploy.sh src lib.rs integration-tests Cargo.toml src tests.rs package-lock.json package.json rewarder .gitpod.yml README.md contract Cargo.toml README.md build.sh deploy.sh src lib.rs integration-tests Cargo.toml src tests.rs package-lock.json package.json rewardpoolcontract Cargo.toml README.md build.sh deploy.sh src lib.rs staking .gitpod.yml README.md contract Cargo.toml README.md build.sh deploy.sh src lib.rs integration-tests Cargo.toml src tests.rs package-lock.json package.json stakingpool .gitpod.yml README.md contract Cargo.toml README.md build.sh deploy.sh src lib.rs integration-tests Cargo.toml src tests.rs package-lock.json package.json treasury Cargo.toml README.md build.sh deploy.sh src lib.rs
# 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>`. # 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>`. 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 # 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>`. # 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>`. 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 # 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>`. 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 # 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>`. 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 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 # 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>`. # 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>`.
pantemon_question
README.md contract Cargo.toml README.md rustfmt.toml scripts build.sh deploy.sh dev-deploy.sh init-args.js src contract.rs lib.rs utils.rs
# NEAR Smart Contract Rust Template Project structure for writing smart contracts in Rust for NEAR Protocol # Required Software - Rust 1.58 + cargo - Node.js - NEAR CLI 3.1 # Authors - Jacob Lindahl <jacob@near.foundation> [@sudo_build](https://twitter.com/sudo_build) # question
marco-sundsk_senderwallet-registrar
README.md contracts Cargo.toml README.md __tests__ sw-registrar helper.ts operator.ava.ts owner.ava.ts package-lock.json package.json sw-registrar Cargo.toml build_local.sh src lib.rs owner.rs user_info.rs utils.rs views.rs tsconfig.json
# Registrar Contract for Sender Wallet An upgradable IMS contract for Sender-Wallet user management. ## Description * Everyone can check a given user's information. * Operators can do all above and can add user information. * Owner can do all above and can upgrade the contract and management Operators. ### For Everyone ```rust pub struct ContractMetadata { pub version: String, /// the owner of the contract, normally a DAO pub owner_id: AccountId, /// those operators's near accounts pub operators: Vec<AccountId>, /// how many users currently managed pub user_count: U64, } /// get contract basic info pub fn metadata(&self) -> ContractMetadata; pub struct HumanReadableUserInfo { // user NEAR Account, the key to find a user pub account_id: AccountId, // user nick name on SenderWallet side pub user_name: String, // Timestamp (secs) that adding this user pub register_at: u32, } /// Check a given user's UserInfo pub fn get_user_info(&self, account_id: ValidAccountId) -> Option<HumanReadableUserInfo>; ``` ### For Operators ```rust #[payable] pub fn register_new_user(&mut self, accound_id: ValidAccountId, user_name: String); ``` ### For Owner ```rust pub fn set_owner(&mut self, owner_id: ValidAccountId); pub fn extend_operators(&mut self, operators: Vec<ValidAccountId>); pub fn remove_operators(&mut self, operators: Vec<ValidAccountId>); ``` ## Build 1. Install `rustup` via [https://rustup.rs/](https://rustup.rs/) 2. Run the following: ```bash rustup default stable rustup target add wasm32-unknown-unknown ``` 3. Build: ```bash cd sw-registrar ./build_local.sh ``` 4. Test: ```bash cd sw-registrar cargo test ``` ## Deploying to Testnet To deploy to TestNet, you can use next command: ```bash npm install -g near-cli near dev-deploy res/sw_registrar_local.wasm ``` This will output on the contract ID it deployed. # senderwallet-registrar SenderWallet User Registrar Contract ## Build In `contracts` Dir: - Build all artifacts: `make` ## Test In `contracts` Dir: - Run all tests: `make test` - Run with some flags: - Run specific test file: `TEST_FILE={filename} make test` - Print contract logs: `LOGS=1 make test`
near_near-indexer-events
Cargo.toml README.md migrations 20220712171424_initial.sql src configs.rs db_adapters coin legacy DOC.md aurora.rs mod.rs rainbow_bridge.rs skyward.rs tkn_near.rs wentokensir.rs wrap_near.rs mod.rs nep141_events.rs event_types.rs events.rs mod.rs nft mod.rs nep171_events.rs numeric_types.rs lib.rs main.rs metrics.rs models coin_events.rs contracts.rs mod.rs nft_events.rs
# Indexer Events Async Postgres-compatible solution to load the data from NEAR blockchain. Based on [NEAR Lake Framework](https://github.com/near/near-lake-framework-rs). See [Indexer Base](https://github.com/near/near-indexer-base#indexer-base) docs for all the explanations, installation guide, etc. This solution collects balance-changing events about FTs, NFTs, etc. - We can index the blockchain from any point of time. The code does not check if all the previous history is collected. - Potentially, some events may be skipped. - We do not check the correctness of collected events, it should be done separately. - We can re-run infinite number of indexers writing at the same DB, they may index same or different parts of the blockchain. It should not break the flow. ### Why existing `assets__*` tables are not enough? `assets__non_fungible_token_events`, `assets__fungible_token_events` do not have the sorting column. In the current solution, we've added artificial `event_index` column. The new `coin_events` table stores the data in the format of affected/involved account_id, that simplifies filtering by affected `account_id`. `coin_events` still does not have `absolute_value` column, so you have to collect it from RPC if needed. ### What if my contract does not produce events? Please go and update your contract with our new [SDK](https://github.com/near/near-sdk-rs). If it's important for you to collect all the previous history as well, you need to make the contribution and implement your own legacy handler. You can use [existing handlers](src/db_adapters/coin/legacy) as the example, [wrap_near](src/db_adapters/coin/legacy/wrap_near.rs) may be a good starting point. ### My contract produces events/there's a custom legacy logic for my contract, but the Enhanced API still ignores me. Why? It means that we've found inconsistency in the data you provided with the data we've queried by RPC. To be more clear, we collected all the logs/performed all the legacy logic, we know all the changed balances for all the active users at the end of the block. After that, we ask the RPC to provide all the needed balances. The numbers should be the same. If they are not the same, it means the data is inconsistent. When we meet the inconsistency, we mark such contract as "non-trusted". If you want to fix this, you need to write/edit [legacy handler](src/db_adapters/coin/legacy/DOC.md) for your contract. ### Contribution Guide Please refer to this [guide](https://github.com/near/near-indexer-for-explorer/blob/master/CONTRIBUTING.md) before submitting PRs to this repo
PrimeLabCore_tenk-frontend-template
README.md package.json public index.html src Contexts BuyContext BuyContext.js index.js Main.js assets images copy-icon.svg faq-ellipse-left.svg faq-ellipse-right.svg faq-kat.svg footer-near-logo.svg generate.svg hero-big-cat.svg hero-cloud1.svg hero-cloud2.svg hero-cloud3.svg hero-ellipse.svg leran-background-circle.svg leran-background-ellipse.svg link-drop-background.svg nearkat-item-clothes.svg nearkat-item-hat.svg nearkat-item-palette.svg nearkat-logo.svg nfts-kat1.svg nfts-kat2.svg nfts-kat3.svg nfts-kat4.svg rarity-background-gradient.svg rarity-common.svg rarity-kat1.svg rarity-kat2.svg rarity-kat3.svg rarity-kat4.svg rarity-rare.svg rarity-rate-kat1.svg rarity-rate-kat2.svg rarity-rate-kat3.svg rarity-rate-kat4.svg rarity-super-rare.svg rarity-uncommon.svg rarity-very-rare.svg reveal.svg roadmap-background-clouds.svg roadmap-ellipse-left.svg roadmap-ellipse-right.svg share-social discord.svg email.svg facebook.svg instagram.svg linkedin.svg telegram.svg twitter.svg wechat.svg social-face.svg social-mintbase.svg social-twitter.svg sold-out-kat.svg components Buy BuyMore index.js index.js BuyMoreBtn index.js ConnectWalletBtn index.js FAQ index.js Generate index.js GenerateCountBtn index.js Hero index.js Learn index.js Loader Loader.js index.js Navigation Navigation.js index.js NearkatsList index.js NftItem NftItem.js index.js NftItemInfo NftItemInfo.js index.js NftList NftList.js index.js NumberOfBuy index.js Price index.js Rarity index.js rarityData.js RateList index.js RenderRoutes RenderRoutes.js RouteWithSubRoutes RouteWithSubRoutes.js index.js index.js Roadmap index.js ScrollToTop index.js ShareSocialLinks index.js SocialLinks index.js config.js hooks useCopyToClipboard.js index.js layouts Footer Footer.js index.js Header Header.js index.js Layout Layout.js index.js pages Home Home.js index.js LinkDrop LinkDrop.js SaveBtn index.js ShareableCircle index.js ShareableInput index.js ShareableLink index.js index.js MyNFTS MyNFTS.js dataNfts.js index.js NoNfts index.js Reveal dataReveal.js index.js routes.js setupTests.js state app.js near.js utils near-utils.js state-utils.js
# Simple React App template 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.
ngocquang_near-tutorial-1
README.md contract Cargo.toml src lib.rs package.json
near-tutorial-1 near deploy --wasm-file out/main.wasm --account-id contract1.chihiro.testnet --master-account chihiro.testnet near create-account contract1.chihiro.testnet --masterAccount chihiro.testnet
hermes1108_near-mr-giggles-nft-smart-contract
Cargo.toml README.md build.sh neardev dev-account.env src approval.rs enumeration.rs events.rs internal.rs lib.rs metadata.rs mint.rs nft_core.rs royalty.rs util.rs
# TBD
gyan0890_NEAR-Quest4-Auction
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
# `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) 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)
hrs025_Car-Marktplace
README.md as-pect.config.js asconfig.json package.json scripts 1.init.sh 2.run.sh src as-pect.d.ts as_types.d.ts sample __tests__ index.unit.spec.ts asconfig.json assembly as_types.d.ts index.ts model.ts tsconfig.json utils.ts tsconfig.json utils.ts
# Near-Car # Near-Car
laitsky_tamagotchi-on-near
README.md client README.md package.json public index.html manifest.json robots.txt src App.js App.test.js components Game.js HowToPlay.js MintNFT.js Navbar.js Play.js RenderNotConnected.js config.js index.css index.js logo.svg reportWebVitals.js serviceWorker.js setupTests.js test-utils.js theme.js utils.js contract .idea codeStyles codeStyleConfig.xml modules.xml vcs.xml Cargo.toml README.md build.sh deploy.sh src external.rs lib.rs test.sh nft-contract Cargo.toml README.md build.sh deploy.sh src approval.rs enumeration.rs events.rs internal.rs lib.rs metadata.rs mint.rs nft_core.rs royalty.rs
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.<br /> Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.<br /> You will also see any lint errors in the console. ### `npm test` Launches the test runner in the interactive watch mode.<br /> 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.<br /> 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.<br /> 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 ### Analyzing the Bundle Size This section has moved here: 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 ### Advanced Configuration This section has moved here: 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 ### `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 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 # Tamagotchi on NEAR [Deployed app (testnet)](tamagotchi-on-near.vercel.app) Simple Tamagotchi clone made fully on-chain with NEAR and Rust. This repository serves 3 main folders: - `client`: Where the frontend code is written — basically the program where the user will interact with. Made using React and Chakra. - `contract`: Where the smart contract is written. Made using NEAR SDK and Rust. This folder contains the business logic of the game that meets the game spec (written in the next section) such as feeding and playing. - `nft-contract`: The repo to integrate the game with NEP-171 NFT standards so every character is a non-fungible where every account ID has different NFT. Not written from scratch due to the nature of complexities of NFT standards from NEAR itself (still ongoing development to simplify the whole process). It was taken from NEAR NFT contract templates. # Game Specification ## Tamagotchi character Each tamagotchi is an unique NFT based on NEP-171 NFT standards, hence, tradable. ## Feed and hungry mechanics The player can give food to the tamagotchi. There are two types of food: 1. Meal — fills hungry hearts, adds 1 to tamagotchi weight 2. Snack — fills one hungry heart, adds 2 to the tamagotchi weight Overfeeding will make tamagotchi sick ## Play mechanics The player can play with the tamagotchi. The gameplay is simple, the player has to guess where the tamagotchi will be facing. The options are : left, right. If the player guess is correct, then the player wins. Playing the game will reduce tamagotchi weight and hungry meter by 1 Winning the game will increase tamagotchi happy heart by 1 ## Medicine If tamagotchi is sick, giving medicine will cure it. A sick tamagotchi cannot be fed or played. ## Sickness The tamagotchi will be sick if giving tamagotchi too manys nacks after the hungry meter is 4. If tamagotchi get sick, decrease the happiness meter by 3. # Screenshots Welcome page: [![Screen-Shot-2022-10-01-at-21-09-54.png](https://i.postimg.cc/pr8bX9YR/Screen-Shot-2022-10-01-at-21-09-54.png)](https://postimg.cc/cts5FLbb) Mint page (if user has yet to mint the NFT tamagotchi character): [![Screen-Shot-2022-10-01-at-21-10-54.png](https://i.postimg.cc/qMdWxvx6/Screen-Shot-2022-10-01-at-21-10-54.png)](https://postimg.cc/JtPT1mgR) Play page: [![Screen-Shot-2022-10-01-at-21-09-43.png](https://i.postimg.cc/2jnKyfNk/Screen-Shot-2022-10-01-at-21-09-43.png)](https://postimg.cc/0r2fXFNF) # 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/)