repoName
stringlengths 7
77
| tree
stringlengths 0
2.85M
| readme
stringlengths 0
4.9M
|
---|---|---|
Giftea_NEAR-tour-ui | .env
.eslintrc.json
README.md
contract
README.md
as-pect.config.js
asconfig.json
package.json
scripts
1.deploy.sh
10.rate_tour.sh
11.delete_tour.sh
2.create_tour.sh
3.get_tour.sh
4.get_tours.sh
5.buy_tour.sh
6.update_tour.sh
7.like_tour.sh
8.dislike_tour.sh
9.comment_on_tour.sh
README.md
src
as-pect.d.ts
as_types.d.ts
tour
README.md
__tests__
README.md
as-pect.d.ts
index.unit.spec.ts
asconfig.json
assembly
index.ts
models
commentModel.ts
rateModel.ts
tourModel.ts
tsconfig.json
utils.ts
package.json
public
index.html
manifest.json
robots.txt
src
App.js
Router.js
components
index.js
index.css
index.js
pages
AddTour.js
Home.js
HomePage.js
Tour.js
styles
Home.css
utils
DateUtils.js
config.js
near.js
tour.js
| 
## Design
### Interface
```ts
function setTour
```
- "Change" function (ie. a function that alters contract state)
- Receives a `Tour` object as a parameter, creates a new Tour and returns the success message
```ts
function getTour
```
- "View" function (ie. a function that does not alters contract state)
- Recieves a Tour's `id` as parameter
- Returns a Tour object
```ts
function getTours
```
- "View" function (ie. a function that does not alters contract state)
- Returns the whole Tours details/content
```ts
function buyTour
```
- "Change" function (ie. a function that alters contract state)
- Recieves a Tour's `id` as parameter
- This fetches a Tour by the `id` parameter and increaments it's sold amount
```ts
function updateTour
```
- "Change" function (ie. a function that alters contract state)
- Receives a `Tour` object as a parameter, updates Tour and returns the success message
```ts
function deleteTour
```
- "Change" function (ie. a function that alters contract state)
- Recieves a Tour's `id` as parameter
- Fetches the Tour by `id`, deletes it together with it's comments and rates
```ts
function likeTour
```
- "Change" function (ie. a function that alters contract state)
- Recieves a Tour's `id` as parameter
- Fetches the Tour by `id`, and adds a like to it.
- If a like has been added by a user and the function is called again, it removes the like.
- If a dislike has been added by a user and the function is called, it removes the dislike and adds a like
```ts
function dislikeTour
```
- "Change" function (ie. a function that alters contract state)
- Recieves a Tour's `id` as parameter
- Fetches the Tour by `id`, and adds a dislike to it.
- If a dislike has been added by a user and the function is called again, it removes the dislike.
- If a like has been added by a user and the function is called, it removes the like and adds a dislike
```ts
function commentOnTour
```
- "Change" function (ie. a function that alters contract state)
- Receives a `Comment` object as a parameter, fetches the Tour by the `tourId` value within the `Comment` object
- Creates a new comment and adds it to the Tour
```ts
function rateTour
```
- "Change" function (ie. a function that alters contract state)
- Receives a `Rate` object as a parameter, fetches the Tour by the `tourId` value within the `Rate` object
- Creates a new rate and adds it to the Tour
- The function will not execute if a user has rated before
# Getting Started with NEAR Tours
Near Tours allows a user who has access to the application to create tours and interact with tours created by other users. Peculiar functionalities are:
- Create Tour
- Delete Tour (You can only delete tours you created)
- A user can like or dislike a tour
- A user can leave a comment on a tour
- A user can rate a tour only once!
## [Live Link](https://giftea.github.io/NEAR-tour-ui)
<img width="1439" alt="Screenshot 2022-06-01 at 11 20 21 PM" src="https://user-images.githubusercontent.com/70780434/171515612-871777c8-a6ef-41b0-b795-4312a42146b0.png">
## This a demo for dacade
[Dacade](https://dacade.org/signup?invite=giftea)
### Unit Tests
Unit tests can be run with the command below:
```
yarn run test
```
### Tests for Contract in `index.unit.spec.ts`
```
[Describe]: Checks for creating account
[Success]: โ creates a tour
[Describe]: View a single Tour
[Success]: โ Returns a single tour
[Success]: โ Smart contract panics when there's no Tour with such ID
[Describe]: To purchase a single Tour
[Success]: โ purchases a single tour and returns a response
[Success]: โ Smart contract panics when there's no Tour with such ID
[Describe]: To delete a single Tour
[Success]: โ deletes a single tour and returns a response
[Success]: โ Smart contract panics when there's no Tour with such ID
[Describe]: To like on a single Tour
[Success]: โ likes on a single tour and returns a response
[Success]: โ unlikes on a single tour and returns a response
[Success]: โ Smart contract panics when there's no Tour with such ID
[Describe]: To dislike on a single Tour
[Success]: โ dislikes on a single tour and returns a response
[Success]: โ undislikes on a single tour and returns a response
[Success]: โ Smart contract panics when there's no Tour with such ID
[Describe]: Comment on tour
[Success]: โ comments on tour
[Success]: โ Smart contract panics when there's no Tour with such ID
[Describe]: Rate tour
[Success]: โ rates tour
[Success]: โ Smart contract panics when there's no Tour with such ID
[File]: src/tour/__tests__/index.unit.spec.ts
[Groups]: 9 pass, 9 total
[Result]: โ PASS
[Snapshot]: 0 total, 0 added, 0 removed, 0 different
[Summary]: 17 pass, 0 fail, 17 total
[Time]: 220.521ms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[Result]: โ PASS
[Files]: 1 total
[Groups]: 9 count, 9 pass
[Tests]: 17 pass, 0 fail, 17 total
[Time]: 15046.675ms
โจ Done in 32.52s.
```
## Setting up your terminal
The scripts in this folder support a simple demonstration of the contract.
It uses the following setup:
```txt
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ โ
โ โ โ
โ โ โ
โ โ โ
โ โ โ
โ โ โ
โ โ โ
โ A โ B โ
โ โ โ
โ โ โ
โ โ โ
โ โ โ
โ โ โ
โ โ โ
โ โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
```
### Terminal **A**
*This window is used to compile, deploy and control the contract*
- Environment
```sh
export CONTRACT= # depends on deployment
export OWNER= # any account you control
# for example
# export CONTRACT=dev-1654101510417-62946478212070
# export OWNER=giftea.testnet
```
- Commands
```sh
1.deploy.sh # cleanup, compile and deploy contract
2.create_tour.sh # call methods on the deployed contract
```
### Terminal **B**
*This window is used to render the contract account storage*
- Environment
```sh
export CONTRACT= # depends on deployment
# for example
# export CONTRACT=dev-1654101510417-62946478212070
```
- Commands
```sh
# monitor contract storage using near-account-utils
# https://github.com/near-examples/near-account-utils
watch -d -n 1 yarn storage $CONTRACT
```
---
## OS Support
### Linux
- The `watch` command is supported natively on Linux
- To learn more about any of these shell commands take a look at [explainshell.com](https://explainshell.com)
### MacOS
- Consider `brew info visionmedia-watch` (or `brew install watch`)
### Windows
- Consider this article: [What is the Windows analog of the Linux watch command?](https://superuser.com/questions/191063/what-is-the-windows-analog-of-the-linux-watch-command#191068)
# Sample
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
The goal of this repository is to make it as easy as possible to get started writing unit tests for AssemblyScript contracts built to work with NEAR Protocol.
## Usage
### Getting started
1. clone this repo to a local folder
2. run `yarn`
3. run `yarn install`
4. run `yarn test`
### Top-level `yarn` commands
- run `yarn test` to run all tests
- (!) be sure to run `yarn build:release` at least once before:
- run `yarn test:unit` to run only unit tests
- run `yarn build` to quickly verify build status
- run `yarn deploy` to quickly run the `./scripts/1.deploy.sh` command to deploy smart contract
- run `yarn clean` to clean up build folder
### Other documentation
- tour contract and test documentation
- see `/src/tour/README` for contract interface
- see `/src/tour/__tests__/README` for tour unit testing details
- see `/scripts/README` for running scripts
### Contracts and Unit Tests
```txt
src
โโโ tour <-- tour contract
โย ย โโโ README.md
โย ย โโโ __tests__
โย ย โย ย โโโ README.md
โย ย โย ย โโโ index.unit.spec.ts
โย ย โโโ assembly
โย ย โโโ index.ts
| โโโ models
| โโโ commentModel.ts
| โโโ rateModel.ts
| โโโ tourModel.ts
|
โโโ utils.ts <-- shared contract code
```
### Helper Scripts
```txt
scripts
โโโ 1.deploy.sh
โโโ 2.create_tour.sh
โโโ 3.get_tour.sh
โโโ 4.get_tours.sh
โโโ 5.buy_tour.sh
โโโ 6.update_tour.sh
โโโ 7.like_tour.sh
โโโ 8.dislike_tour.sh
โโโ 9.comment_on_tour.sh
โโโ 10.rate_tour.sh
โโโ 11.delete_tour.sh
โโโ README.md <-- instructions
```
## Deployed Contract Link
[Check out the deployed Smart Contract on explorer.testnet.near.org](https://explorer.testnet.near.org/transactions/4Y8PBn45mJtyDD4ir1aopPkMNqZdfC2hwJrXhTxAi7cA)
|
Niceboy0829_Rust---Net-145-and-nep-148-contract | README.md
fungible_token_metadata.rs
storage_manager.rs
| # Rust---Net-145-and-nep-148-contract
|
fabianferno_perma-books | .devcontainer
devcontainer.json
.env
README.md
config
env.js
getHttpsConfig.js
jest
babelTransform.js
cssTransform.js
fileTransform.js
modules.js
paths.js
pnpTs.js
webpack.config.js
webpackDevServer.config.js
package.json
public
index.html
manifest.json
robots.txt
scripts
build.js
start.js
test.js
src
logo.svg
react-app-env.d.ts
reportWebVitals.ts
setupTests.ts
tsconfig.json
| # PermaBooks
<img src="https://raw.githubusercontent.com/fabianferno/perma-books/main/ezgif.com-gif-maker.gif" width="100%" />
Perma-books is a dApp that provides **permanent decentralized archival solution** for publications, compositions, and literature. This platform is a simple and effective way to store data forever on-chain without paying incentives on a regular basis!
## Inspiration
As years pass by, we tend to forget the old literature and resources that helped us a lot as we grew up. These data can easily be lost or erased if not maintained regularly. We searched for multiple solutions but everything has its own downsides. We wanted a solution that can store data permanently without even having to be maintained or incentivized frequently.
## What it does
Perma-books provides a user-friendly UI experience to store data directly hassle-free. First, the user connects his polygon wallet to the website and then he connects his account to any one of the public bundlr networks. After connecting, One can easily upload any files from his computer and bundle them instantly once the transaction is signed. It may take a few minutes to deploy it on the chain. As soon as the files are deployed we receive the transaction ID, through which we can directly access the data via www.arweave.net/TX_ID
## How we built it
Perma-books is powered by Arweave and bundlr network. It has a _next.js_ app with a _react_ frontend that makes use of _chakra-ui_ design system. The file gets stored in remote arweave nodes permanently. Thanks to the documentation and resource materials. It made our work much easier.
## Accomplishments that we're proud of
We're excited as this is our first blockchain project. It was quite challenging to understand and work with the new technologies. But we started the project and worked on it with determination to complete it in a short span of 4 days. It was really amazing to see the application turn out the way we expected it to. Thanks to Arweave!
## What we learned
We learned various concepts underlying Arweave and bundlr network. We also learned to use a new javascript component library _chakra-ui_. We experimented in creating wallets in metamask and arweave, archiving webpages using arweave, and much more.
## What's next for Perma-books
_Perma-books_ has the potential to rapidly advance as our team of engineers always work towards bringing more advancements and innovations for the betterment of this world. Educational videos or images can also be bundled in the bundlr network and saved on-chain using Arweave.
Finally, we'd like to thank the developers of Arweave who provided instant support when we faced problems. The amazing documentation of Arweave and bundlr helped us to work on our project with ease. It was a wonderful development experience as we look forward to integrating many of our blockchain applications using Arweave because of its versatility and flexibility to be able to work with multiple chains.
Developed with โค๏ธ by
- @fabianferno
- @gabrielantonyxaviour
|
jumpsiegel_nearkey | Cargo.toml
NOTES.md
README.md
foo.js
package-lock.json
package.json
src
lib.rs
test.ts
| welcome to wormhole on near
|
Mr-OMD_FirstNearPathPractice | 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.
[](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.
[](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
```
[](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
```
|
mashharuki_BikeSharingDapp | README.md
near_bike_share_dapp
.gitpod.yml
README.md
contract
Cargo.toml
src
lib.rs
frontend
App.js
__mocks__
fileMock.js
assets
css
global.css
img
logo-black.svg
logo-white.svg
js
near
config.js
utils.js
index.html
index.js
integration-tests
package.json
rs
Cargo.toml
src
tests.rs
src
main.ava.ts
package.json
| # BikeSharingDapp
React.js ใจ Rust ใงๆง็ฏใใ่ช่ปข่ปใทใงใขใชใณใฐ Dapp ้็บ็จใฎใชใใธใใชใงใใ
### WebAssembly(WASM)ใจใฏ
ใใฉใฆใถใงใใญใฐใฉใ ใ้ซ้ๅฎ่กใใใใใฎใใใใฉใฆใถไธใงๅใใใคใใชใณใผใใฎๆฐใใใใฉใผใใใ(ไปๆง)ใใฎใใจใ
Google, Microsoft, Mozzila, Apple ใซใใฃใฆไปๆงใ็ญๅฎใใ้็บใ้ฒใใใใฆใใใ
C/C++ใ RustใGolangใTypeScript ใชใฉใใใณใณใใคใซใๅฏ่ฝใ
### NEAR ใๆก็จใใในใใฌใผใธในใใผใญใณใฐใซใคใใฆ
ใณใณใใฉใฏใใฎใขใซใฆใณใใฏใใญใใฏใใงใผใณไธใงไฝฟ็จใใใในใฆใฎในใใฌใผใธใใซใใผใใใฎใซๅๅใชๆฎ้ซ(NEAR)ใๆใฃใฆใใชใใใฐใชใใชใใใฆใผใถใผใๅขใใใจใใฎในใใฌใผใธใณในใใๅขใใฆใใใใใใใฆใผใถใผใซๆฏๆใฃใฆใใใใใจใใ่ใใในใใฌใผใธในใใผใญใณใฐใงใใใ
### ใขใซใฆใณใไฝๆใณใใณใ
```
near generate-key ft_mashharuki.testnet
```
### ใญใผใซใซใงไฝๆใใใขใซใฆใณใใ NearWallet ใซใคใณใใผใใใๆนๆณ
ไฝๆใใใขใซใฆใณใ ID ใจ privatekey ใๅใ่พผใใง URL ใๅฉใ
[https://wallet.testnet.near.org/auto-import-secret-key#YOUR_ACCOUNT_ID/YOUR_PRIVATE_KEY](https://wallet.testnet.near.org/auto-import-secret-key#YOUR_ACCOUNT_ID/YOUR_PRIVATE_KEY)
### ใตใใขใซใฆใณใไฝๆใณใใณใ
```cmd
export ID=ft_mashharuki.testnet
near create-account sub.$ID --masterAccount $ID --initialBalance 30
```
### ไปๅใในใ็จใฎไฝๆใใใขใซใฆใณใ
1. ft_mashharuki.testnet
2. sub.ft_mashharuki.testnet(FT ใณใณใใฉใฏใใใใญใคๆธใฟ)
### ้็บ็จใฎไฝๆใใใขใซใฆใณใใฎใใผใขใใใฏใณใผใ(้็บ็จใชใฎใงๆฌ็ชใงใฏไฝฟ็จใใชใใใจ๏ผ๏ผ)
```
nothing aisle fade bid fashion furnace approve sentence frog exchange citizen advance
```
### FT ใฎใใใญใคใใฉใณใถใฏใทใงใณ
[https://explorer.testnet.near.org/transactions/EmqAZmPPgsgnZvgmpXQxYKvdaSr9yb2VbKe57tab5cmM](https://explorer.testnet.near.org/transactions/EmqAZmPPgsgnZvgmpXQxYKvdaSr9yb2VbKe57tab5cmM)
### ้ๅฝข็ๆใณใใณใ
`npx [email protected] --frontend=react --contract=rust near_bike_share_dapp`
### ใณใณใฝใผใซใซ่กจ็คบใใใ URL ๆ
ๅ ฑ
```cmd
see: https://explorer.testnet.near.org/accounts/mashharuki.testnet
App.js:187 see: https://explorer.testnet.near.org/accounts/dev-1664367873698-91420483511088
```
### ในใใผใใณใณใใฉใฏใใฎใในใใณใใณใ
`yarn test:unit`
```cmd
running 3 tests
test tests::check_default ... ok
test tests::check_inspecting_account ... ok
test tests::return_by_other_account - should panic ... ok
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests bike_share
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
โจ Done in 16.48s.
```
### ในใใผใใณใณใใฉใฏใใฎ็ตๅใในใใณใใณใ
`yarn test:integration:rs`
```cmd
Finished dev [unoptimized + debuginfo] target(s) in 4.09s
Running `target/debug/examples/integration-tests`
2022-10-02T03:42:05.442562Z DEBUG stats: EpochId(`11111111111111111111111111111111`) Orphans: 0 With missing chunks: 0 In processing 0
2022-10-02T03:42:15.425218Z DEBUG stats: EpochId(`11111111111111111111111111111111`) Orphans: 0 With missing chunks: 0 In processing 0
16 AquR2kK8j2PrZy68pLwafPRoHG5DoDCYKqbqXZPUC85i Processed in progress for 0ms Chunks:(โ))
15 7bJvc1NMdUPH8PfQBTmdHXz7nj6tesBHUVeCQJWMma96 Processed in progress for 1ms Chunks:(โ))
14 x9PgUYDZXjCiMGquFbC4AsFCwcGqMNRQztHdJjkcctG Processed in progress for 1ms Chunks:(โ))
13 5djvxjYD1YYSpSKuT5HsYgtTjPTgK39P5nCXCuBmFTK9 Processed in progress for 0ms Chunks:(โ))
12 3WU71KsLjf9CixYiFGXdazbLz5mKzams1Ykd4ZsHxvq3 Processed in progress for 1ms Chunks:(โ))
11 GocWFY5kL4v4X4BoPkArMQKEdHvwyyRdjtDuf7Nn9Udh Processed in progress for 1ms Chunks:(โ))
10 898opjWfcxfphbByYZCs15ug383ArsFX6ZLZGUVSKwtQ Processed in progress for 1ms Chunks:(โ))
9 7RPMov1zS7EN1isXBHiGwUnLHqxjEZhsuspyfYjJhUzz Processed in progress for 0ms Chunks:(โ))
8 AsofRiS4yW3uQY5ijMb72SsiYDVfKn3mmQJZsvqW3quo Processed in progress for 3ms Chunks:(โ))
7 GbNKn2uSqfVUZ5TgxbrswitAAREha6u2xU61CPYVaci Processed in progress for 5ms Chunks:(โ))
6 FL2D5nWLCK9xDZc5AY7qkWV1bVpZdm9gE6VJFeCWfUtK Processed in progress for 0ms Chunks:(โ))
5 A8CzdMScNjKpuMTCoHavu4mt7rFqkcfCVS8EwjTMFk4i Processed in progress for 1ms Chunks:(โ))
4 3TtnEewz1oRKovdHNcjU93Ld1X8FxNRQPd9gU5yQathW Processed in progress for 1ms Chunks:(โ))
3 ezKtwaU2tmLMsTVkYVZuWoMx87yfZjd6TdFP8cN527z Processed in progress for 216ms Chunks:(โ))
2 amxwM5JDU17C67GuVU8KmAAHSsQKjEGwGmwPtj9Rmcz Processed in progress for 20ms Chunks:(โ))
1 DLiLGBKKNCDsrYK6kMCDeUaPeeKpZT2wHw7TtxdeYaaK Processed in progress for 123ms Chunks:(X))
2022-10-02T03:42:25.427102Z DEBUG stats: EpochId(`11111111111111111111111111111111`) Orphans: 0 With missing chunks: 0 In processing 0
32 5juGQqxLTBB7LGmVM1ZTokPUEZ3MpydNBFmcHn1hPsaS Processed in progress for 1ms Chunks:(โ))
31 3Gfb7Xzvd9t97tnrZNRyC7wfJGos85REUhynQ1FLyy6s Processed in progress for 0ms Chunks:(โ))
30 yT7g6cY6P29qi7yRf4A2Vo3mewa76tkmNZvxFPw56mw Processed in progress for 1ms Chunks:(โ))
29 G1skPfqqVX5CfpnQtkCQL2zmLq1khB1b72UCpQ32fyaE Processed in progress for 1ms Chunks:(โ))
28 AG8rH89tsoyJymN1hivz4R9ZPH7bQ3WBasMvrgmHrbWp Processed in progress for 1ms Chunks:(โ))
27 k6zDwbTabxD4uKKMUFW639s1sLjGUEWY5QkKHZdomFW Processed in progress for 1ms Chunks:(โ))
26 94vecdseScEcQ7WSax7LxXVcvnfjkHDGKYgDvZSFS6Qq Processed in progress for 1ms Chunks:(โ))
25 EEtzpAZmgGXA5JZ6ZReupCWEAukJoWSmgfByAabhjFHk Processed in progress for 2ms Chunks:(โ))
24 BbNf9snRUyGwBeFNnBoJHBmQiMqRxqrDXc8gapWh65vy Processed in progress for 0ms Chunks:(โ))
23 5DBXCq58wFcL1XAnt9fKNt7fZ6tqC74KxEp9dmsCeZ3D Processed in progress for 1ms Chunks:(โ))
22 HyLom11XcHntotebZyw24wVNvp639o7YcN2gJsXncRv6 Processed in progress for 1ms Chunks:(โ))
21 HHDjNYHkBa6Rnemec9H74v4JkQGphRqhiqJp8qo2PHiW Processed in progress for 11ms Chunks:(โ))
20 Bxdk4dKrW51w4dUjZC6AEr6aYvpHxAzCpkUmrd3dhyhD Processed in progress for 0ms Chunks:(โ))
19 3EAVj8eL5g62Ds9g5sJSobH5wMEQDKcyKpq73bPDmTpM Processed in progress for 1ms Chunks:(โ))
18 5rRigaG7SGYJpPTgvwuVTJkQWSfDGXxDom3LkjWBXVTp Processed in progress for 93ms Chunks:(โ))
17 AMh9n8V3bGjLuBat2FzkQWZPhGcHDcPZSEKcorDLhYaX Processed in progress for 0ms Chunks:(โ))
16 AquR2kK8j2PrZy68pLwafPRoHG5DoDCYKqbqXZPUC85i Processed in progress for 0ms Chunks:(โ))
15 7bJvc1NMdUPH8PfQBTmdHXz7nj6tesBHUVeCQJWMma96 Processed in progress for 1ms Chunks:(โ))
14 x9PgUYDZXjCiMGquFbC4AsFCwcGqMNRQztHdJjkcctG Processed in progress for 1ms Chunks:(โ))
13 5djvxjYD1YYSpSKuT5HsYgtTjPTgK39P5nCXCuBmFTK9 Processed in progress for 0ms Chunks:(โ))
12 3WU71KsLjf9CixYiFGXdazbLz5mKzams1Ykd4ZsHxvq3 Processed in progress for 1ms Chunks:(โ))
11 GocWFY5kL4v4X4BoPkArMQKEdHvwyyRdjtDuf7Nn9Udh Processed in progress for 1ms Chunks:(โ))
10 898opjWfcxfphbByYZCs15ug383ArsFX6ZLZGUVSKwtQ Processed in progress for 1ms Chunks:(โ))
9 7RPMov1zS7EN1isXBHiGwUnLHqxjEZhsuspyfYjJhUzz Processed in progress for 0ms Chunks:(โ))
8 AsofRiS4yW3uQY5ijMb72SsiYDVfKn3mmQJZsvqW3quo Processed in progress for 3ms Chunks:(โ))
7 GbNKn2uSqfVUZ5TgxbrswitAAREha6u2xU61CPYVaci Processed in progress for 5ms Chunks:(โ))
6 FL2D5nWLCK9xDZc5AY7qkWV1bVpZdm9gE6VJFeCWfUtK Processed in progress for 0ms Chunks:(โ))
5 A8CzdMScNjKpuMTCoHavu4mt7rFqkcfCVS8EwjTMFk4i Processed in progress for 1ms Chunks:(โ))
4 3TtnEewz1oRKovdHNcjU93Ld1X8FxNRQPd9gU5yQathW Processed in progress for 1ms Chunks:(โ))
3 ezKtwaU2tmLMsTVkYVZuWoMx87yfZjd6TdFP8cN527z Processed in progress for 216ms Chunks:(โ))
2 amxwM5JDU17C67GuVU8KmAAHSsQKjEGwGmwPtj9Rmcz Processed in progress for 20ms Chunks:(โ))
1 DLiLGBKKNCDsrYK6kMCDeUaPeeKpZT2wHw7TtxdeYaaK Processed in progress for 123ms Chunks:(X))
2022-10-02T03:42:35.428868Z DEBUG stats: EpochId(`11111111111111111111111111111111`) Orphans: 0 With missing chunks: 0 In processing 0
48 ENN8fKHeGUwrNdiiPnvah7EBAarLmaty4eoXZ96ooBb1 Processed in progress for 1ms Chunks:(โ))
47 EX9ud6HE1i24GY4hyCrzZiszUXALnXHUZCFoDqveBDkz Processed in progress for 2ms Chunks:(โ))
46 DtgcVo61NQra5UNm7qpAdDWTMD4oo3dRvar2v3CF812b Processed in progress for 1ms Chunks:(โ))
45 8n8naKCZvPP2x5JKDKBaUM6vm1RGDF7wRtA1eEhkmRem Processed in progress for 1ms Chunks:(โ))
44 DdyXa1NYX4nT9mUjZRyCBHJgbysMoQtttUgZw3aN63eq Processed in progress for 1ms Chunks:(โ))
43 Hc1mfKjmjRLAVwBkGtNrEGkpugnG4wfwq1jfR2nBhuBf Processed in progress for 1ms Chunks:(โ))
42 2zBr2TMY7Qoev9uKPye7v4dBzaH4L8iscbTCNFKYMmw6 Processed in progress for 1ms Chunks:(โ))
41 7Edos24Zry4BUMrQ63KYrDBKhTqGToLdvwt8eVSAXc5k Processed in progress for 1ms Chunks:(โ))
40 DzHpJQHKfHgm74C1wVCxGjxE149PfNJGZvPEjPkXXgBR Processed in progress for 2ms Chunks:(โ))
39 2fHQFAZxUJa7HQCTecZJEp5qQ8DZ4NHk76bYKsu9xz63 Processed in progress for 1ms Chunks:(โ))
38 g4Rj23gzp2WetE5AST9Rgf8kAGrEedmyeHZKT44xAfe Processed in progress for 1ms Chunks:(โ))
37 Esq4j5bBcdmWLLXEWwDSMxRErpRTyKJkkbWywYbag7NU Processed in progress for 1ms Chunks:(โ))
36 CTgvEAJBUaknMgZu67gLoHswUhNfntLXGBc4DUe8Qa7Z Processed in progress for 1ms Chunks:(โ))
35 GXnkVoXjGgT5p8wo4vwA2UZFqdfXvRsmVu17g95bakKt Processed in progress for 0ms Chunks:(โ))
34 FM4f4kUM4qj7Xmh4JecVxaXnRimdcnytLnkufVVujEMQ Processed in progress for 1ms Chunks:(โ))
33 Hgu7sbkLh2rLD8xFsQEUoNXurxqB6UYANqB7461mUjR2 Processed in progress for 1ms Chunks:(โ))
32 5juGQqxLTBB7LGmVM1ZTokPUEZ3MpydNBFmcHn1hPsaS Processed in progress for 1ms Chunks:(โ))
31 3Gfb7Xzvd9t97tnrZNRyC7wfJGos85REUhynQ1FLyy6s Processed in progress for 0ms Chunks:(โ))
30 yT7g6cY6P29qi7yRf4A2Vo3mewa76tkmNZvxFPw56mw Processed in progress for 1ms Chunks:(โ))
29 G1skPfqqVX5CfpnQtkCQL2zmLq1khB1b72UCpQ32fyaE Processed in progress for 1ms Chunks:(โ))
28 AG8rH89tsoyJymN1hivz4R9ZPH7bQ3WBasMvrgmHrbWp Processed in progress for 1ms Chunks:(โ))
27 k6zDwbTabxD4uKKMUFW639s1sLjGUEWY5QkKHZdomFW Processed in progress for 1ms Chunks:(โ))
26 94vecdseScEcQ7WSax7LxXVcvnfjkHDGKYgDvZSFS6Qq Processed in progress for 1ms Chunks:(โ))
25 EEtzpAZmgGXA5JZ6ZReupCWEAukJoWSmgfByAabhjFHk Processed in progress for 2ms Chunks:(โ))
24 BbNf9snRUyGwBeFNnBoJHBmQiMqRxqrDXc8gapWh65vy Processed in progress for 0ms Chunks:(โ))
23 5DBXCq58wFcL1XAnt9fKNt7fZ6tqC74KxEp9dmsCeZ3D Processed in progress for 1ms Chunks:(โ))
22 HyLom11XcHntotebZyw24wVNvp639o7YcN2gJsXncRv6 Processed in progress for 1ms Chunks:(โ))
21 HHDjNYHkBa6Rnemec9H74v4JkQGphRqhiqJp8qo2PHiW Processed in progress for 11ms Chunks:(โ))
20 Bxdk4dKrW51w4dUjZC6AEr6aYvpHxAzCpkUmrd3dhyhD Processed in progress for 0ms Chunks:(โ))
19 3EAVj8eL5g62Ds9g5sJSobH5wMEQDKcyKpq73bPDmTpM Processed in progress for 1ms Chunks:(โ))
18 5rRigaG7SGYJpPTgvwuVTJkQWSfDGXxDom3LkjWBXVTp Processed in progress for 93ms Chunks:(โ))
17 AMh9n8V3bGjLuBat2FzkQWZPhGcHDcPZSEKcorDLhYaX Processed in progress for 0ms Chunks:(โ))
16 AquR2kK8j2PrZy68pLwafPRoHG5DoDCYKqbqXZPUC85i Processed in progress for 0ms Chunks:(โ))
15 7bJvc1NMdUPH8PfQBTmdHXz7nj6tesBHUVeCQJWMma96 Processed in progress for 1ms Chunks:(โ))
14 x9PgUYDZXjCiMGquFbC4AsFCwcGqMNRQztHdJjkcctG Processed in progress for 1ms Chunks:(โ))
13 5djvxjYD1YYSpSKuT5HsYgtTjPTgK39P5nCXCuBmFTK9 Processed in progress for 0ms Chunks:(โ))
12 3WU71KsLjf9CixYiFGXdazbLz5mKzams1Ykd4ZsHxvq3 Processed in progress for 1ms Chunks:(โ))
11 GocWFY5kL4v4X4BoPkArMQKEdHvwyyRdjtDuf7Nn9Udh Processed in progress for 1ms Chunks:(โ))
10 898opjWfcxfphbByYZCs15ug383ArsFX6ZLZGUVSKwtQ Processed in progress for 1ms Chunks:(โ))
9 7RPMov1zS7EN1isXBHiGwUnLHqxjEZhsuspyfYjJhUzz Processed in progress for 0ms Chunks:(โ))
8 AsofRiS4yW3uQY5ijMb72SsiYDVfKn3mmQJZsvqW3quo Processed in progress for 3ms Chunks:(โ))
7 GbNKn2uSqfVUZ5TgxbrswitAAREha6u2xU61CPYVaci Processed in progress for 5ms Chunks:(โ))
6 FL2D5nWLCK9xDZc5AY7qkWV1bVpZdm9gE6VJFeCWfUtK Processed in progress for 0ms Chunks:(โ))
5 A8CzdMScNjKpuMTCoHavu4mt7rFqkcfCVS8EwjTMFk4i Processed in progress for 1ms Chunks:(โ))
4 3TtnEewz1oRKovdHNcjU93Ld1X8FxNRQPd9gU5yQathW Processed in progress for 1ms Chunks:(โ))
3 ezKtwaU2tmLMsTVkYVZuWoMx87yfZjd6TdFP8cN527z Processed in progress for 216ms Chunks:(โ))
2 amxwM5JDU17C67GuVU8KmAAHSsQKjEGwGmwPtj9Rmcz Processed in progress for 20ms Chunks:(โ))
1 DLiLGBKKNCDsrYK6kMCDeUaPeeKpZT2wHw7TtxdeYaaK Processed in progress for 123ms Chunks:(X))
Passed โ
test_transfer_ft_to_user_inspected_bike
2022-10-02T03:42:45.429826Z DEBUG stats: EpochId(`11111111111111111111111111111111`) Orphans: 0 With missing chunks: 0 In processing 0
65 8EvoAeCrdXGVPLjaWKAJbkbWaKHfrWTbsrcf96ThmjaL Processed in progress for 1ms Chunks:(โ))
64 3XT5PHQfWCzrz8dimry1EyXCEaR3XCmqZsXgTpUDP3UQ Processed in progress for 0ms Chunks:(โ))
63 CkQQfCNav3gd29uy5v7DrHVcXt9ZCWjYiK9R4FW8fVXy Processed in progress for 0ms Chunks:(โ))
62 9C21sdAU2wdsnG431LmjBuKMvWBhtmQBbDkGsAnBhitJ Processed in progress for 1ms Chunks:(โ))
61 31fmvseLVDVjVGvAykRHUu2qyKfid8ESdFguHArTxWz7 Processed in progress for 0ms Chunks:(โ))
60 6Wr8CMEJTvAGHCDTZQmftnkL3fHrzJnGuNQHTkEj7zDE Processed in progress for 1ms Chunks:(โ))
59 28unnkSU2Z5m1LDebTXgRDsccE65SzvTbbjvtZxwoeUY Processed in progress for 1ms Chunks:(โ))
58 7sTbpzdjoELUTpxqKUw6BXHf6TY4ArUsPaB4cEW6zMFV Processed in progress for 2ms Chunks:(โ))
57 CY7UCRtbmruuQSocibMJJS8Y6tHdj2R5hdbX4X89bXrp Processed in progress for 1ms Chunks:(โ))
56 G2UmBvAMTwpGxLXqAip2RraxKBkv1Hh1uaUyR4dy5TLh Processed in progress for 1ms Chunks:(โ))
55 8BN7oJMUzqW3vFyzTok1Uona83Eix7MqAxGNvr9VzbSi Processed in progress for 1ms Chunks:(โ))
54 AGgPXJV2qpKELBTGcGqZsDKfrMiV3NbiiDR5QzwFk8Ag Processed in progress for 0ms Chunks:(โ))
53 G4x424in1Frov1aUiQn9vzLrmw56sNTzZ52qwefxyTrf Processed in progress for 0ms Chunks:(โ))
52 EAzANTvJEYSm55ybdfpXga7h2WVsxMVonfYykj9W5vTt Processed in progress for 1ms Chunks:(โ))
51 22PYbwgx1HNqqbChr2jJdUmr1etWA7soxbQbSGy3yJnv Processed in progress for 1ms Chunks:(โ))
50 4JMomcvQmTmnvY6GZCXXQbcY1Qz4Qco8bjD9JAUBKUYG Processed in progress for 1ms Chunks:(โ))
49 BFWZSLkDmEv6LjvEakBj5EY4mudNzoykxBGEyDiQJNW1 Processed in progress for 2ms Chunks:(โ))
48 ENN8fKHeGUwrNdiiPnvah7EBAarLmaty4eoXZ96ooBb1 Processed in progress for 1ms Chunks:(โ))
47 EX9ud6HE1i24GY4hyCrzZiszUXALnXHUZCFoDqveBDkz Processed in progress for 2ms Chunks:(โ))
46 DtgcVo61NQra5UNm7qpAdDWTMD4oo3dRvar2v3CF812b Processed in progress for 1ms Chunks:(โ))
45 8n8naKCZvPP2x5JKDKBaUM6vm1RGDF7wRtA1eEhkmRem Processed in progress for 1ms Chunks:(โ))
44 DdyXa1NYX4nT9mUjZRyCBHJgbysMoQtttUgZw3aN63eq Processed in progress for 1ms Chunks:(โ))
43 Hc1mfKjmjRLAVwBkGtNrEGkpugnG4wfwq1jfR2nBhuBf Processed in progress for 1ms Chunks:(โ))
42 2zBr2TMY7Qoev9uKPye7v4dBzaH4L8iscbTCNFKYMmw6 Processed in progress for 1ms Chunks:(โ))
41 7Edos24Zry4BUMrQ63KYrDBKhTqGToLdvwt8eVSAXc5k Processed in progress for 1ms Chunks:(โ))
40 DzHpJQHKfHgm74C1wVCxGjxE149PfNJGZvPEjPkXXgBR Processed in progress for 2ms Chunks:(โ))
39 2fHQFAZxUJa7HQCTecZJEp5qQ8DZ4NHk76bYKsu9xz63 Processed in progress for 1ms Chunks:(โ))
38 g4Rj23gzp2WetE5AST9Rgf8kAGrEedmyeHZKT44xAfe Processed in progress for 1ms Chunks:(โ))
37 Esq4j5bBcdmWLLXEWwDSMxRErpRTyKJkkbWywYbag7NU Processed in progress for 1ms Chunks:(โ))
36 CTgvEAJBUaknMgZu67gLoHswUhNfntLXGBc4DUe8Qa7Z Processed in progress for 1ms Chunks:(โ))
35 GXnkVoXjGgT5p8wo4vwA2UZFqdfXvRsmVu17g95bakKt Processed in progress for 0ms Chunks:(โ))
34 FM4f4kUM4qj7Xmh4JecVxaXnRimdcnytLnkufVVujEMQ Processed in progress for 1ms Chunks:(โ))
33 Hgu7sbkLh2rLD8xFsQEUoNXurxqB6UYANqB7461mUjR2 Processed in progress for 1ms Chunks:(โ))
32 5juGQqxLTBB7LGmVM1ZTokPUEZ3MpydNBFmcHn1hPsaS Processed in progress for 1ms Chunks:(โ))
31 3Gfb7Xzvd9t97tnrZNRyC7wfJGos85REUhynQ1FLyy6s Processed in progress for 0ms Chunks:(โ))
30 yT7g6cY6P29qi7yRf4A2Vo3mewa76tkmNZvxFPw56mw Processed in progress for 1ms Chunks:(โ))
29 G1skPfqqVX5CfpnQtkCQL2zmLq1khB1b72UCpQ32fyaE Processed in progress for 1ms Chunks:(โ))
28 AG8rH89tsoyJymN1hivz4R9ZPH7bQ3WBasMvrgmHrbWp Processed in progress for 1ms Chunks:(โ))
27 k6zDwbTabxD4uKKMUFW639s1sLjGUEWY5QkKHZdomFW Processed in progress for 1ms Chunks:(โ))
26 94vecdseScEcQ7WSax7LxXVcvnfjkHDGKYgDvZSFS6Qq Processed in progress for 1ms Chunks:(โ))
25 EEtzpAZmgGXA5JZ6ZReupCWEAukJoWSmgfByAabhjFHk Processed in progress for 2ms Chunks:(โ))
24 BbNf9snRUyGwBeFNnBoJHBmQiMqRxqrDXc8gapWh65vy Processed in progress for 0ms Chunks:(โ))
23 5DBXCq58wFcL1XAnt9fKNt7fZ6tqC74KxEp9dmsCeZ3D Processed in progress for 1ms Chunks:(โ))
22 HyLom11XcHntotebZyw24wVNvp639o7YcN2gJsXncRv6 Processed in progress for 1ms Chunks:(โ))
21 HHDjNYHkBa6Rnemec9H74v4JkQGphRqhiqJp8qo2PHiW Processed in progress for 11ms Chunks:(โ))
20 Bxdk4dKrW51w4dUjZC6AEr6aYvpHxAzCpkUmrd3dhyhD Processed in progress for 0ms Chunks:(โ))
19 3EAVj8eL5g62Ds9g5sJSobH5wMEQDKcyKpq73bPDmTpM Processed in progress for 1ms Chunks:(โ))
18 5rRigaG7SGYJpPTgvwuVTJkQWSfDGXxDom3LkjWBXVTp Processed in progress for 93ms Chunks:(โ))
17 AMh9n8V3bGjLuBat2FzkQWZPhGcHDcPZSEKcorDLhYaX Processed in progress for 0ms Chunks:(โ))
16 AquR2kK8j2PrZy68pLwafPRoHG5DoDCYKqbqXZPUC85i Processed in progress for 0ms Chunks:(โ))
15 7bJvc1NMdUPH8PfQBTmdHXz7nj6tesBHUVeCQJWMma96 Processed in progress for 1ms Chunks:(โ))
2022-10-02T03:42:55.430917Z DEBUG stats: EpochId(`11111111111111111111111111111111`) Orphans: 0 With missing chunks: 0 In processing 0
81 BgP1HA6cAyTf6iMmHh6gCfYRheJQn7i2upv5ztKrDJXz Processed in progress for 0ms Chunks:(โ))
80 GvkbDxpx3oGTbnpdYfpAhrLj9rxgrAEsZ64acy1b6EAw Processed in progress for 1ms Chunks:(โ))
79 95sb9yjxzschXd6vfALgwrsizu8k9XhqMuzQ7okq6SkN Processed in progress for 2ms Chunks:(โ))
78 HDuUBrwPZfRMSNh117y7nqsGMoSG8mScqdMDeTuNEk1D Processed in progress for 1ms Chunks:(โ))
77 3THR5aNXbXsgD9VDJYD5mogSWWc3xU7QfBrAWV3p8Gd5 Processed in progress for 0ms Chunks:(โ))
76 CsH3cyepJZq4sBQ4QbqLbySYZbEU6moZMz4qUz9UrtwV Processed in progress for 1ms Chunks:(โ))
75 H7EChPZU3noRCc1nMAz33eCwZQpMMb4s7Sbhx3Mah61f Processed in progress for 2ms Chunks:(โ))
74 A479dVpCriH9tW3hEcMfKdNUk79vmcUT5J3c7tdRLB5q Processed in progress for 0ms Chunks:(โ))
73 HvrXABRvx37Fi1B38xJ6kLze1DH883uoKn4TJmetQ942 Processed in progress for 1ms Chunks:(โ))
72 8eNEEVTbAUpri1KDCXVYCb2yxyN3cVkA7bnPwm6KCmMD Processed in progress for 1ms Chunks:(โ))
71 EUgrb5nyXwqcNrbNiXhN5yNAPAdUGk5kaixFAPjPpKVN Processed in progress for 4ms Chunks:(โ))
70 2k7iEoKaRjqd6M8pDKLPAmPvpzWSbdta652orRMcR5DZ Processed in progress for 2ms Chunks:(โ))
69 C9nDm4osBo31diTrpdfGgWGUZ2FBAAdrMEbDcn7nU62P Processed in progress for 2ms Chunks:(โ))
68 J1j59dsK6i2qfxWjLsepy6Y1LEytKMu6SxtHkVAEAhds Processed in progress for 0ms Chunks:(โ))
67 AYf9YiEc3zfs4bsFzF2QXqSj2RwHisqQmvsYjyP86Hs2 Processed in progress for 1ms Chunks:(โ))
66 8yFxHWMyA7uPoMMmimtnoKEbqiDFdgkXV4Uund7ZwKTX Processed in progress for 1ms Chunks:(โ))
65 8EvoAeCrdXGVPLjaWKAJbkbWaKHfrWTbsrcf96ThmjaL Processed in progress for 1ms Chunks:(โ))
64 3XT5PHQfWCzrz8dimry1EyXCEaR3XCmqZsXgTpUDP3UQ Processed in progress for 0ms Chunks:(โ))
63 CkQQfCNav3gd29uy5v7DrHVcXt9ZCWjYiK9R4FW8fVXy Processed in progress for 0ms Chunks:(โ))
62 9C21sdAU2wdsnG431LmjBuKMvWBhtmQBbDkGsAnBhitJ Processed in progress for 1ms Chunks:(โ))
61 31fmvseLVDVjVGvAykRHUu2qyKfid8ESdFguHArTxWz7 Processed in progress for 0ms Chunks:(โ))
60 6Wr8CMEJTvAGHCDTZQmftnkL3fHrzJnGuNQHTkEj7zDE Processed in progress for 1ms Chunks:(โ))
59 28unnkSU2Z5m1LDebTXgRDsccE65SzvTbbjvtZxwoeUY Processed in progress for 1ms Chunks:(โ))
58 7sTbpzdjoELUTpxqKUw6BXHf6TY4ArUsPaB4cEW6zMFV Processed in progress for 2ms Chunks:(โ))
57 CY7UCRtbmruuQSocibMJJS8Y6tHdj2R5hdbX4X89bXrp Processed in progress for 1ms Chunks:(โ))
56 G2UmBvAMTwpGxLXqAip2RraxKBkv1Hh1uaUyR4dy5TLh Processed in progress for 1ms Chunks:(โ))
55 8BN7oJMUzqW3vFyzTok1Uona83Eix7MqAxGNvr9VzbSi Processed in progress for 1ms Chunks:(โ))
54 AGgPXJV2qpKELBTGcGqZsDKfrMiV3NbiiDR5QzwFk8Ag Processed in progress for 0ms Chunks:(โ))
53 G4x424in1Frov1aUiQn9vzLrmw56sNTzZ52qwefxyTrf Processed in progress for 0ms Chunks:(โ))
52 EAzANTvJEYSm55ybdfpXga7h2WVsxMVonfYykj9W5vTt Processed in progress for 1ms Chunks:(โ))
51 22PYbwgx1HNqqbChr2jJdUmr1etWA7soxbQbSGy3yJnv Processed in progress for 1ms Chunks:(โ))
50 4JMomcvQmTmnvY6GZCXXQbcY1Qz4Qco8bjD9JAUBKUYG Processed in progress for 1ms Chunks:(โ))
49 BFWZSLkDmEv6LjvEakBj5EY4mudNzoykxBGEyDiQJNW1 Processed in progress for 2ms Chunks:(โ))
48 ENN8fKHeGUwrNdiiPnvah7EBAarLmaty4eoXZ96ooBb1 Processed in progress for 1ms Chunks:(โ))
47 EX9ud6HE1i24GY4hyCrzZiszUXALnXHUZCFoDqveBDkz Processed in progress for 2ms Chunks:(โ))
46 DtgcVo61NQra5UNm7qpAdDWTMD4oo3dRvar2v3CF812b Processed in progress for 1ms Chunks:(โ))
45 8n8naKCZvPP2x5JKDKBaUM6vm1RGDF7wRtA1eEhkmRem Processed in progress for 1ms Chunks:(โ))
44 DdyXa1NYX4nT9mUjZRyCBHJgbysMoQtttUgZw3aN63eq Processed in progress for 1ms Chunks:(โ))
43 Hc1mfKjmjRLAVwBkGtNrEGkpugnG4wfwq1jfR2nBhuBf Processed in progress for 1ms Chunks:(โ))
42 2zBr2TMY7Qoev9uKPye7v4dBzaH4L8iscbTCNFKYMmw6 Processed in progress for 1ms Chunks:(โ))
41 7Edos24Zry4BUMrQ63KYrDBKhTqGToLdvwt8eVSAXc5k Processed in progress for 1ms Chunks:(โ))
40 DzHpJQHKfHgm74C1wVCxGjxE149PfNJGZvPEjPkXXgBR Processed in progress for 2ms Chunks:(โ))
39 2fHQFAZxUJa7HQCTecZJEp5qQ8DZ4NHk76bYKsu9xz63 Processed in progress for 1ms Chunks:(โ))
38 g4Rj23gzp2WetE5AST9Rgf8kAGrEedmyeHZKT44xAfe Processed in progress for 1ms Chunks:(โ))
37 Esq4j5bBcdmWLLXEWwDSMxRErpRTyKJkkbWywYbag7NU Processed in progress for 1ms Chunks:(โ))
36 CTgvEAJBUaknMgZu67gLoHswUhNfntLXGBc4DUe8Qa7Z Processed in progress for 1ms Chunks:(โ))
35 GXnkVoXjGgT5p8wo4vwA2UZFqdfXvRsmVu17g95bakKt Processed in progress for 0ms Chunks:(โ))
34 FM4f4kUM4qj7Xmh4JecVxaXnRimdcnytLnkufVVujEMQ Processed in progress for 1ms Chunks:(โ))
33 Hgu7sbkLh2rLD8xFsQEUoNXurxqB6UYANqB7461mUjR2 Processed in progress for 1ms Chunks:(โ))
32 5juGQqxLTBB7LGmVM1ZTokPUEZ3MpydNBFmcHn1hPsaS Processed in progress for 1ms Chunks:(โ))
31 3Gfb7Xzvd9t97tnrZNRyC7wfJGos85REUhynQ1FLyy6s Processed in progress for 0ms Chunks:(โ))
Passed โ
test_transfer_call_to_use_bike
โจ Done in 61.40s.
```
#### account_id ใฎในใใฌใผใธใฎไฝฟ็จ็ถๆณใ่กจใใใผใฟๆง้ ใๅๅพใใใณใใณใ
`near view sub.dev-1660204085773-49134722844982 storage_balance_of '{"account_id": "'mashharuki.testnet'"}'`
```zsh
View call: sub.dev-1660204085773-49134722844982.storage_balance_of({"account_id": "mashharuki.testnet"})
{ total: '1250000000000000000000', available: '0' }
```
#### ใใผใฏใณใ็บ่กใใ
```zsh
near call sub23.mashharuki2.testnet new '{"owner_id": "'mashharuki2.testnet'", "total_supply": "1000000000000000", "metadata": { "spec": "ft-1.0.0", "name": "My First Token", "symbol": "MYFT", "decimals": 8 }}' --accountId mashharuki2.testnet
```
### ใใผใฏใณใฎใใๅใใ่กใใใใซๅใๅใๅดใฎใขใใฌในใ FT ใณใณใใฉใฏใใซ็ป้ฒใใ
```zsh
near call sub23.mashharuki2.testnet storage_deposit '' --accountId dev-1666503589999-87468235150551 --amount 0.00125
```
```zsh
near call sub23.mashharuki2.testnet ft_transfer '{"receiver_id": "dev-1666503589999-87468235150551", "amount": "19"}' --accountId mashharuki2.testnet --amount 0.000000000000000000000001
```
```zsh
near view sub23.mashharuki2.testnet ft_balance_of '{"account_id": "dev-1666503589999-87468235150551"}'
```
### ๅ่ๆ็ฎ
1. [Near Workspaces](https://github.com/near/workspaces-rs)
2. [Gitpod](https://gitpod.io/workspaces)
3. [Near Docs](https://docs.near.org/api/rpc/contracts)
4. [NEP-141 Fungible Token](https://nomicon.io/Standards/Tokens/FungibleToken/Core#reference-level-explanation)
5. [Storage Management](https://nomicon.io/Standards/StorageManagement)
near-blank-project
==================
This [React] app was initialized with [create-near-app]
Quick Start
===========
To run this project locally:
1. Prerequisites: Make sure you've installed [Node.js] โฅ 12
2. Install dependencies: `yarn install`
3. Run the local development server: `yarn dev` (see `package.json` for a
full list of `scripts` you can run with `yarn`)
Now you'll have a local development environment backed by the NEAR TestNet!
Go ahead and play with the app and the code. As you make code changes, the app will automatically reload.
Exploring The Code
==================
1. The "backend" code lives in the `/contract` folder. See the README there for
more info.
2. The frontend code lives in the `/frontend` folder. `/frontend/index.html` is a great
place to start exploring. Note that it loads in `/frontend/assets/js/index.js`, where you
can learn how the frontend connects to the NEAR blockchain.
3. Tests: there are different kinds of tests for the frontend and the smart
contract. See `contract/README` for info about how it's tested. The frontend
code gets tested with [jest]. You can run both of these at once with `yarn
run test`.
Deploy
======
Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `yarn dev`, your smart contract gets deployed to the live NEAR TestNet with a throwaway account. When you're ready to make it permanent, here's how.
Step 0: Install near-cli (optional)
-------------------------------------
[near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `yarn install`, but for best ergonomics you may want to install it globally:
yarn install --global near-cli
Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx`
Ensure that it's installed with `near --version` (or `npx near --version`)
Step 1: Create an account for the contract
------------------------------------------
Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `near-blank-project.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `near-blank-project.your-name.testnet`:
1. Authorize NEAR CLI, following the commands it gives you:
near login
2. Create a subaccount (replace `YOUR-NAME` below with your actual account name):
near create-account near-blank-project.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet
Step 2: set contract name in code
---------------------------------
Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above.
const CONTRACT_NAME = process.env.CONTRACT_NAME || 'near-blank-project.YOUR-NAME.testnet'
Step 3: deploy!
---------------
One command:
yarn deploy
As you can see in `package.json`, this does two things:
1. builds & deploys smart contract to NEAR TestNet
2. builds & deploys frontend code to GitHub using [gh-pages]. This will only work if the project already has a repository set up on GitHub. Feel free to modify the `deploy` script in `package.json` to deploy elsewhere.
Troubleshooting
===============
On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details.
[React]: https://reactjs.org/
[create-near-app]: https://github.com/near/create-near-app
[Node.js]: https://nodejs.org/en/download/package-manager/
[jest]: https://jestjs.io/
[NEAR accounts]: https://docs.near.org/docs/concepts/account
[NEAR Wallet]: https://wallet.testnet.near.org/
[near-cli]: https://github.com/near/near-cli
[gh-pages]: https://github.com/tschaub/gh-pages
|
mdb1710_nearcertvoting | README.md
contract-advanced.html
contract.html
index.html
lib
near-api-js.js
login-advanced.html
login.html
| # `near-api-js` Starter Kit
This is a simple project to help you get started with frontend development on NEAR Protocol
## Files
```txt
โโโ index.html # default page, nothing here
โโโ login.html # code to login to NEAR Wallet
โโโ contract.html # code to call view and change methods (basic)
โโโ contract-advanced.html # code to call view and change methods (advanced)
```
|
Marinamontelo_nft-test | .cache
00
03938615e259d763415ee653967800.json
acebd9d71312be2f520e638adc6863.json
c48660d31dfa4c2c9f26f1b1bcca7c.json
03
99c1c2e1e0cb0babe2c0b3b003c051.json
04
b8c7fd7c26aa9e361d400d002bf10c.json
db2a52c716804680681a4fa6b03e8a.json
05
a4de5848367d070e2f3572400fca06.json
07
2de3bd8e4dadd59cea8e1075d204b3.json
98f497441c8ab94348b71618b02f04.json
9a9c701219c8fc41ac31a488ab1bb7.json
c0b901491f91026de58d005a858cba.json
08
46e94042e00e87ba5326c6efc1bfdf.json
eeb4111275e5c9f91d41e3bd1bfa07.json
09
72862d57b842e012f0ef88cce8658b.json
7e3bd839cf3143bbee80b3d0fce433.json
8acd3c627c0b90322952351723aa3c.json
8f4ee2314d2acf016d9c1a6c27a630.json
0a
a7e482139657b462349c2a43238f04.json
0b
ff89aef475857b7e83468743d0c324.json
0c
5f8159ba3f64b89b4a1408443117dd.json
a077005991b946c412add78b24c5d5.json
0d
33e7f94032f255b34ec43c66f83797.json
6ee6e7b89dde13373b66bf6f662082.json
be1b49a68146f66c101bedd77f06af.json
0e
f24dbbef6e6d004e7a6f8d98138e08.json
0f
2609f9af0c11d4f83c4bbf0dedff0c.json
b9f5e91200694f6d46981b4431dd31.json
10
26889056478b1ca9b854f8ac701e46.json
11
3ad6b7591c9f1b3729f91efe2a7306.json
12
840e403ca9efc1077c1cea41070932.json
13
609dbc1f821d7586b9e99bd20bca5b.json
e51382f576537f3ab7f0636446922a.json
14
67c719dd5fcfbfaade12f5088d3f2b.json
15
b1d54ee5273d967b5ca5781301b5a9.json
16
673181489fb68d17c75a3d8bf9c95e.json
17
09799345ede13cef20531b81cb0593.json
f2e4a37dc42c681723ee13f6fbfaa8.json
19
6696aed41558928c8a13064b38cde3.json
1a
5459a1e214f03e59b3e8a52de100db.json
911be3687e53a7d24884cb6a8e9744.json
1b
a422730fef1be904a8e67e237d40b5.json
d31fea2950e5110ae7a8fdb9bdb6fd.json
1e
733f4c9807c3624f4007b483650927.json
dd6cf53cc62a7fe744ee1feefdc2be.json
1f
1f51e7707a7982745986b501f893b6.json
fec9c62c17144b71c56a21090530ad.json
20
8cae1c71bcbe15ed3d3a0e770ca8f5.json
96b8922b27ffc993fdce7e7e8c6d8d.json
a56220d014cda8995490ffc2e4f787.json
21
4ee8f98453e9984425a6a4f648f174.json
5337bfb107eafbf1083b334d18fba0.json
6d865e0dce05a79ca8920de7ff2fec.json
dfdfc7c3f3878237fc73fd45eff6fa.json
22
a8a841b39276d7e7837717f7c75106.json
d9f6f510b163e5e0a84a742b5363fa.json
e4b0bc8f13aa9e5d8b6ad526914dc3.json
ecae17cf5d4cd566690e86df93bfe3.json
23
4549ebb9332e67110b50eeb3343916.json
849a73055172d37367b7002b8ef3bb.json
24
4aa78b02600706e717dbcc5a41f091.json
70e7bf2049be8efb4d905886a4101e.json
9577b685e8fa5c435ca00dfa01cc9b.json
e69f802625c4591c4c8847a7bc1929.json
25
383106e8f398f7d144fc606141f157.json
7f4f827cd4009e15d5fab82be15f35.json
a1c6887b6fe45857d8bb7318f16e91.json
26
fcf2e53d63befe65419dd7c698b382.json
27
5c426bba3423b2bc8abd754360e5ba.json
8283b0af86e3866b8b6ccc28806069.json
28
3eec5d01c75757f27ddc01fe41e53f.json
c5df5f606862e07d8ae2297c19e409.json
29
4e8af716453c2eee2d273357abbda6.json
2a
c7f1c10d533c35ea0679c15ae2c21e.json
2b
0dd8ccdafd479aa4a40820634c108c.json
7d1198ae0600203932d4f8cd87cc28.json
2c
8046ba220562638da44e5cec9d2562.json
2d
12e170d61535a490c9ef004fe77c65.json
81c4328d80bdaf97b6db60d07eb62d.json
e491b54e0978567d29bf18a7dfaeb9.json
2e
58849b83390d15a67497bbb1fe135f.json
2f
3debd2c6fb91642be518e3d891dbeb.json
f65fa27fead8a929807590a30833db.json
30
1c972985020a3786639c6cafc6bb7d.json
31
60325d0f4b1809d2dc2f68dc9a41c5.json
791dcd185160a4064bcb5ba1d1658e.json
32
d72be0a2c804fbde9fc4533282eb25.json
33
2dde07b78a629a5686d6ce968c802a.json
e9aad4cdf169f53013868b0e3f89dd.json
eb2a07ac83ced46b89215fc9bb1d91.json
34
c62e055192b5f148651abc5862bd3f.json
35
94b5f8ac7ebc1be9444dcd44647e04.json
36
41854ab97debfa1fb245c62f3361f7.json
7052e532d9bf95a5da89870f2bfb81.json
37
7e1453b59d3110475a9a515d08741d.json
9f2c5028ba8734097d02a7974859d5.json
38
3f2481253104ca490ecac9c5f77e9a.json
8768831cbad913df32a1a89a8df59f.json
39
b30b7b16f64a791ca4d63792be4bae.json
3a
9c70cbad0c31e4753d076be05366ee.json
f81c023ed1fc1e734f0ebe9fb9c7b3.json
3d
6ee2f890fa5fac1e9c5c943a989d93.json
7da139d0921deeb19d0ffee00f5450.json
cc69b327d517d883207d56a2d6618d.json
e5fda0ed6c61532fad829a7b0ec3c2.json
3e
c75a9f615ec7bd74a0051147a707d5.json
3f
22d6099cad698285fd5261b83dbcab.json
3f1b05c75d989d8ba452e96f5aa8fa.json
40
a95783be82c7e646b8a0b9df2960e3.json
41
f20005e41bcf64441a74f81bf16499.json
42
06d820cb2f18a6b70a598c784a788e.json
33f4809f4342dd7154962e3a020955.json
8cf22b5b1e18f05416c547e1ea7774.json
44
0f06ca0f5b7a3f00d13134abdf4617.json
2976c90b5597b1e6a42c2933c57b59.json
45
0ef7a1d7454cbf7cfc9cc18b4519e6.json
46
0f5f2c83eb26189766163e16f2026b.json
deafa77dad0facbd1925b8032a0caa.json
47
0a3839e65fae5e1de1b006ab4ae4d0.json
48
631ca980cedf9bc1d18eb01cd1e574.json
49
3cf3dfb244a264de172fd45bdd704d.json
890839d76c4d174cc891882b7edaa1.json
c3161df4e126aca569c8886973e0ff.json
fd5b912ecd5ce62a98fc066f598535.json
4b
4daf980cf50f1ebfe86991fa4f8694.json
4d
b4edea39fc95747855c4bf1374136b.json
4e
43af8c31b6a682297f6ce21a0423f1.json
4f
63791f8f15b60124c54fd29ee0ca7c.json
6d66f0183bb4cc1d2e32c0fe2876e2.json
50
1e1aa4d466ebc9c0bc78fed505abdb.json
3ee4519f80ca7fce7f43dff8d534e7.json
51
b8ec2ed9c2399a7ca57ab1b725b019.json
52
bc9d0676b0ec93bbbab797bec332cc.json
d440173e96c954e8c2a825231167e1.json
53
fd02de02bb3fabb77f9c19eed289f8.json
56
7aee85411489f3d9c1b2f8ab14f8bd.json
ba15d972b1c2e913c159d3d91e7610.json
dfb7237e4afd2a84526d20dedbd123.json
57
06de404229972e3808672d6e169e0c.json
9453ebdf9fa9ca6c7776179a619642.json
58
3ada95ee34a7fba1e99922aa8782b9.json
86b7cbdb44952172860fd91df426ac.json
b2452b2839206caf356a6943861b8f.json
59
40f90daa24e5b613ea8e57ef21e13e.json
5b
32e9dcc3adb4d5b1efa0a1b8db98f6.json
af9c3bf1ad6067ad058c1b34765263.json
5c
01d454fbe22418711bea32b59e4e6c.json
4b2880f95f10baff719dd779874ec8.json
86027d602785e2fc1f3308f00d79e3.json
5d
05ffc7598595ba4ef219ac72287d76.json
246aa3c1ac79a3f94e0d04bc976ca3.json
5e
2de0bbebe6225a0057e52d1b348536.json
c630b87d4b27898193f0a3d08c5b6d.json
e43616745f0e9f4e763d355c902bfb.json
5f
124b0698334287a1c4da385ef91e91.json
4bc7c0eaef8e9275cd1ec8984aefe8.json
5e484981b3ee81963f7701cc80b78b.json
99bf6f1aab7ee497c59a69d9d5c815.json
60
9098a6b35f004fbf17d7a1d465773e.json
61
4246022a2033ff6e5db13c6f954ec3.json
69c6ef4ee434b5a98b9738417d073c.json
a6fcf6396abbfe86b4b01a8501d49a.json
f40c23b1c43cb3828a799f03eca6a6.json
63
1aad0376429157148b57116f4614d6.json
480301ead3b3e6b851d2f96531e5fa.json
64
118e339253f26a1c4220dd4c497f15.json
2068bacf9a10700605fc6205db0ce2.json
66
59c70aa8fef97ba4b817b37bd48072.json
f57abf1a1e1fd0772fc0c2e01f6336.json
67
328428c2b86a9851369ee63e60baf3.json
36b0d2d7e1deab1f0749df63452b1f.json
68
24c5fc71d5295dd580aface10d7f0a.json
3305052b5b32dbd91c7aa77293b827.json
5a79340de8db62056d9ab83b099691.json
eb65c2debce60328f5d67d753d8efd.json
69
34004fa50b2b7d7b9de65b9f1102c1.json
a40d32064477d6fbea53b5777f97d7.json
6a
0ff9f71eac80df9665e5392ed197e6.json
1b7b5a7f09ae4babfdf25987c59b27.json
c24ab8ad67f3169d84c18c43c88a69.json
d38b402397c35b5f0970f57e78efc2.json
6b
d95e5eafd9dbb3afd9b2a78753cae1.json
6c
96545ad9df7ef9c1e41f2a7880abd3.json
a5569a8d32046496b518c93fb8d18c.json
6d
0629c29f75ebccd0d9040436de82b5.json
5a5bb76411d34bde355039ac46311a.json
6f
18b3de91b24ed5f9bee29a0f59dfe4.json
be0e3749e606190a01330b40320bb4.json
71
61e5b14c5e6f0ab3c9a446797896ef.json
72
480cb573af76931e44fe9a3502be72.json
74
6cda84b69785c588dac8a15f871520.json
7d27cc6e84aa77254a145859d91a69.json
90caf800c93d39d22d19a6bc8a8ee9.json
75
646e78abdd4b18d8fc807f59d4bbfc.json
f826f114fd68c94975231721a2e52b.json
76
4013683652c0a40dd51a6139bd21ed.json
78
f906a00caeb836494270fb15b23a30.json
79
76cad38a848c844ae53396bfcc40a9.json
a5beafed236aec872e4f9607ae7ca8.json
7a
135b09978fde5f80c3bf5f7b3c62f4.json
3098cd3e19e3daa4f68f9aa3b32ec1.json
d6547d4a8d47d638eb3046e116ad27.json
7b
a9f4aaeb74fb341e7806960a483eb6.json
7c
367713b206ab527a5325308f6aa4a2.json
4d646c4af9956dc227921ddbd2b70e.json
7d
462945752ddc8f7fbc824ed3a4dbdd.json
86ebe8e8df8860ed677eb470dc579e.json
7e
a104b2fa3727dd84cb9ce895313d7a.json
7f
c280d21dc9d4da91a16a41543dce7d.json
80
60e0fc9360ee756337d651cc2e4268.json
c38bfeaa45740f7cac050c55e15c3c.json
81
78eef285e9aa7cbb0b1e95edaa1650.json
82
3c1ae94c21dfbe2a04f9c933ba45be.json
83
05bc83b4cad62dbf25985bc03b7586.json
83fe2d9c628caa2579f81cce79585e.json
a44e915532511e8a4764f580943aa5.json
84
852cdce8a64e2b9330879e3e250731.json
85
a568fd39de79594161e01eda0180ec.json
ed62a21b5815743c8c746400f9e778.json
86
b70e43565ae89cfaa74c25f8048f18.json
c6e79c824b956f41e15e20cd8a1c32.json
87
1dce2b0dc72e05bc328dceb7c2f5e0.json
88
99538341612710ee2fcd323e150206.json
f8093e22e7979752a4add65b955152.json
89
88a225065a338721a931167d9ce8cd.json
ce66b735e184fdfcf5912b2ffb62a6.json
8a
9ddd807f01225d79ef560e9abcc8f5.json
8c
1aaea801947aa088d0f29652ff69cd.json
2358817029f787bb0e191d13729462.json
ee558f04b3327cc82257490953fcb2.json
8e
74d7e8710bf62474c37928a077df76.json
e59fea296ca30a807b03d06020d3bd.json
91
ade2d43f9dee9bf2eb9f6fa626b36a.json
e080101fc47da3a707e2187544b96f.json
93
dadc0aa21e570c8489cc56aad7a3fe.json
94
263eef26241afebda29e24c5eaa5ee.json
cf8f3675d8e959fffcde8cad916ebb.json
95
23748c87c364d55d75856d9cb85e4d.json
96
3a5350caf982dc34bc70f7d595ab36.json
974d18e76ea4a6a5ac98ccf9daff64.json
97
0838324909c73f992fa0afc098318d.json
677634f07607e2be5d90dd59359647.json
98
0bf6217abfc82adbe55daa5a294d9e.json
3cc002d4b0330b4de14f51c40fa5d5.json
9d02c2583011642a59c1573307d854.json
99
15bb17dc3c5d1455dced465da4c036.json
24371e529e6249debb3c024a5264d6.json
9a
193173b09561f2e945be54c64d402d.json
ab8a9e69c577538793a59567197a58.json
9d
1f59b2ef1ae7042d0e780c4783aedd.json
a99a21e7934eb86a89a596d46ea17f.json
9f
af529c5004eaa0d7edc69a1eb20d52.json
b3aef6a817a18e43ebfeded2c31409.json
d703d289526c848cbaf947ff4066ad.json
a0
3fcf5231b8e7fd06ff07e8655fcdef.json
a1
ed800519d20da8f0094161119de413.json
a3
068afb2b86b7f2f716742eff337e0b.json
59e9c83af9a10a948cbfe4fbdd5f61.json
ff08bd1b466e9f97ecfe194b575886.json
a6
3a9a4e93220563fda9bc4d1005ef03.json
a80013a9347ff5aafad2a9805f35f1.json
b8e7cf0aaaa7d712e63ffd8d774350.json
a7
0eac7aa3b50fc9c0c0ff39511543b5.json
abf514da3a3af5109a451d20b86178.json
b5aba5ed11972d676a7ea1104e1690.json
a9
3bdae049769a1e7b9c858a29988254.json
b7f2269432126a0c2ffedceb827f65.json
ac
3fee61e9a5b21da27b65ff2bc8ea39.json
cb24f41b173c32930315c5ac404274.json
ad
4f03adf3f72acfe1aae5f2071feae9.json
6ae7e6e86c095e36f148471d5d43f1.json
ae
0f008f8d147e1944a7c5678ec5ea20.json
af
3d655c55010e1f7b0d178ede06c275.json
d7b7a786db5e3a08db6a0f541e5a5a.json
b0
433762c57fd322adb7bc61f2ee5fc7.json
bf62a4be7a00677352b6b1359e89d1.json
b1
8585fd0f44890db04714b78cda58ea.json
b2
47d4bb2c90c8935d5240d8ce375e45.json
77bccb88af44e5021538acb6c76273.json
b3
1f656e9cecff221a842a6c4656e60b.json
8be820b3d37c26258f9979396a769f.json
b4
1db6d7b977e40d77bfdaad5b38795e.json
3735d611e24ab5654116beb8d78f7e.json
542b0e86838afe87b034f7984b237f.json
f6c90fdbff4721204965ce6ba63f44.json
f9aaf4d5ce52da38abbfd79f2c1556.json
b6
1bdae4bf75ded259129f46856e380d.json
59c23d7b277e628eca448e83a741e5.json
876d2b784eb099cb3966c492e41b75.json
b8
5117f576034c5a050e8d57a7ce2ec0.json
72f7113fa2bcab94c5944005675ec1.json
c1da49b59ae28c8e04136b5e55c2fa.json
b9
48930d6827271fc58324455417c3f0.json
88d1dfbfe163b7b66d092d99de7d73.json
ba
3a145fd70346171fe728a149a4bc30.json
85c336e3bcd237938a1ee27ee9e612.json
e4af0a058b708be4f814cd8421cc3a.json
bb
38654967342197b52b133f5e9a5c98.json
c77d45efc6bccceb2f7227d9e73c9b.json
fe450e8ce6f2c839e4ca6b3ab98b2d.json
bc
7dde33483426fb58404d35e93baa07.json
bd
4fb2efc67743ad138b2548af0540f4.json
c0
69887570ea4951170b15b4a3fcb102.json
c1
68e85a623f5228c2ef29239c749d88.json
c2
5aadb72095a5a1bc55e75697be4852.json
ab81dd116a0f860659185693bde0c4.json
ce9cd69b0c5a9d6cd4e3fd6c4c9358.json
d7dc87a7bc70d51ccc9c7f5d845a07.json
c3
24faceecf3d90541fe60a053fa5291.json
5194ad3ae736a6515d355bf072e4bb.json
c4
439a8a92035f77792560517f2f42be.json
cd4b7b1f461747798ecd73adbf3f1c.json
c6
6e989933d640fc7caf0d953ec9cd2b.json
c7
91793d190079f7c53020a0e843a746.json
c8
2fa26cd9f6c5832e0ab87f3486ffbf.json
c9
34cca3a11e49d8ae183c5d3c2cb865.json
cc30b7ff9d54ffbb14c6e831ee7240.json
ca
5f0d295a7c55c834dff1afe7e19e4f.json
cb
5f22c672b2621b5b77a911a3deac7c.json
cd
2429cb114d20d31f5a0aae089e03dd.json
ce
9c86c5814f2add2e98ca3fd269af0f.json
e143c2c5a68f2d61453a1ec7b0131f.json
cf
5bd21847259d6cd7ed912f0e6bfee8.json
beb809ecd13186416e3d16c4cda326.json
d1
36515d6182fc803bf18c521640c656.json
492669f1d35ca286e3dbbe13e8dbaa.json
989251b78b538a4c9e04a966c6cfc9.json
d2
64fdaf8ddc1b71da1bb9d76204e9ef.json
d7358f9ff35579c5bc9423c22749b6.json
d3
30218da20a9015727a650460a4dd0d.json
4ebd5389102c472666fe95dc14ae77.json
50ac1e8782426e5d865416b3afa15c.json
d4
4f7509d82819ba8316da638b37117b.json
8a6c5b3531684aab122263e21252cb.json
d5
0d21517c06f3912b9ed5f176540af3.json
d6
2d1693353af8a581fad332eaa9ee8d.json
986b50924fd6e82bf7ba7f88ffd688.json
9b06961ecb2ce3e47d8a7593eac73d.json
d7
2ae25a06152fb385965b8bb7e56b0e.json
8c4581f2af87aa90d4c4c447a83736.json
a3e6eb6955dada451f14336a187583.json
ac42d9574854b3c863b98654b94458.json
d9
0810baaa35e307678fac7c88245222.json
9721a15394e33094c6bcdb53bdd0bb.json
da
b925c9f55e13a2d834f355387f0783.json
db
58bcc4b5703ef367c3b802948119db.json
dc
32cb4bc2ec0db174fc91224525f7e4.json
7f042f5b024c2d10702ef006eb8378.json
f7a4a18df733378c4f468123a13c76.json
dd
660a0b85b874a71eb4976f1f5dfb78.json
e6b74c1c6c5121a6d4c2e79f7521aa.json
de
2f7f055b01546930fc1d9c70afcee6.json
6605eff3c47de60d298a69d4757276.json
e0
a3e5a7fc49b140584d3682bd81d2b9.json
fab153845f4d380f21b64a98892f7d.json
e1
e7ff371763b49518bf3803df14e5fb.json
e2
f34e0cdc05b06a9720992f6e5f91c1.json
fa15150c34051be1731998bf698c2f.json
e3
174e8a69ddc5b8389e3e0cdd218fd8.json
9cb8983336834de05a83984356ad31.json
e4
4141047720a32f41c8284e567de0f6.json
6be949ef6579de4f60ed56f1a887cf.json
73747c2bd57388b4d0057ae3835e34.json
df13b2521e72eef90cca6ba9beed0e.json
e5
55bd4e3fe75f67911104fabee61e80.json
5fb13080ed01b5e2e5f3ec148c31dd.json
6c4cc08f7596eab62f17a177bff377.json
e6
3c6c29069716e2a4ec107545c7f7b5.json
607e75db930e2e51a7205a414776e8.json
a9a81d1314715cef71841119eb6c50.json
e7
429090944c655d1ff0280ffecf03ed.json
e9
0b833cebef02e34a121773b3875534.json
56219b162f919e008262a99398435c.json
ea
292b312a5edbfd26b89cd38b3624b0.json
b893bf5ce7c790f85b4ed7ea377c11.json
eb
7c712c68bc4de37dd611ef47950c1a.json
fb0a6cd79f09b996597f9ecf5b0165.json
ec
1c08bc9bd093b12c5fa2cb2aba6097.json
ea4768b7ba8b5fb57ec1dc61035229.json
ed
31c9350b84dec341a917f4982186d0.json
5e51807ff79335f4cb4ca104e4053e.json
69b787f4c4a85487049a0fc131eb98.json
9b1bc9d441267baceade87cac8c10e.json
ee
962205f6d49e75b13988456e62c2e6.json
ef
0a72a6e4b3b438181d6a1e3bf27837.json
59262a31c079875fc3dbb73063819e.json
70ab142351bdda38bf98cbc7e1e68e.json
9a3566bd83ad6eac3b3aa014323d8a.json
b9621a1d157aa320ca04c043567465.json
f0
8c2eea58c688f7b7e4e48762d9266c.json
db7d59af4bb09ba2cdd4e0f8147fa5.json
f1
13d42de190ac6904648432354060f2.json
f2
b2a6a7fe676ef6572ea8740a1609ae.json
f4
fc71beb9c899bd78d67b7038e83253.json
f5
131cfb85710952c3ecae81e3de135c.json
f6
1175a7c9130c3b771480aeeab2cf45.json
e2af40f022a2a9d1ad87546426838b.json
f7
42cc58eda498d098d7ef9f13257fa1.json
f8
d0a2b7e9342fb9d973f549e250715b.json
f9
3de59d031ab86e097492cf7dec46f1.json
8717efcaef00125ebac7213cfd7d62.json
fa
7021df8116e9a4715faf19cc2d87ea.json
94391cc4fce490cc3ad9900296a1a5.json
fb
2b6a0ff731bc93aff38b500e82ecae.json
fd
78d3e11ffa58d35ccd3d6f766481b0.json
df8da9882fcf52a56bed9a60ba83cb.json
fe
1cc5f2aacf6774f8dbe834e7ce2265.json
9155d6552b668520b6700e5ee3ae84.json
Welcome to debugging React
.gitpod.yml
Cargo.toml
README-Windows.md
README.md
build.bat
build.sh
dist
index.html
logo-white.7fec831f.svg
src.e31bb0bc.css
flags.sh
nft
Cargo.toml
src
lib.rs
package.json
res
README.md
src
App.css
App.js
Components
AllTabs
FirstTab.js
SecondTab.js
InfoBubble.js
MintingTool.js
TabComponent
TabContent.js
TabNavItem.js
Tabs.js
__mocks__
fileMock.js
assets
logo-black.svg
logo-white.svg
near_icon.svg
near_logo_wht.svg
config.js
global.css
index.html
index.js
jest.init.js
main.test.js
utils.js
wallet
login
index.html
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
| # Folder that contains wasm files
Non-fungible Token (NFT)
===================
[](https://gitpod.io/#https://github.com/near-examples/NFT)
This repository includes an example implementation of a [non-fungible token] contract which uses [near-contract-standards] and [simulation] tests.
[non-fungible token]: https://nomicon.io/Standards/NonFungibleToken/README.html
[near-contract-standards]: https://github.com/near/near-sdk-rs/tree/master/near-contract-standards
[simulation]: https://github.com/near/near-sdk-rs/tree/master/near-sdk-sim
Prerequisites
=============
If you're using Gitpod, you can skip this step.
* Make sure Rust is installed per the prerequisites in [`near-sdk-rs`](https://github.com/near/near-sdk-rs).
* Make sure [near-cli](https://github.com/near/near-cli) is installed.
Explore this contract
=====================
The source for this contract is in `nft/src/lib.rs`. It provides methods to manage access to tokens, transfer tokens, check access, and get token owner. Note, some further exploration inside the rust macros is needed to see how the `NonFungibleToken` contract is implemented.
Building this contract
======================
Run the following, and we'll build our rust project up via cargo. This will generate our WASM binaries into our `res/` directory. This is the smart contract we'll be deploying onto the NEAR blockchain later.
```bash
./build.sh
```
Testing this contract
=====================
We have some tests that you can run. For example, the following will run our simple tests to verify that our contract code is working.
```bash
cargo test -- --nocapture
```
The more complex simulation tests aren't run with this command, but we can find them in `tests/sim`.
Using this contract
===================
### Quickest deploy
You can build and deploy this smart contract to a development account. [Dev Accounts](https://docs.near.org/docs/concepts/account#dev-accounts) are auto-generated accounts to assist in developing and testing smart contracts. Please see the [Standard deploy](#standard-deploy) section for creating a more personalized account to deploy to.
```bash
near dev-deploy --wasmFile res/non_fungible_token.wasm
```
Behind the scenes, this is creating an account and deploying a contract to it. On the console, notice a message like:
>Done deploying to dev-1234567890123
In this instance, the account is `dev-1234567890123`. A file has been created containing a key pair to
the account, located at `neardev/dev-account`. To make the next few steps easier, we're going to set an
environment variable containing this development account id and use that when copy/pasting commands.
Run this command to set the environment variable:
```bash
source neardev/dev-account.env
```
You can tell if the environment variable is set correctly if your command line prints the account name after this command:
```bash
echo $CONTRACT_NAME
```
The next command will initialize the contract using the `new` method:
```bash
near call $CONTRACT_NAME new_default_meta '{"owner_id": "'$CONTRACT_NAME'"}' --accountId $CONTRACT_NAME
```
To view the NFT metadata:
```bash
near view $CONTRACT_NAME nft_metadata
```
### Standard deploy
This smart contract will get deployed to your NEAR account. For this example, please create a new NEAR account. Because NEAR allows the ability to upgrade contracts on the same account, initialization functions must be cleared. If you'd like to run this example on a NEAR account that has had prior contracts deployed, please use the `near-cli` command `near delete`, and then recreate it in Wallet. To create (or recreate) an account, please follow the directions in [Test Wallet](https://wallet.testnet.near.org) or ([NEAR Wallet](https://wallet.near.org/) if we're using `mainnet`).
In the project root, log in to your newly created account with `near-cli` by following the instructions after this command.
near login
To make this tutorial easier to copy/paste, we're going to set an environment variable for our account id. In the below command, replace `MY_ACCOUNT_NAME` with the account name we just logged in with, including the `.testnet` (or `.near` for `mainnet`):
ID=MY_ACCOUNT_NAME
We can tell if the environment variable is set correctly if our command line prints the account name after this command:
echo $ID
Now we can deploy the compiled contract in this example to your account:
near deploy --wasmFile res/non_fungible_token.wasm --accountId $ID
NFT contract should be initialized before usage. More info about the metadata at [nomicon.io](https://nomicon.io/Standards/NonFungibleToken/Metadata.html). But for now, we'll initialize with the default metadata.
near call $ID new_default_meta '{"owner_id": "'$ID'"}' --accountId $ID
We'll be able to view our metadata right after:
near view $ID nft_metadata
Then, let's mint our first token. This will create a NFT based on Olympus Mons where only one copy exists:
near call $ID nft_mint '{"token_id": "0", "receiver_id": "'$ID'", "token_metadata": { "title": "Olympus Mons", "description": "Tallest mountain in charted solar system", "media": "https://upload.wikimedia.org/wikipedia/commons/thumb/0/00/Olympus_Mons_alt.jpg/1024px-Olympus_Mons_alt.jpg", "copies": 1}}' --accountId $ID --deposit 0.1
Transferring our NFT
====================
Let's set up an account to transfer our freshly minted token to. This account will be a sub-account of the NEAR account we logged in with originally via `near login`.
near create-account alice.$ID --masterAccount $ID --initialBalance 10
Checking Alice's account for tokens:
near view $ID nft_tokens_for_owner '{"account_id": "'alice.$ID'"}'
Then we'll transfer over the NFT into Alice's account. Exactly 1 yoctoNEAR of deposit should be attached:
near call $ID nft_transfer '{"token_id": "0", "receiver_id": "alice.'$ID'", "memo": "transfer ownership"}' --accountId $ID --depositYocto 1
Checking Alice's account again shows us that she has the Olympus Mons token.
Notes
=====
* The maximum balance value is limited by U128 (2**128 - 1).
* JSON calls should pass U128 as a base-10 string. E.g. "100".
* This does not include escrow functionality, as ft_transfer_call provides a superior approach. An escrow system can, of course, be added as a separate contract or additional functionality within this contract.
AssemblyScript
==============
Currently, AssemblyScript is not supported for this example. An old version can be found in the [NEP4 example](https://github.com/near-examples/NFT/releases/tag/nep4-example), but this is not recommended as it is out of date and does not follow the standards the NEAR SDK has set currently.
|
near-tips_extension | dist
manifest.json
popup.html
package-lock.json
package.json
src
background
background.js
classes.js
content
content.css
content.js
popup
DefaultTips
index.js
Deposit
index.js
PopupContainer
index.js
popup.css
utils
constants.js
logger.js
messages.js
near-utils.js
notify.js
useNearSetup.js
webpack.config.js
| |
mhassanist_sample-rust-vector-near | Cargo.toml
README.md
rustfmt.toml
src
lib.rs
| |
Kariimayman_PharmacyBlockchain | README.md
as-pect.config.js
asconfig.json
assembly
Transaction.ts
as_types.d.ts
index.ts
tsconfig.json
neardev
dev-account.env
package.json
| This is my First project using NEAR and BLOCKCHAINS,This project was created as a submission for an internship program.
My idea is that pharmacies logs are non-changeable and this program simulates a demo of pharmacy that keeps all of its logs on the chain to protect doctors/consumers from fraud and drugs misuse.
The AddDrug function simulates the supplier adding new drugs to the pharmacy.
The RemoveDrung function simulates the consumer purchasing a drug from the pharmacy.
Use this account for an already tested and deployed program -> project.kareemayman.testnet.
Try using the View functions on the PowerShell terminal and any other functions on Bash terminal because sometimes it would return a random error and this is what worked for me.
|
near-examples_crossword-tutorial-chapter-3 | README.md
babel.config.js
contract
Cargo.toml
README.md
build.sh
src
lib.rs
test.sh
testnet-chapter-3-args.sh
testnet.sh
package.json
src
App.css
App.js
components
CrosswordPage.js
NoCrosswordsPage.js
SuccessPage.js
WonPage.js
config.js
css
main.css
normalize.css
fonts
OFL.txt
README.txt
index.html
index.js
loader.js
utils.js
| Crossword Smart Contract
==================
A [smart contract] written in [Rust] that demonstrates a crossword puzzle on the NEAR blockchain.
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 `./build.sh` script.
2. Tests: You can run smart contract tests with the `./test.sh` 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/develop/welcome
[Rust]: https://www.rust-lang.org/
[correct target]: https://github.com/near/near-sdk-rs#pre-requisites
[cargo]: https://doc.rust-lang.org/book/ch01-03-hello-cargo.html
Chapter 3 of the NEAR crossword tutorial
==================
How to play with this contract
===============================
1. Clone the repo.
```
git clone https://github.com/near-examples/crossword-tutorial-chapter-3
cd crossword-tutorial-chapter-3
```
2. Next, make sure you have NEAR CLI by running:
```
near --version
```
If you need to install `near-cli`:
```
npm install near-cli -g
```
3. Build the smart contract
```
cd contract
./build.sh
```
4. Run `near dev-deploy` to deploy the contract to `testnet`.
5. Create a crossword, let's say that the answer to your crossword is "many clever words"
6. Answer for your crossword from now on will be a seed phrase! Let's generate key pair out of it.
```bash
near generate-key randomAccountId.testnet --seedPhrase='many clever words'
```
Now this key pair will be store on your machine under `~/.near-credentials/testnet/randomAccountId.json`
7. We should add your puzzle to our contract. To do that run
```bash
near call <contract-account-id> new_puzzle '{"answer_pk":"<generated-pk>"}' --accountId=<signer-acc-id> --deposit=10
```
Where:
- `contract-account-id` - Account on which contract is stored. If you have used `near dev-deploy` in the first step it was autogenerated for you. It should look like `dev-<random-numbers>`.
- `generate-pk` - Public key from JSON generated in the step #4
- `accountId` - your existing testnet accountId (you can create one at https://wallet.testnet.near.org/)
- `deposit` - reword for the person who will solve this puzzle
After this call your puzzle will be added to the NEAR Crossword contract. Share your Crossword with friends, the person who will be able to solve it will be able to generate the same key pair and get the reward. Let's do that in the following steps.
8. Pretend that we have solved the puzzle and generated the very same key pair. This time it should be stored at `~/.near-credentials/testnet/<contract-id>.json`. We are using `<contract-id>` here because in the next step we will need to sign the transaction with this acc.
Attention! If you are using the same machine, your old key pair from `<dev-acc>` will be overwritten! Save it in some other place if you need it. Keys are stored in `~/.near-credentials/testnet/` folder.
To generate the new key:
```bash
near generate-key <crossword-contract-id> --seedPhrase='many clever words'
```
Also, we need to have another key that will be used later to get the reward. Let's generate it.
```bash
near generate-key keyToGetTheReward.testnet
```
7. Let's call `submit_solution` function to solve this puzzle.
```bash
near call <contract-id> submit_solution '{"solver_pk":"<PK from keyToGetTheReward.testnet>"}' --accountId=<contract-id>
```
Puzzle solved! Let's get our reward!
8. To get the reward we need to call the `claim_reward` function with the function call key that we have added in the previous step. Before that call we should prepare the keys:
```bash
cp ~/.near-credentials/testnet/keyToGetTheReward.testnet.json ~/.near-credentials/testnet/<contract-id>.json
```
And now we can claim our reward:
```bash
near call <contract-id> claim_reward '{"receiver_acc_id":"serhii.testnet", "crossword_pk":"<PK from randomAccountId account>", "memo":"Victory!"}' --accountId=<contract-id>
```
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 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 `crossword.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `crossword.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 crossword.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 || 'crossword.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
[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://docs.near.org/tools/near-cli
[gh-pages]: https://github.com/tschaub/gh-pages
|
Learn-NEAR-Club_for_nep141 | README.md
nep141transfer
.gitpod.yml
README.md
babel.config.js
contract
Cargo.toml
README.md
call.sh
compile.js
deploy.sh
src
lib.rs
target
.rustc_info.json
debug
.fingerprint
Inflector-800d07129f6cdf34
lib-inflector.json
ahash-b65b262a71b5b48f
lib-ahash.json
aho-corasick-5234701034b12ee4
lib-aho_corasick.json
autocfg-d43d9e10379c8327
lib-autocfg.json
base64-5c7414cfb92860e8
lib-base64.json
block-buffer-48a0121b7a494a71
lib-block-buffer.json
block-buffer-4f3fb299dcc57797
lib-block-buffer.json
block-padding-24376a58a4f53824
lib-block-padding.json
borsh-38a358ea8d1b6330
lib-borsh.json
borsh-derive-2496b5a3da2de1d5
lib-borsh-derive.json
borsh-derive-internal-71f7df885f5fc9d1
lib-borsh-derive-internal.json
borsh-schema-derive-internal-d48151dcd18bd47d
lib-borsh-schema-derive-internal.json
bs58-6d6a6df200788597
lib-bs58.json
byte-tools-a0454fdb8e320603
lib-byte-tools.json
byteorder-477bf8c6d3a0e523
build-script-build-script-build.json
byteorder-541037c38e614382
run-build-script-build-script-build.json
byteorder-d836ba3e41654e24
lib-byteorder.json
cfg-if-38c8a3e888ecb06a
lib-cfg-if.json
cfg-if-e7a28af79b261e75
lib-cfg-if.json
convert_case-7aafe547bc5ceeeb
lib-convert_case.json
cpuid-bool-464b343952c951fe
lib-cpuid-bool.json
derive_more-5df7e3e03b033154
lib-derive_more.json
digest-8eb0f00a25be5de8
lib-digest.json
digest-a6306f4b8b561fd0
lib-digest.json
generic-array-3d570e92a726c457
run-build-script-build-script-build.json
generic-array-4e5a80a149b11b12
lib-generic_array.json
generic-array-b1f13dbac0488c4c
lib-generic_array.json
generic-array-db4e6ee7ce77adcf
build-script-build-script-build.json
hashbrown-1996868e232a969d
run-build-script-build-script-build.json
hashbrown-5b53035a525237f4
lib-hashbrown.json
hashbrown-67e4b559fbdc6052
build-script-build-script-build.json
hashbrown-d70458254ef89d14
lib-hashbrown.json
hex-26332ec05e0770db
lib-hex.json
indexmap-8272f3af80ca6d09
lib-indexmap.json
indexmap-c44c39c626da403f
build-script-build-script-build.json
indexmap-e9541724a67540a6
run-build-script-build-script-build.json
itoa-4365935becaf39d2
lib-itoa.json
keccak-ed6528dddc74fc69
lib-keccak.json
lazy_static-5c53d641eb010a81
lib-lazy_static.json
libc-5b4c4db6d7de7114
lib-libc.json
libc-aa9cacf7625af113
build-script-build-script-build.json
libc-cb24f294663ed32f
run-build-script-build-script-build.json
memchr-31f61a31cc94078a
build-script-build-script-build.json
memchr-529486d68603d187
run-build-script-build-script-build.json
memchr-9559fd627c3017a7
lib-memchr.json
memory_units-eac19ce3353440d4
lib-memory_units.json
near-contract-standards-33ceb1d5329bcbe2
lib-near-contract-standards.json
near-primitives-core-2729ea16ccb58af0
lib-near-primitives-core.json
near-rpc-error-core-b81897cee34ee445
lib-near-rpc-error-core.json
near-rpc-error-macro-77a0da42930561dd
lib-near-rpc-error-macro.json
near-runtime-utils-cb5598dbc5fa1ede
lib-near-runtime-utils.json
near-sdk-core-6d55c350445995df
lib-near-sdk-core.json
near-sdk-fa0c3f8fcbf68096
lib-near-sdk.json
near-sdk-macros-d07ac3678987a9c0
lib-near-sdk-macros.json
near-vm-errors-3f84c9b231654038
lib-near-vm-errors.json
near-vm-logic-06517b87cf53cd46
lib-near-vm-logic.json
num-bigint-30ed1efb7d4614f9
lib-num-bigint.json
num-bigint-738950308211bdc4
build-script-build-script-build.json
num-bigint-903fba555a0294e1
run-build-script-build-script-build.json
num-integer-008ef4a1adfea7f9
lib-num-integer.json
num-integer-729ca4e2d130a65c
run-build-script-build-script-build.json
num-integer-f15fbd4e37130eca
build-script-build-script-build.json
num-rational-0b703d2b243f42b3
lib-num-rational.json
num-rational-0c37f8418ca2ece8
build-script-build-script-build.json
num-rational-7717938b666bda74
run-build-script-build-script-build.json
num-traits-32ab1c2cdbda060a
run-build-script-build-script-build.json
num-traits-5741655b2ee87f30
build-script-build-script-build.json
num-traits-f5d93b6c3af2aac0
lib-num-traits.json
opaque-debug-45a15423c8ac1fee
lib-opaque-debug.json
opaque-debug-abc732d989c9d05a
lib-opaque-debug.json
proc-macro-crate-453199bbea6e7da8
lib-proc-macro-crate.json
proc-macro2-078cf92a0d8e67c9
run-build-script-build-script-build.json
proc-macro2-48023dd2ea5720b7
build-script-build-script-build.json
proc-macro2-540b6631119ce641
lib-proc-macro2.json
quote-2d316e7355c2bd28
lib-quote.json
regex-ff7b93346f2be0bb
lib-regex.json
regex-syntax-5c8121566f39070a
lib-regex-syntax.json
ryu-059aa1fbb24cd15e
lib-ryu.json
ryu-a3e82c1c02ae1955
build-script-build-script-build.json
ryu-f99552c5fa0b2a9b
run-build-script-build-script-build.json
serde-62c745322dbfa55f
run-build-script-build-script-build.json
serde-a6f085765be5773f
lib-serde.json
serde-d3806f79d3ce6de0
build-script-build-script-build.json
serde_derive-08a09e34df56f722
build-script-build-script-build.json
serde_derive-374b32841dff1025
lib-serde_derive.json
serde_derive-39f5282f60218653
run-build-script-build-script-build.json
serde_json-355599846872559a
lib-serde_json.json
serde_json-3be56b3afbb219d7
build-script-build-script-build.json
serde_json-89ecf85119327278
run-build-script-build-script-build.json
sha2-e9660514a60eeafa
lib-sha2.json
sha3-85766bf0f4d660d2
lib-sha3.json
syn-94cda2719c0e8bf9
lib-syn.json
syn-c450192d11660aa8
run-build-script-build-script-build.json
syn-db0672afc39b9b75
build-script-build-script-build.json
token-swap-testnet-2c2ae977d75a1fee
lib-token-swap-testnet.json
token-swap-testnet-9477e911e9424f17
test-lib-token-swap-testnet.json
toml-fbd4ae0f8223247c
lib-toml.json
typenum-2e8a23d2e72498ba
build-script-build-script-main.json
typenum-65efd23b6c1d4655
lib-typenum.json
typenum-f6d195b3ffce7585
run-build-script-build-script-main.json
unicode-xid-12009cf1a2496f6d
lib-unicode-xid.json
version_check-d6dca5d2eaa8c554
lib-version_check.json
wee_alloc-044c4ffd9be5f7bf
lib-wee_alloc.json
wee_alloc-5924e4acfa8ae6c6
build-script-build-script-build.json
wee_alloc-d3ee9f4f34f817d6
run-build-script-build-script-build.json
build
num-bigint-903fba555a0294e1
out
radix_bases.rs
typenum-f6d195b3ffce7585
out
consts.rs
op.rs
tests.rs
wee_alloc-d3ee9f4f34f817d6
out
wee_alloc_static_array_backend_size_bytes.txt
release
.fingerprint
Inflector-5749979cefab0aea
lib-inflector.json
autocfg-3f6504d403aebb13
lib-autocfg.json
borsh-derive-2834e9c66b9f6131
lib-borsh-derive.json
borsh-derive-internal-df0fa273e74794a8
lib-borsh-derive-internal.json
borsh-schema-derive-internal-4fc0ea913b7ea568
lib-borsh-schema-derive-internal.json
byteorder-0292db916d9dedf9
build-script-build-script-build.json
convert_case-d61cbb148bff0687
lib-convert_case.json
derive_more-8b21e87a2d6cf361
lib-derive_more.json
generic-array-e006a62c75373819
build-script-build-script-build.json
hashbrown-4cac487d76ede60f
run-build-script-build-script-build.json
hashbrown-63d2f7b81a8ab82e
build-script-build-script-build.json
hashbrown-8d331258e55ddbfb
lib-hashbrown.json
indexmap-30475067e5920015
lib-indexmap.json
indexmap-89b15de24e86a31b
run-build-script-build-script-build.json
indexmap-cabe69f1a7e1fdc9
build-script-build-script-build.json
itoa-9f4fb4841fb2e1c0
lib-itoa.json
memchr-569c819b7482fc3f
build-script-build-script-build.json
near-rpc-error-core-f264d2494024f924
lib-near-rpc-error-core.json
near-rpc-error-macro-90b8150f0c7f470f
lib-near-rpc-error-macro.json
near-sdk-core-032f2d8a340d3933
lib-near-sdk-core.json
near-sdk-macros-e31f95ac88d52b90
lib-near-sdk-macros.json
num-bigint-40697c0e877261cb
build-script-build-script-build.json
num-integer-2eb5029502a0bde8
build-script-build-script-build.json
num-rational-5ee415194a7efd8a
build-script-build-script-build.json
num-traits-72a14a33045ac8d1
build-script-build-script-build.json
proc-macro-crate-1bfc3f79ebbb1be2
lib-proc-macro-crate.json
proc-macro2-1a1dfdb1c780706c
lib-proc-macro2.json
proc-macro2-4cb02ba5cc702bad
build-script-build-script-build.json
proc-macro2-bb481a784045799c
run-build-script-build-script-build.json
quote-b5543ec51d1d6855
lib-quote.json
ryu-226f1d8f7effe500
lib-ryu.json
ryu-33d63cf8baf83297
run-build-script-build-script-build.json
ryu-bd6fd6ed98668f10
build-script-build-script-build.json
serde-3962d7e81b55f82d
lib-serde.json
serde-aa28080fc5443ad8
run-build-script-build-script-build.json
serde-e1d69ac1029f46cf
build-script-build-script-build.json
serde_derive-1d4d1dbbd1b68d10
lib-serde_derive.json
serde_derive-a63028e0f4689ad6
build-script-build-script-build.json
serde_derive-b9d6662241bb17fb
run-build-script-build-script-build.json
serde_json-1ab35cb35cd7c7a4
lib-serde_json.json
serde_json-2014bf7ee871c82d
build-script-build-script-build.json
serde_json-e5f32c081008a946
run-build-script-build-script-build.json
syn-17dbd3ecff78966f
build-script-build-script-build.json
syn-33b2077f21d43737
run-build-script-build-script-build.json
syn-775142f13c5d1fdd
lib-syn.json
toml-a8d2ca19cbed6504
lib-toml.json
typenum-4f0cd91bdd29748b
build-script-build-script-main.json
unicode-xid-e4e736734ff8b42a
lib-unicode-xid.json
version_check-c1ef40f964686aae
lib-version_check.json
wee_alloc-0a13e1daccaecc5c
build-script-build-script-build.json
rls
.rustc_info.json
debug
.fingerprint
Inflector-800d07129f6cdf34
lib-inflector.json
ahash-bcc8848a7f2ae332
lib-ahash.json
aho-corasick-1cbef844a76b5d3c
lib-aho_corasick.json
autocfg-d43d9e10379c8327
lib-autocfg.json
base64-06135271d248c171
lib-base64.json
block-buffer-7b4189d02841db12
lib-block-buffer.json
block-buffer-a936c44369c6687a
lib-block-buffer.json
block-padding-38cd3b2c66637c8d
lib-block-padding.json
borsh-41d6d25f6342d922
lib-borsh.json
borsh-derive-2496b5a3da2de1d5
lib-borsh-derive.json
borsh-derive-internal-71f7df885f5fc9d1
lib-borsh-derive-internal.json
borsh-schema-derive-internal-d48151dcd18bd47d
lib-borsh-schema-derive-internal.json
bs58-a151b08edefd8abf
lib-bs58.json
byte-tools-818b0adb94c52bf7
lib-byte-tools.json
byteorder-461198e3a3e1689c
lib-byteorder.json
byteorder-477bf8c6d3a0e523
build-script-build-script-build.json
byteorder-541037c38e614382
run-build-script-build-script-build.json
cfg-if-20b9f5fb82bebd1b
lib-cfg-if.json
cfg-if-810dd9fbe1e28608
lib-cfg-if.json
convert_case-7aafe547bc5ceeeb
lib-convert_case.json
cpuid-bool-ad75c1c2944cc795
lib-cpuid-bool.json
derive_more-5df7e3e03b033154
lib-derive_more.json
digest-9dcf0aa3154dc7bb
lib-digest.json
digest-ab0611971c63a183
lib-digest.json
generic-array-1dbbaa2e2fa530e9
lib-generic_array.json
generic-array-3d570e92a726c457
run-build-script-build-script-build.json
generic-array-b3f8cd377f843cf3
lib-generic_array.json
generic-array-db4e6ee7ce77adcf
build-script-build-script-build.json
greeter-00ca0aea9c5637fa
test-lib-greeter.json
greeter-e1c5515f6f515563
lib-greeter.json
hashbrown-1996868e232a969d
run-build-script-build-script-build.json
hashbrown-1df96b88cb790594
lib-hashbrown.json
hashbrown-34c060aeea2a27f8
lib-hashbrown.json
hashbrown-5b53035a525237f4
lib-hashbrown.json
hashbrown-67e4b559fbdc6052
build-script-build-script-build.json
hex-4e132399b961d086
lib-hex.json
indexmap-25c44c019f255a34
lib-indexmap.json
indexmap-8272f3af80ca6d09
lib-indexmap.json
indexmap-c44c39c626da403f
build-script-build-script-build.json
indexmap-e9541724a67540a6
run-build-script-build-script-build.json
itoa-3a4185a1241cab3f
lib-itoa.json
itoa-4365935becaf39d2
lib-itoa.json
keccak-0308e12d974eb640
lib-keccak.json
lazy_static-acd7d23482fe8b54
lib-lazy_static.json
libc-a4a086f32dc5095c
lib-libc.json
libc-aa9cacf7625af113
build-script-build-script-build.json
libc-cb24f294663ed32f
run-build-script-build-script-build.json
memchr-31f61a31cc94078a
build-script-build-script-build.json
memchr-529486d68603d187
run-build-script-build-script-build.json
memchr-a54d4b647f438279
lib-memchr.json
memory_units-78e37e243757af92
lib-memory_units.json
near-contract-standards-7cac6b9ffeb58c8c
lib-near-contract-standards.json
near-primitives-core-10b3717619638d24
lib-near-primitives-core.json
near-rpc-error-core-b81897cee34ee445
lib-near-rpc-error-core.json
near-rpc-error-macro-77a0da42930561dd
lib-near-rpc-error-macro.json
near-runtime-utils-1e65fbd610bd7fff
lib-near-runtime-utils.json
near-sdk-77a648afbdb7804c
lib-near-sdk.json
near-sdk-core-6d55c350445995df
lib-near-sdk-core.json
near-sdk-macros-d07ac3678987a9c0
lib-near-sdk-macros.json
near-vm-errors-03c19ad4a73a9441
lib-near-vm-errors.json
near-vm-logic-c7bd82123138e73b
lib-near-vm-logic.json
num-bigint-738950308211bdc4
build-script-build-script-build.json
num-bigint-903fba555a0294e1
run-build-script-build-script-build.json
num-bigint-bf5e2b767df1c977
lib-num-bigint.json
num-integer-374bc874abd03eea
lib-num-integer.json
num-integer-729ca4e2d130a65c
run-build-script-build-script-build.json
num-integer-f15fbd4e37130eca
build-script-build-script-build.json
num-rational-0000a14962554f15
lib-num-rational.json
num-rational-0c37f8418ca2ece8
build-script-build-script-build.json
num-rational-7717938b666bda74
run-build-script-build-script-build.json
num-traits-32ab1c2cdbda060a
run-build-script-build-script-build.json
num-traits-5741655b2ee87f30
build-script-build-script-build.json
num-traits-a1e2ecf636bdf134
lib-num-traits.json
opaque-debug-dbbd94c139b791ac
lib-opaque-debug.json
opaque-debug-e348ac3040cb1f3b
lib-opaque-debug.json
proc-macro-crate-453199bbea6e7da8
lib-proc-macro-crate.json
proc-macro2-078cf92a0d8e67c9
run-build-script-build-script-build.json
proc-macro2-48023dd2ea5720b7
build-script-build-script-build.json
proc-macro2-540b6631119ce641
lib-proc-macro2.json
quote-2d316e7355c2bd28
lib-quote.json
regex-6792f3d5f7a30912
lib-regex.json
regex-syntax-283170c95ddd4231
lib-regex-syntax.json
ryu-059aa1fbb24cd15e
lib-ryu.json
ryu-0bcf425490ac7c5b
lib-ryu.json
ryu-a3e82c1c02ae1955
build-script-build-script-build.json
ryu-f99552c5fa0b2a9b
run-build-script-build-script-build.json
serde-62c745322dbfa55f
run-build-script-build-script-build.json
serde-a6f085765be5773f
lib-serde.json
serde-d3806f79d3ce6de0
build-script-build-script-build.json
serde-fd8a30d646d2c3c7
lib-serde.json
serde_derive-08a09e34df56f722
build-script-build-script-build.json
serde_derive-374b32841dff1025
lib-serde_derive.json
serde_derive-39f5282f60218653
run-build-script-build-script-build.json
serde_json-000bb3d9cc2942b5
lib-serde_json.json
serde_json-355599846872559a
lib-serde_json.json
serde_json-3be56b3afbb219d7
build-script-build-script-build.json
serde_json-89ecf85119327278
run-build-script-build-script-build.json
sha2-3b0cc4e9779a2db1
lib-sha2.json
sha3-4337f43ee7d343a4
lib-sha3.json
syn-94cda2719c0e8bf9
lib-syn.json
syn-c450192d11660aa8
run-build-script-build-script-build.json
syn-db0672afc39b9b75
build-script-build-script-build.json
token-swap-testnet-09d616a24631caf2
lib-token-swap-testnet.json
token-swap-testnet-2386622a0caa8337
test-lib-token-swap-testnet.json
toml-fbd4ae0f8223247c
lib-toml.json
typenum-2e8a23d2e72498ba
build-script-build-script-main.json
typenum-998188894a333e6e
lib-typenum.json
typenum-f6d195b3ffce7585
run-build-script-build-script-main.json
unicode-xid-12009cf1a2496f6d
lib-unicode-xid.json
version_check-d6dca5d2eaa8c554
lib-version_check.json
wee_alloc-5924e4acfa8ae6c6
build-script-build-script-build.json
wee_alloc-c1d7f65472a26d1f
lib-wee_alloc.json
wee_alloc-d3ee9f4f34f817d6
run-build-script-build-script-build.json
build
byteorder-477bf8c6d3a0e523
save-analysis
build_script_build-477bf8c6d3a0e523.json
generic-array-db4e6ee7ce77adcf
save-analysis
build_script_build-db4e6ee7ce77adcf.json
hashbrown-67e4b559fbdc6052
save-analysis
build_script_build-67e4b559fbdc6052.json
indexmap-c44c39c626da403f
save-analysis
build_script_build-c44c39c626da403f.json
libc-aa9cacf7625af113
save-analysis
build_script_build-aa9cacf7625af113.json
memchr-31f61a31cc94078a
save-analysis
build_script_build-31f61a31cc94078a.json
num-bigint-738950308211bdc4
save-analysis
build_script_build-738950308211bdc4.json
num-bigint-903fba555a0294e1
out
radix_bases.rs
num-integer-f15fbd4e37130eca
save-analysis
build_script_build-f15fbd4e37130eca.json
num-rational-0c37f8418ca2ece8
save-analysis
build_script_build-0c37f8418ca2ece8.json
num-traits-5741655b2ee87f30
save-analysis
build_script_build-5741655b2ee87f30.json
proc-macro2-48023dd2ea5720b7
save-analysis
build_script_build-48023dd2ea5720b7.json
ryu-a3e82c1c02ae1955
save-analysis
build_script_build-a3e82c1c02ae1955.json
serde-d3806f79d3ce6de0
save-analysis
build_script_build-d3806f79d3ce6de0.json
serde_derive-08a09e34df56f722
save-analysis
build_script_build-08a09e34df56f722.json
serde_json-3be56b3afbb219d7
save-analysis
build_script_build-3be56b3afbb219d7.json
syn-db0672afc39b9b75
save-analysis
build_script_build-db0672afc39b9b75.json
typenum-2e8a23d2e72498ba
save-analysis
build_script_main-2e8a23d2e72498ba.json
typenum-f6d195b3ffce7585
out
consts.rs
op.rs
tests.rs
wee_alloc-5924e4acfa8ae6c6
save-analysis
build_script_build-5924e4acfa8ae6c6.json
wee_alloc-d3ee9f4f34f817d6
out
wee_alloc_static_array_backend_size_bytes.txt
deps
save-analysis
libbyte_tools-818b0adb94c52bf7.json
wasm32-unknown-unknown
release
.fingerprint
ahash-8c58807f382e66f7
lib-ahash.json
aho-corasick-65bdad5ccd0afeba
lib-aho_corasick.json
base64-34b2a67c0a34dffa
lib-base64.json
block-buffer-bf48142245c11f83
lib-block-buffer.json
block-buffer-f457efd2e85208b0
lib-block-buffer.json
block-padding-bbe2fca682e29116
lib-block-padding.json
borsh-314c377aa7dc87a7
lib-borsh.json
bs58-dd9f69d8dfb8a015
lib-bs58.json
byte-tools-ba70efe336cbf88a
lib-byte-tools.json
byteorder-256b35d0289c82bc
run-build-script-build-script-build.json
byteorder-b7a830ad10f825bd
lib-byteorder.json
cfg-if-950d0a7dbc7a6161
lib-cfg-if.json
cfg-if-a6ff2e39031e9a8c
lib-cfg-if.json
digest-a6347735a6861627
lib-digest.json
digest-c33d73e7aa004107
lib-digest.json
generic-array-464121e6da6a9d8c
lib-generic_array.json
generic-array-9a03818d936e736e
lib-generic_array.json
generic-array-d5fdf0cdb6ed11c3
run-build-script-build-script-build.json
hashbrown-017e7c11a4d4410a
run-build-script-build-script-build.json
hashbrown-9a69fc5cdce926bc
lib-hashbrown.json
hashbrown-de04fb26ca91f33f
lib-hashbrown.json
hex-55f98987d3a8b6f5
lib-hex.json
indexmap-66d9b119537e9afd
run-build-script-build-script-build.json
indexmap-d07ba61bf7b8093f
lib-indexmap.json
itoa-e83d8606ef403f64
lib-itoa.json
keccak-91e8af1321717e4d
lib-keccak.json
lazy_static-4b8a8ba8d8020a3b
lib-lazy_static.json
memchr-10d81bf6dd5dc302
run-build-script-build-script-build.json
memchr-ef8ef45014915f50
lib-memchr.json
memory_units-9e7a51aa2631a9e3
lib-memory_units.json
near-contract-standards-fd7a44655666e3bc
lib-near-contract-standards.json
near-primitives-core-2b679de79d84b6c9
lib-near-primitives-core.json
near-runtime-utils-0aa5c5ee73bde69d
lib-near-runtime-utils.json
near-sdk-29aa5ea56280d09e
lib-near-sdk.json
near-vm-errors-8aa419fcdc82e1e2
lib-near-vm-errors.json
near-vm-logic-a2240379ed3c5fc2
lib-near-vm-logic.json
num-bigint-659c9f7d25ee8fac
lib-num-bigint.json
num-bigint-66a6a33249048872
run-build-script-build-script-build.json
num-integer-755c8bf6aeaf44cb
lib-num-integer.json
num-integer-9d794b6677d447bc
run-build-script-build-script-build.json
num-rational-023dd8e6f059369b
run-build-script-build-script-build.json
num-rational-d0961ed9614a47b6
lib-num-rational.json
num-traits-47138211810a1507
lib-num-traits.json
num-traits-e717aafc1d443448
run-build-script-build-script-build.json
opaque-debug-39ca4a564ad1994b
lib-opaque-debug.json
opaque-debug-c3d49065e25de639
lib-opaque-debug.json
regex-b0bdbcd82de4adfd
lib-regex.json
regex-syntax-3635f77f8ccf74e8
lib-regex-syntax.json
ryu-8f570de05576f075
lib-ryu.json
ryu-e0bac78f0ec97426
run-build-script-build-script-build.json
serde-0c62fc648c29eb78
run-build-script-build-script-build.json
serde-c0de21881b2a3cee
lib-serde.json
serde_json-ccde9ba036fd190f
lib-serde_json.json
serde_json-d5456916b2ef3fac
run-build-script-build-script-build.json
sha2-93e6ad570319f4fb
lib-sha2.json
sha3-28e391ffc9af1c2b
lib-sha3.json
token-swap-testnet-2c2ae977d75a1fee
lib-token-swap-testnet.json
typenum-0aa313a258ef4abd
lib-typenum.json
typenum-7d25526d05ad0689
run-build-script-build-script-main.json
wee_alloc-13c592cabc43f70b
run-build-script-build-script-build.json
wee_alloc-13ea6c116226e9d9
lib-wee_alloc.json
build
num-bigint-66a6a33249048872
out
radix_bases.rs
typenum-7d25526d05ad0689
out
consts.rs
op.rs
tests.rs
wee_alloc-13c592cabc43f70b
out
wee_alloc_static_array_backend_size_bytes.txt
copy-dev-account.js
defi
Cargo.toml
README.md
call.sh
compile.js
defi_call.sh
defi_deploy.sh
src
lib.rs
target
.rustc_info.json
debug
.fingerprint
Inflector-800d07129f6cdf34
lib-inflector.json
ahash-b65b262a71b5b48f
lib-ahash.json
aho-corasick-5234701034b12ee4
lib-aho_corasick.json
autocfg-d43d9e10379c8327
lib-autocfg.json
base64-5c7414cfb92860e8
lib-base64.json
block-buffer-48a0121b7a494a71
lib-block-buffer.json
block-buffer-4f3fb299dcc57797
lib-block-buffer.json
block-padding-24376a58a4f53824
lib-block-padding.json
borsh-38a358ea8d1b6330
lib-borsh.json
borsh-derive-2496b5a3da2de1d5
lib-borsh-derive.json
borsh-derive-internal-71f7df885f5fc9d1
lib-borsh-derive-internal.json
borsh-schema-derive-internal-d48151dcd18bd47d
lib-borsh-schema-derive-internal.json
bs58-6d6a6df200788597
lib-bs58.json
byte-tools-a0454fdb8e320603
lib-byte-tools.json
byteorder-477bf8c6d3a0e523
build-script-build-script-build.json
byteorder-541037c38e614382
run-build-script-build-script-build.json
byteorder-d836ba3e41654e24
lib-byteorder.json
cfg-if-38c8a3e888ecb06a
lib-cfg-if.json
cfg-if-e7a28af79b261e75
lib-cfg-if.json
convert_case-7aafe547bc5ceeeb
lib-convert_case.json
cpuid-bool-464b343952c951fe
lib-cpuid-bool.json
derive_more-5df7e3e03b033154
lib-derive_more.json
digest-8eb0f00a25be5de8
lib-digest.json
digest-a6306f4b8b561fd0
lib-digest.json
generic-array-3d570e92a726c457
run-build-script-build-script-build.json
generic-array-4e5a80a149b11b12
lib-generic_array.json
generic-array-b1f13dbac0488c4c
lib-generic_array.json
generic-array-db4e6ee7ce77adcf
build-script-build-script-build.json
hashbrown-1996868e232a969d
run-build-script-build-script-build.json
hashbrown-5b53035a525237f4
lib-hashbrown.json
hashbrown-67e4b559fbdc6052
build-script-build-script-build.json
hashbrown-d70458254ef89d14
lib-hashbrown.json
hex-26332ec05e0770db
lib-hex.json
indexmap-8272f3af80ca6d09
lib-indexmap.json
indexmap-c44c39c626da403f
build-script-build-script-build.json
indexmap-e9541724a67540a6
run-build-script-build-script-build.json
itoa-4365935becaf39d2
lib-itoa.json
keccak-ed6528dddc74fc69
lib-keccak.json
lazy_static-5c53d641eb010a81
lib-lazy_static.json
libc-5b4c4db6d7de7114
lib-libc.json
libc-aa9cacf7625af113
build-script-build-script-build.json
libc-cb24f294663ed32f
run-build-script-build-script-build.json
memchr-31f61a31cc94078a
build-script-build-script-build.json
memchr-529486d68603d187
run-build-script-build-script-build.json
memchr-9559fd627c3017a7
lib-memchr.json
memory_units-eac19ce3353440d4
lib-memory_units.json
near-contract-standards-33ceb1d5329bcbe2
lib-near-contract-standards.json
near-primitives-core-2729ea16ccb58af0
lib-near-primitives-core.json
near-rpc-error-core-b81897cee34ee445
lib-near-rpc-error-core.json
near-rpc-error-macro-77a0da42930561dd
lib-near-rpc-error-macro.json
near-runtime-utils-cb5598dbc5fa1ede
lib-near-runtime-utils.json
near-sdk-core-6d55c350445995df
lib-near-sdk-core.json
near-sdk-fa0c3f8fcbf68096
lib-near-sdk.json
near-sdk-macros-d07ac3678987a9c0
lib-near-sdk-macros.json
near-vm-errors-3f84c9b231654038
lib-near-vm-errors.json
near-vm-logic-06517b87cf53cd46
lib-near-vm-logic.json
num-bigint-30ed1efb7d4614f9
lib-num-bigint.json
num-bigint-738950308211bdc4
build-script-build-script-build.json
num-bigint-903fba555a0294e1
run-build-script-build-script-build.json
num-integer-008ef4a1adfea7f9
lib-num-integer.json
num-integer-729ca4e2d130a65c
run-build-script-build-script-build.json
num-integer-f15fbd4e37130eca
build-script-build-script-build.json
num-rational-0b703d2b243f42b3
lib-num-rational.json
num-rational-0c37f8418ca2ece8
build-script-build-script-build.json
num-rational-7717938b666bda74
run-build-script-build-script-build.json
num-traits-32ab1c2cdbda060a
run-build-script-build-script-build.json
num-traits-5741655b2ee87f30
build-script-build-script-build.json
num-traits-f5d93b6c3af2aac0
lib-num-traits.json
opaque-debug-45a15423c8ac1fee
lib-opaque-debug.json
opaque-debug-abc732d989c9d05a
lib-opaque-debug.json
proc-macro-crate-453199bbea6e7da8
lib-proc-macro-crate.json
proc-macro2-078cf92a0d8e67c9
run-build-script-build-script-build.json
proc-macro2-48023dd2ea5720b7
build-script-build-script-build.json
proc-macro2-540b6631119ce641
lib-proc-macro2.json
quote-2d316e7355c2bd28
lib-quote.json
regex-ff7b93346f2be0bb
lib-regex.json
regex-syntax-5c8121566f39070a
lib-regex-syntax.json
ryu-059aa1fbb24cd15e
lib-ryu.json
ryu-a3e82c1c02ae1955
build-script-build-script-build.json
ryu-f99552c5fa0b2a9b
run-build-script-build-script-build.json
serde-62c745322dbfa55f
run-build-script-build-script-build.json
serde-a6f085765be5773f
lib-serde.json
serde-d3806f79d3ce6de0
build-script-build-script-build.json
serde_derive-08a09e34df56f722
build-script-build-script-build.json
serde_derive-374b32841dff1025
lib-serde_derive.json
serde_derive-39f5282f60218653
run-build-script-build-script-build.json
serde_json-355599846872559a
lib-serde_json.json
serde_json-3be56b3afbb219d7
build-script-build-script-build.json
serde_json-89ecf85119327278
run-build-script-build-script-build.json
sha2-e9660514a60eeafa
lib-sha2.json
sha3-85766bf0f4d660d2
lib-sha3.json
syn-94cda2719c0e8bf9
lib-syn.json
syn-c450192d11660aa8
run-build-script-build-script-build.json
syn-db0672afc39b9b75
build-script-build-script-build.json
token-swap-testnet-2c2ae977d75a1fee
lib-token-swap-testnet.json
token-swap-testnet-9477e911e9424f17
test-lib-token-swap-testnet.json
toml-fbd4ae0f8223247c
lib-toml.json
typenum-2e8a23d2e72498ba
build-script-build-script-main.json
typenum-65efd23b6c1d4655
lib-typenum.json
typenum-f6d195b3ffce7585
run-build-script-build-script-main.json
unicode-xid-12009cf1a2496f6d
lib-unicode-xid.json
version_check-d6dca5d2eaa8c554
lib-version_check.json
wee_alloc-044c4ffd9be5f7bf
lib-wee_alloc.json
wee_alloc-5924e4acfa8ae6c6
build-script-build-script-build.json
wee_alloc-d3ee9f4f34f817d6
run-build-script-build-script-build.json
build
num-bigint-903fba555a0294e1
out
radix_bases.rs
typenum-f6d195b3ffce7585
out
consts.rs
op.rs
tests.rs
wee_alloc-d3ee9f4f34f817d6
out
wee_alloc_static_array_backend_size_bytes.txt
release
.fingerprint
Inflector-5749979cefab0aea
lib-inflector.json
autocfg-3f6504d403aebb13
lib-autocfg.json
borsh-derive-2834e9c66b9f6131
lib-borsh-derive.json
borsh-derive-internal-df0fa273e74794a8
lib-borsh-derive-internal.json
borsh-schema-derive-internal-4fc0ea913b7ea568
lib-borsh-schema-derive-internal.json
byteorder-0292db916d9dedf9
build-script-build-script-build.json
convert_case-d61cbb148bff0687
lib-convert_case.json
derive_more-8b21e87a2d6cf361
lib-derive_more.json
generic-array-e006a62c75373819
build-script-build-script-build.json
hashbrown-4cac487d76ede60f
run-build-script-build-script-build.json
hashbrown-63d2f7b81a8ab82e
build-script-build-script-build.json
hashbrown-8d331258e55ddbfb
lib-hashbrown.json
indexmap-30475067e5920015
lib-indexmap.json
indexmap-89b15de24e86a31b
run-build-script-build-script-build.json
indexmap-cabe69f1a7e1fdc9
build-script-build-script-build.json
itoa-9f4fb4841fb2e1c0
lib-itoa.json
memchr-569c819b7482fc3f
build-script-build-script-build.json
near-rpc-error-core-f264d2494024f924
lib-near-rpc-error-core.json
near-rpc-error-macro-90b8150f0c7f470f
lib-near-rpc-error-macro.json
near-sdk-core-032f2d8a340d3933
lib-near-sdk-core.json
near-sdk-macros-e31f95ac88d52b90
lib-near-sdk-macros.json
num-bigint-40697c0e877261cb
build-script-build-script-build.json
num-integer-2eb5029502a0bde8
build-script-build-script-build.json
num-rational-5ee415194a7efd8a
build-script-build-script-build.json
num-traits-72a14a33045ac8d1
build-script-build-script-build.json
proc-macro-crate-1bfc3f79ebbb1be2
lib-proc-macro-crate.json
proc-macro2-1a1dfdb1c780706c
lib-proc-macro2.json
proc-macro2-4cb02ba5cc702bad
build-script-build-script-build.json
proc-macro2-bb481a784045799c
run-build-script-build-script-build.json
quote-b5543ec51d1d6855
lib-quote.json
ryu-226f1d8f7effe500
lib-ryu.json
ryu-33d63cf8baf83297
run-build-script-build-script-build.json
ryu-bd6fd6ed98668f10
build-script-build-script-build.json
serde-3962d7e81b55f82d
lib-serde.json
serde-aa28080fc5443ad8
run-build-script-build-script-build.json
serde-e1d69ac1029f46cf
build-script-build-script-build.json
serde_derive-1d4d1dbbd1b68d10
lib-serde_derive.json
serde_derive-a63028e0f4689ad6
build-script-build-script-build.json
serde_derive-b9d6662241bb17fb
run-build-script-build-script-build.json
serde_json-1ab35cb35cd7c7a4
lib-serde_json.json
serde_json-2014bf7ee871c82d
build-script-build-script-build.json
serde_json-e5f32c081008a946
run-build-script-build-script-build.json
syn-17dbd3ecff78966f
build-script-build-script-build.json
syn-33b2077f21d43737
run-build-script-build-script-build.json
syn-775142f13c5d1fdd
lib-syn.json
toml-a8d2ca19cbed6504
lib-toml.json
typenum-4f0cd91bdd29748b
build-script-build-script-main.json
unicode-xid-e4e736734ff8b42a
lib-unicode-xid.json
version_check-c1ef40f964686aae
lib-version_check.json
wee_alloc-0a13e1daccaecc5c
build-script-build-script-build.json
rls
.rustc_info.json
debug
.fingerprint
Inflector-800d07129f6cdf34
lib-inflector.json
ahash-bcc8848a7f2ae332
lib-ahash.json
aho-corasick-1cbef844a76b5d3c
lib-aho_corasick.json
autocfg-d43d9e10379c8327
lib-autocfg.json
base64-06135271d248c171
lib-base64.json
block-buffer-7b4189d02841db12
lib-block-buffer.json
block-buffer-a936c44369c6687a
lib-block-buffer.json
block-padding-38cd3b2c66637c8d
lib-block-padding.json
borsh-41d6d25f6342d922
lib-borsh.json
borsh-derive-2496b5a3da2de1d5
lib-borsh-derive.json
borsh-derive-internal-71f7df885f5fc9d1
lib-borsh-derive-internal.json
borsh-schema-derive-internal-d48151dcd18bd47d
lib-borsh-schema-derive-internal.json
bs58-a151b08edefd8abf
lib-bs58.json
byte-tools-818b0adb94c52bf7
lib-byte-tools.json
byteorder-461198e3a3e1689c
lib-byteorder.json
byteorder-477bf8c6d3a0e523
build-script-build-script-build.json
byteorder-541037c38e614382
run-build-script-build-script-build.json
cfg-if-20b9f5fb82bebd1b
lib-cfg-if.json
cfg-if-810dd9fbe1e28608
lib-cfg-if.json
convert_case-7aafe547bc5ceeeb
lib-convert_case.json
cpuid-bool-ad75c1c2944cc795
lib-cpuid-bool.json
derive_more-5df7e3e03b033154
lib-derive_more.json
digest-9dcf0aa3154dc7bb
lib-digest.json
digest-ab0611971c63a183
lib-digest.json
generic-array-1dbbaa2e2fa530e9
lib-generic_array.json
generic-array-3d570e92a726c457
run-build-script-build-script-build.json
generic-array-b3f8cd377f843cf3
lib-generic_array.json
generic-array-db4e6ee7ce77adcf
build-script-build-script-build.json
greeter-00ca0aea9c5637fa
test-lib-greeter.json
greeter-e1c5515f6f515563
lib-greeter.json
hashbrown-1996868e232a969d
run-build-script-build-script-build.json
hashbrown-1df96b88cb790594
lib-hashbrown.json
hashbrown-34c060aeea2a27f8
lib-hashbrown.json
hashbrown-5b53035a525237f4
lib-hashbrown.json
hashbrown-67e4b559fbdc6052
build-script-build-script-build.json
hex-4e132399b961d086
lib-hex.json
indexmap-25c44c019f255a34
lib-indexmap.json
indexmap-8272f3af80ca6d09
lib-indexmap.json
indexmap-c44c39c626da403f
build-script-build-script-build.json
indexmap-e9541724a67540a6
run-build-script-build-script-build.json
itoa-3a4185a1241cab3f
lib-itoa.json
itoa-4365935becaf39d2
lib-itoa.json
keccak-0308e12d974eb640
lib-keccak.json
lazy_static-acd7d23482fe8b54
lib-lazy_static.json
libc-a4a086f32dc5095c
lib-libc.json
libc-aa9cacf7625af113
build-script-build-script-build.json
libc-cb24f294663ed32f
run-build-script-build-script-build.json
memchr-31f61a31cc94078a
build-script-build-script-build.json
memchr-529486d68603d187
run-build-script-build-script-build.json
memchr-a54d4b647f438279
lib-memchr.json
memory_units-78e37e243757af92
lib-memory_units.json
near-contract-standards-7cac6b9ffeb58c8c
lib-near-contract-standards.json
near-primitives-core-10b3717619638d24
lib-near-primitives-core.json
near-rpc-error-core-b81897cee34ee445
lib-near-rpc-error-core.json
near-rpc-error-macro-77a0da42930561dd
lib-near-rpc-error-macro.json
near-runtime-utils-1e65fbd610bd7fff
lib-near-runtime-utils.json
near-sdk-77a648afbdb7804c
lib-near-sdk.json
near-sdk-core-6d55c350445995df
lib-near-sdk-core.json
near-sdk-macros-d07ac3678987a9c0
lib-near-sdk-macros.json
near-vm-errors-03c19ad4a73a9441
lib-near-vm-errors.json
near-vm-logic-c7bd82123138e73b
lib-near-vm-logic.json
num-bigint-738950308211bdc4
build-script-build-script-build.json
num-bigint-903fba555a0294e1
run-build-script-build-script-build.json
num-bigint-bf5e2b767df1c977
lib-num-bigint.json
num-integer-374bc874abd03eea
lib-num-integer.json
num-integer-729ca4e2d130a65c
run-build-script-build-script-build.json
num-integer-f15fbd4e37130eca
build-script-build-script-build.json
num-rational-0000a14962554f15
lib-num-rational.json
num-rational-0c37f8418ca2ece8
build-script-build-script-build.json
num-rational-7717938b666bda74
run-build-script-build-script-build.json
num-traits-32ab1c2cdbda060a
run-build-script-build-script-build.json
num-traits-5741655b2ee87f30
build-script-build-script-build.json
num-traits-a1e2ecf636bdf134
lib-num-traits.json
opaque-debug-dbbd94c139b791ac
lib-opaque-debug.json
opaque-debug-e348ac3040cb1f3b
lib-opaque-debug.json
proc-macro-crate-453199bbea6e7da8
lib-proc-macro-crate.json
proc-macro2-078cf92a0d8e67c9
run-build-script-build-script-build.json
proc-macro2-48023dd2ea5720b7
build-script-build-script-build.json
proc-macro2-540b6631119ce641
lib-proc-macro2.json
quote-2d316e7355c2bd28
lib-quote.json
regex-6792f3d5f7a30912
lib-regex.json
regex-syntax-283170c95ddd4231
lib-regex-syntax.json
ryu-059aa1fbb24cd15e
lib-ryu.json
ryu-0bcf425490ac7c5b
lib-ryu.json
ryu-a3e82c1c02ae1955
build-script-build-script-build.json
ryu-f99552c5fa0b2a9b
run-build-script-build-script-build.json
serde-62c745322dbfa55f
run-build-script-build-script-build.json
serde-a6f085765be5773f
lib-serde.json
serde-d3806f79d3ce6de0
build-script-build-script-build.json
serde-fd8a30d646d2c3c7
lib-serde.json
serde_derive-08a09e34df56f722
build-script-build-script-build.json
serde_derive-374b32841dff1025
lib-serde_derive.json
serde_derive-39f5282f60218653
run-build-script-build-script-build.json
serde_json-000bb3d9cc2942b5
lib-serde_json.json
serde_json-355599846872559a
lib-serde_json.json
serde_json-3be56b3afbb219d7
build-script-build-script-build.json
serde_json-89ecf85119327278
run-build-script-build-script-build.json
sha2-3b0cc4e9779a2db1
lib-sha2.json
sha3-4337f43ee7d343a4
lib-sha3.json
syn-94cda2719c0e8bf9
lib-syn.json
syn-c450192d11660aa8
run-build-script-build-script-build.json
syn-db0672afc39b9b75
build-script-build-script-build.json
token-swap-testnet-09d616a24631caf2
lib-token-swap-testnet.json
token-swap-testnet-2386622a0caa8337
test-lib-token-swap-testnet.json
toml-fbd4ae0f8223247c
lib-toml.json
typenum-2e8a23d2e72498ba
build-script-build-script-main.json
typenum-998188894a333e6e
lib-typenum.json
typenum-f6d195b3ffce7585
run-build-script-build-script-main.json
unicode-xid-12009cf1a2496f6d
lib-unicode-xid.json
version_check-d6dca5d2eaa8c554
lib-version_check.json
wee_alloc-5924e4acfa8ae6c6
build-script-build-script-build.json
wee_alloc-c1d7f65472a26d1f
lib-wee_alloc.json
wee_alloc-d3ee9f4f34f817d6
run-build-script-build-script-build.json
build
byteorder-477bf8c6d3a0e523
save-analysis
build_script_build-477bf8c6d3a0e523.json
generic-array-db4e6ee7ce77adcf
save-analysis
build_script_build-db4e6ee7ce77adcf.json
hashbrown-67e4b559fbdc6052
save-analysis
build_script_build-67e4b559fbdc6052.json
indexmap-c44c39c626da403f
save-analysis
build_script_build-c44c39c626da403f.json
libc-aa9cacf7625af113
save-analysis
build_script_build-aa9cacf7625af113.json
memchr-31f61a31cc94078a
save-analysis
build_script_build-31f61a31cc94078a.json
num-bigint-738950308211bdc4
save-analysis
build_script_build-738950308211bdc4.json
num-bigint-903fba555a0294e1
out
radix_bases.rs
num-integer-f15fbd4e37130eca
save-analysis
build_script_build-f15fbd4e37130eca.json
num-rational-0c37f8418ca2ece8
save-analysis
build_script_build-0c37f8418ca2ece8.json
num-traits-5741655b2ee87f30
save-analysis
build_script_build-5741655b2ee87f30.json
proc-macro2-48023dd2ea5720b7
save-analysis
build_script_build-48023dd2ea5720b7.json
ryu-a3e82c1c02ae1955
save-analysis
build_script_build-a3e82c1c02ae1955.json
serde-d3806f79d3ce6de0
save-analysis
build_script_build-d3806f79d3ce6de0.json
serde_derive-08a09e34df56f722
save-analysis
build_script_build-08a09e34df56f722.json
serde_json-3be56b3afbb219d7
save-analysis
build_script_build-3be56b3afbb219d7.json
syn-db0672afc39b9b75
save-analysis
build_script_build-db0672afc39b9b75.json
typenum-2e8a23d2e72498ba
save-analysis
build_script_main-2e8a23d2e72498ba.json
typenum-f6d195b3ffce7585
out
consts.rs
op.rs
tests.rs
wee_alloc-5924e4acfa8ae6c6
save-analysis
build_script_build-5924e4acfa8ae6c6.json
wee_alloc-d3ee9f4f34f817d6
out
wee_alloc_static_array_backend_size_bytes.txt
deps
save-analysis
libbyte_tools-818b0adb94c52bf7.json
libtoken_swap_testnet-09d616a24631caf2.json
token_swap_testnet-2386622a0caa8337.json
wasm32-unknown-unknown
release
.fingerprint
ahash-8c58807f382e66f7
lib-ahash.json
aho-corasick-65bdad5ccd0afeba
lib-aho_corasick.json
base64-34b2a67c0a34dffa
lib-base64.json
block-buffer-bf48142245c11f83
lib-block-buffer.json
block-buffer-f457efd2e85208b0
lib-block-buffer.json
block-padding-bbe2fca682e29116
lib-block-padding.json
borsh-314c377aa7dc87a7
lib-borsh.json
bs58-dd9f69d8dfb8a015
lib-bs58.json
byte-tools-ba70efe336cbf88a
lib-byte-tools.json
byteorder-256b35d0289c82bc
run-build-script-build-script-build.json
byteorder-b7a830ad10f825bd
lib-byteorder.json
cfg-if-950d0a7dbc7a6161
lib-cfg-if.json
cfg-if-a6ff2e39031e9a8c
lib-cfg-if.json
digest-a6347735a6861627
lib-digest.json
digest-c33d73e7aa004107
lib-digest.json
generic-array-464121e6da6a9d8c
lib-generic_array.json
generic-array-9a03818d936e736e
lib-generic_array.json
generic-array-d5fdf0cdb6ed11c3
run-build-script-build-script-build.json
hashbrown-017e7c11a4d4410a
run-build-script-build-script-build.json
hashbrown-9a69fc5cdce926bc
lib-hashbrown.json
hashbrown-de04fb26ca91f33f
lib-hashbrown.json
hex-55f98987d3a8b6f5
lib-hex.json
indexmap-66d9b119537e9afd
run-build-script-build-script-build.json
indexmap-d07ba61bf7b8093f
lib-indexmap.json
itoa-e83d8606ef403f64
lib-itoa.json
keccak-91e8af1321717e4d
lib-keccak.json
lazy_static-4b8a8ba8d8020a3b
lib-lazy_static.json
memchr-10d81bf6dd5dc302
run-build-script-build-script-build.json
memchr-ef8ef45014915f50
lib-memchr.json
memory_units-9e7a51aa2631a9e3
lib-memory_units.json
near-contract-standards-fd7a44655666e3bc
lib-near-contract-standards.json
near-primitives-core-2b679de79d84b6c9
lib-near-primitives-core.json
near-runtime-utils-0aa5c5ee73bde69d
lib-near-runtime-utils.json
near-sdk-29aa5ea56280d09e
lib-near-sdk.json
near-vm-errors-8aa419fcdc82e1e2
lib-near-vm-errors.json
near-vm-logic-a2240379ed3c5fc2
lib-near-vm-logic.json
num-bigint-659c9f7d25ee8fac
lib-num-bigint.json
num-bigint-66a6a33249048872
run-build-script-build-script-build.json
num-integer-755c8bf6aeaf44cb
lib-num-integer.json
num-integer-9d794b6677d447bc
run-build-script-build-script-build.json
num-rational-023dd8e6f059369b
run-build-script-build-script-build.json
num-rational-d0961ed9614a47b6
lib-num-rational.json
num-traits-47138211810a1507
lib-num-traits.json
num-traits-e717aafc1d443448
run-build-script-build-script-build.json
opaque-debug-39ca4a564ad1994b
lib-opaque-debug.json
opaque-debug-c3d49065e25de639
lib-opaque-debug.json
regex-b0bdbcd82de4adfd
lib-regex.json
regex-syntax-3635f77f8ccf74e8
lib-regex-syntax.json
ryu-8f570de05576f075
lib-ryu.json
ryu-e0bac78f0ec97426
run-build-script-build-script-build.json
serde-0c62fc648c29eb78
run-build-script-build-script-build.json
serde-c0de21881b2a3cee
lib-serde.json
serde_json-ccde9ba036fd190f
lib-serde_json.json
serde_json-d5456916b2ef3fac
run-build-script-build-script-build.json
sha2-93e6ad570319f4fb
lib-sha2.json
sha3-28e391ffc9af1c2b
lib-sha3.json
token-swap-testnet-2c2ae977d75a1fee
lib-token-swap-testnet.json
typenum-0aa313a258ef4abd
lib-typenum.json
typenum-7d25526d05ad0689
run-build-script-build-script-main.json
wee_alloc-13c592cabc43f70b
run-build-script-build-script-build.json
wee_alloc-13ea6c116226e9d9
lib-wee_alloc.json
build
num-bigint-66a6a33249048872
out
radix_bases.rs
typenum-7d25526d05ad0689
out
consts.rs
op.rs
tests.rs
wee_alloc-13c592cabc43f70b
out
wee_alloc_static_array_backend_size_bytes.txt
jest.config.js
package.json
src
assets
logo-black.svg
logo-white.svg
config.js
global.css
main.js
utils.js
tests
unit
Notification.spec.js
SignedIn.spec.js
SignedOut.spec.js
| nep141transfer 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
nep141-payment
==================
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 `nep141-payment.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `nep141-payment.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 nep141-payment.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 || 'nep141-payment.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
# for_nep141
nep141transfer 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
|
leomanza_trust-me | README.md
contract
as-pect.config.js
asconfig.json
assembly
__tests__
as-pect.d.ts
main.spec.ts
as_types.d.ts
index.ts
model.ts
tsconfig.json
compile.js
package-lock.json
package.json
neardev
dev-account.env
shared-test-staging
test.near.json
shared-test
test.near.json
package.json
| # ๐ง trust-me
> Proyecto realizado para el NCD Bootcamp NEAR Hispano.
# trust-me es un servicio de manejo de confianza de pares en aplicaciones de negocios p2p desentralizados.
En toda operaciรณn entre pares en redes decentralizadas y anรณnimas, ya sea para una operaciรณn de transferencia de tokens, o bien en donde un recurso (tangible o no intangible) es utilizado como parte de una transacciรณn, es necesario establecer una relaciรณn de confianza entre las partes (aka pares o peers).
Con TrustMe, intentamos quebrar esa barrera brindando un servicio de registro de reputaciรณn de miembros de una comunidad (community-based), o bien una red (blockchain-based).
# ๐ญ trust-me permitirรก realizar las siguientes operaciones
* _consultar el nivel de confianza_ de un miembro en la comunidad antes de realizar una transacciรณn.
* _registrar la confianza_ de un miembro luego de realizar una transacciรณn.
* _registrar la desconfianza_ de un miembro luego de realizar una transacciรณn.
* _consultar los confiantes_ de un miembro de la comunidad.
* _consultar los confidentes_ de un miembro en la comunidad.
* _consultar mis confiantes_ dentro de la comunidad.
* _consultar mis confidentes_ dentro de la comunidad.
* consultar un ranking de miembros con mayor confianza.
* consultar un ranking de miembros con menos confianza.
Cada miembro dentro de la comunidad se identifica con su _NEAR account ID_
# ๐ Prerequisitos
1. node.js >=12 instalado (node.js>=14 preferentemente) (https://nodejs.org)
2. yarn instalado
```bash
npm install --global yarn
```
3. instalar dependencias
```bash
yarn install --frozen-lockfile
```
4. crear una cuenta de NEAR en [testnet](https://docs.near.org/docs/develop/basics/create-account#creating-a-testnet-account)
5. instalar NEAR CLI
```bash
yarn install --global near-cli
```
6. autorizar app para dar acceso a la cuenta de NEAR
```bash
near login
```
๐ Clonar el Repositorio
```bash
git clone https://github.com/leomanza/trust-me.git
cd trust-me
```
๐ instalar y compilar el contrato
```bash
yarn install
yarn build:contract:debug
```
๐ Deployar el contrato
```bash
yarn dev:deploy:contract
```
๐ Correr comandos
Una vez deployado el contrato, usaremos el Account Id devuelto por la operacion para ejecutar los comandos, que serรก el account Id del contrato [serรก utilizado como CONTRACT_ACCOUNT_ID en los ejemplos de comandos]
Utilizaremos ACCOUNT_ID para identificar el account Id que utilizamos para autorizar la app.
### Registrar confianza en un usuario
```bash
near call CONTRACT_ACCOUNT_ID confiar '{"accountId": "juan.testnet", "comment":"todo perfecto", "relatedTx":"6ZSbdHZFkKGxnrYiY9fyym2uShbJYSLmzPSizJfX5Eee"}' --account-id ACCOUNT_ID
```
### Registrar desconfianza en un usuario
```bash
near call CONTRACT_ACCOUNT_ID descofiar '{"accountId": "juan.testnet", "comment":"vendedor poco confiable", "relatedTx":"6ZSbdHZFkKGxnrYiY9fyym2uShbJYSLmzPSizJfX5Eee"}' --account-id ACCOUNT_ID
```
### Obtener nivel de confianza de un usuario
```bash
near view CONTRACT_ACCOUNT_ID getConfianza '{"accountId": "juan.testnet"}'
```
### Obtener confiantes de un usuario
```bash
near call CONTRACT_ACCOUNT_ID getConfiantes '{"accountId":"juan.testnet"}' --accountId ACCOUNT_ID
```
### Obtener confidentes de un usuario
```bash
near call CONTRACT_ACCOUNT_ID getConfidentes '{"accountId":"juan.testnet"}' --accountId ACCOUNT_ID
```
### Obtener mis confiantes
```bash
near call CONTRACT_ACCOUNT_ID getMisConfiantes '{}' --accountId ACCOUNT_ID
```
### Obtener mis confidentes
```bash
near call CONTRACT_ACCOUNT_ID getMisConfidentes '{}' --accountId ACCOUNT_ID
```
# Caso de uso: Confianza de vendedores y compradores de una plataforma de e-commerce.
Para este caso de uso pensamos en una UI sencilla, la cual tendrรญa una mayor funcionalidad al momento de realizar conexiones con Amazon, Ebay, Mercado libre y mรกs. Las acciones que podemos realizar en esta UI son:
* _consultar el nivel de confianza_ de un miembro en la comunidad antes de realizar una transacciรณn.
* Ver a los mejores vendedores por plataforma.
* Crear una cuenta usando tu cuenta de mainet.
* Iniciar sesiรณn usando tu cuenta de mainet y tu contraseรฑa.
* Ver el perfรญl de los vendedores/compradores donde podremos ver:
* Cuanta gente confรญa o desconfรญa en el/ella.
* Su cantidad de ventas/compras.
* Los comentarios de otros usuarios sobre esta persona.
* Poder evaluar a este usuarios.
* Buscar a los usuarios por su id de mainet.
* Evaluar a los demรกs usuarios, usando su id, el nรบmero de transacciรณn de venta/compra, evaluarlo como vendedor/comprador y comentarios sobre el usuario.
<br />
Estos diseรฑos se pueden encontrar y navegar por ellos aquรญ: https://marvelapp.com/prototype/7541b96/screen/81825604
# NEAR NCD Bootcamp - Level 2 :: 1-day course on building full stack dApps on NEAR
This repository contains an implementation of the front-end and NEAR protocolor interaction via RPC API.
The smart contract to interact is the one implemented on the NCD Bootcamp - Level 1. [TrustMe Smart Contract](https://github.com/leomanza/trust-me).
**Prerequisites**
In order to interact with the smart contract, we need it deployed. Once you have it, copy the smart contract account Id that we are going to use on the daap.
## Environment Setup
### Local Environment Setup
1. clone this repo locally
```bash
git clone https://github.com/leomanza/trust-me-frontend.git
```
2. install dependencies
```bash
yarn
```
4. open next.config.js and set the CONTRACT_ID env variable with the trus-me smart contract account id deployed on prerequisites.
```json
module.exports = {
reactStrictMode: true,
env: {
CONTRACT_ID: 'dev-839242103921-12345'
}
}
````
3. run the development server
```bash
npm run dev
# or
yarn dev
```
### DEV Environment Setup
1. clone this repo locally (skip if already done on local env setup)
```bash
git clone ...
```
2. install dependencies (skip if already done on local env setup)
```bash
yarn
```
3. deploy
```bash
vercel
```
4. add CONTRACT_ID env variable
```bash
vercel env add NEXT_PUBLIC_CONTRACT_ID
```
copy/paste contract account id
### DEV Production Setup
1. clone this repo locally (skip if already done on local/dev env setup)
```bash
git clone ...
```
2. install dependencies (skip if already done on local/dev env setup)
```bash
yarn
```
3. deploy
```bash
vercel --prod
```
4. add CONTRACT_ID env variable (skip if already done on dev env setup)
```bash
vercel env add NEXT_PUBLIC_CONTRACT_ID
```
copy/paste contract account id
|
nearuaguild_web4-profile-contracts | Readme.md
factory
Cargo.toml
LICENSE.txt
Readme.md
build.sh
src
lib.rs
utils.rs
page
LICENSE.txt
Readme.md
as-pect.config.js
asconfig.json
assembly
as_types.d.ts
index.ts
profile.ts
tsconfig.json
web4.ts
package.json
public
css
styles.css
images
avatar.svg
icons
amazon.svg
apple-music-white.svg
apple-music.svg
apple-podcasts-white.svg
apple-podcasts.svg
appstore.svg
bandcamp.svg
blog.svg
cashapp_btc.svg
cashapp_dollar.svg
cashapp_pound.svg
clubhouse.svg
coffee.svg
dev_to.svg
discord.svg
email.svg
email_alt.svg
etsy.svg
facebook.svg
figma.svg
flickr.svg
github.svg
gitlab.svg
goodreads.svg
google-podcasts.svg
google_scholar.svg
hashnode.svg
instagram.svg
kickstarter.svg
kit.svg
ko-fi.svg
letterboxd.svg
linkedin.svg
littlelink.svg
mastodon.svg
medium.svg
messenger.svg
notion.svg
onlyfans.svg
patreon.svg
paypal.svg
pinterest.svg
playstore.svg
producthunt.svg
redbubble.svg
reddit.svg
signal.svg
skoob.svg
snapchat.svg
soundcloud.svg
spotify-green.svg
spotify.svg
steam.svg
strava.svg
substack.svg
telegram.svg
threema.svg
tiktok.svg
trello.svg
tumblr.svg
twitch.svg
twitter.svg
unsplash.svg
untappd.svg
venmo.svg
vimeo.svg
vrchat.svg
web.svg
whatsapp.svg
wordpress.svg
xing.svg
youtube-music.svg
youtube.svg
| |
Learn-NEAR_NCD--heritage | README.md
as-pect.config.js
asconfig.json
package.json
scripts
1.init.sh
2.run.sh
README.md
src
as-pect.d.ts
as_types.d.ts
heritage
__tests__
README.md
index.unit.spec.ts
asconfig.json
assembly
index.ts
models.ts
tsconfig.json
utils.ts
| ## Setting up your terminal
The scripts in this folder support a simple demonstration of the contract.
It uses the following setup:
```txt
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ โ
โ โ โ
โ โ โ
โ โ โ
โ โ โ
โ โ โ
โ โ โ
โ A โ B โ
โ โ โ
โ โ โ
โ โ โ
โ โ โ
โ โ โ
โ โ โ
โ โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
```
### Terminal **A**
*This window is used to compile, deploy and control the contract*
- Environment
```sh
export CONTRACT= # depends on deployment
export OWNER= # any account you control
# for example
# export CONTRACT=dev-1615190770786-2702449
# export OWNER=sherif.testnet
```
- Commands
```sh
1.init.sh # cleanup, compile and deploy contract
2.run.sh # call methods on the deployed contract
```
### Terminal **B**
*This window is used to render the contract account storage*
- Environment
```sh
export CONTRACT= # depends on deployment
# for example
# export CONTRACT=dev-1615190770786-2702449
```
- Commands
```sh
# monitor contract storage using near-account-utils
# https://github.com/near-examples/near-account-utils
watch -d -n 1 yarn storage $CONTRACT
```
---
## OS Support
### Linux
- The `watch` command is supported natively on Linux
- To learn more about any of these shell commands take a look at [explainshell.com](https://explainshell.com)
### MacOS
- Consider `brew info visionmedia-watch` (or `brew install watch`)
### Windows
- Consider this article: [What is the Windows analog of the Linux watch command?](https://superuser.com/questions/191063/what-is-the-windows-analog-of-the-linux-watch-command#191068)
## Unit tests
Unit tests can be run from the top level folder using the following command:
```
yarn test:unit
```
### Tests for Contract in `index.unit.spec.ts`
```
[Describe]: Staked class
[Success]: โ should initialize correctly
[Success]: โ owner should be set correctly
[Success]: โ balance should be initialized correctly
[Describe]: Deposit funds
[Success]: โ Can't deposit less than 0 funds
[Success]: โ Can deposit funds
[Success]: โ Can deposit funds and these funds are deposited
[Success]: โ Total fundings in the contract should be ONE NEAR
[Success]: โ Total fundings in the contract should be TWO NEAR
[Success]: โ Alice deposit should be ONE NEAR
[Success]: โ Alice deposit should be ONE NEAR and Bob deposit should be ONE NEAR and total funds should be TWO NEAR
[Describe]: WithDraw funds
[Success]: โ Alice cannot withdraw funds during the locked time
[Success]: โ Alice can withdraw funds after the locked time
[Success]: โ Contract amount should be 0 NEAR after withdraw
[Success]: โ Alice cannot withdraw funds two times
[Success]: โ Bob cannot withdraw funds
[File]: src/heritage/__tests__/index.unit.spec.ts
[Groups]: 4 pass, 4 total
[Result]: โ PASS
[Snapshot]: 0 total, 0 added, 0 removed, 0 different
[Summary]: 15 pass, 0 fail, 15 total
[Time]: 223.96ms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[Result]: โ PASS
[Files]: 1 total
[Groups]: 4 count, 4 pass
[Tests]: 15 pass, 0 fail, 15 total
[Time]: 16122.843ms
```
# Near-heritage: The spicy hello word
This repository includes a complete project structure for AssemblyScript contracts targeting the NEAR platform. This is an spicy "hello world" in assemblyscript for new developers.
The goal of this project is to have a smart contract where a user adds NEARs to the smart contract for a limit of time and having the restriction that only the selected wallet can unlock these NEARs.
The example here is very basic. It's a simple contract demonstrating the following concepts:
- a single contract
- basic usage of timestamps
- basic contract storage
- basic usage of VMContext in the unit tests
The goal of this repository is to make it as easy as possible to get started writing unit and simulation tests for AssemblyScript contracts built to work with NEAR Protocol.
## Usage
### Getting started
1. clone this repo to a local folder
2. run `yarn`
3. run `yarn test`
### Top-level `yarn` commands
- run `yarn test` to run all tests
- (!) be sure to run `yarn build:release` at least once before:
- run `yarn test:unit` to run only unit tests
- run `yarn test:simulate` to run only simulation tests
- run `yarn build` to quickly verify build status
- run `yarn clean` to clean up build folder
### Other documentation
- Sample contract and test documentation
- see `/src/heritage/README` for contract interface
- see `/src/heritage/__tests__/README` for Sample unit testing details
- Sample contract simulation tests
- see `/simulation/README` for simulation testing
## The file system
Please note that boilerplate project configuration files have been ommitted from the following lists for simplicity.
### Contracts and Unit Tests
```txt
src
โโโ heritage <-- heritage contract
โย ย โโโ README.md
โย ย โโโ __tests__
โย ย โย ย โโโ README.md
โย ย โย ย โโโ index.unit.spec.ts
โย ย โโโ assembly
โย ย โโโ index.ts
โ โโโ models.ts
โโโ utils.ts <-- shared contract code
```
### Helper Scripts
```txt
scripts
โโโ 1.init.sh
โโโ 2.run.sh
โโโ README.md <-- instructions
```
|
On0n0k1_Tutorial_NEAR_Rust | EN
README.md
lesson_1_contract
Cargo.toml
Readme.md
src
lib.rs
lesson_2_ownership
Cargo.toml
Readme.md
src
lib.rs
lesson_3_structs
Cargo.toml
Readme.md
src
lib.rs
lesson_4_modules
Cargo.toml
Readme.md
src
a_module
mod.rs
specific_module.rs
another_module.rs
lib.rs
yet_another_module.rs
yet_another_module
internal_module.rs
internal_module
a_deep_module.rs
tests
another.rs
common
mod.rs
contract.rs
lesson_5_macro_usage
Cargo.toml
Readme.md
src
lib.rs
lesson_6_enums
Cargo.toml
Readme.md
lesson_6_1_simple
Cargo.toml
Readme.md
src
lib.rs
model.rs
lesson_6_2_thermometer
Cargo.toml
Readme.md
src
contract.rs
entry
mod.rs
lib.rs
schedule
date.rs
date
day.rs
month.rs
year.rs
mod.rs
time.rs
time
hour.rs
minute.rs
second.rs
temperature
mod.rs
temp_format.rs
utils.rs
lesson_6_3_game_score
Cargo.toml
Readme.md
src
lib.rs
model
chapter
mod.rs
reward.rs
character
class.rs
mod.rs
stats.rs
errors.rs
mod.rs
player
mod.rs
view.rs
score
high_score.rs
mod.rs
ranking.rs
storage.rs
static
Readme.md
tutorials
cargo.md
nearcli.md
rust.md
setup-nearcli.md
ES
README.md
lesson_1_contract
Cargo.toml
Readme.md
src
lib.rs
lesson_2_ownership
Cargo.toml
Readme.md
src
lib.rs
lesson_3_structs
Cargo.toml
Readme.md
src
lib.rs
lesson_4_modules
Cargo.toml
Readme.md
src
a_module
mod.rs
specific_module.rs
another_module.rs
lib.rs
yet_another_module.rs
yet_another_module
internal_module.rs
internal_module
a_deep_module.rs
tests
another.rs
common
mod.rs
contract.rs
lesson_5_macro_usage
Cargo.toml
Readme.md
src
lib.rs
lesson_6_enums
Cargo.toml
Readme.md
lesson_6_1_simple
Cargo.toml
Readme.md
src
lib.rs
model.rs
static
Readme.md
tutorials
cargo.md
nearcli.md
rust.md
setup-nearcli.md
PT-BR
README.md
lesson_1_contract
Cargo.toml
Readme.md
src
lib.rs
lesson_2_ownership
Cargo.toml
Readme.md
src
lib.rs
lesson_3_structs
Cargo.toml
Readme.md
src
lib.rs
lesson_4_modules
Cargo.toml
Readme.md
src
a_module
mod.rs
specific_module.rs
another_module.rs
lib.rs
yet_another_module.rs
yet_another_module
internal_module.rs
internal_module
a_deep_module.rs
tests
another.rs
common
mod.rs
contract.rs
lesson_5_macro_usage
Cargo.toml
Readme.md
src
lib.rs
lesson_6_enums
Cargo.toml
Readme.md
lesson_6_1_simple
Cargo.toml
Readme.md
src
lib.rs
model.rs
lesson_6_2_thermometer
Cargo.toml
Readme.md
src
contract.rs
entry
mod.rs
lib.rs
schedule
date.rs
date
day.rs
month.rs
year.rs
mod.rs
time.rs
time
hour.rs
minute.rs
second.rs
temperature
mod.rs
temp_format.rs
utils.rs
lesson_6_3_game_score
Cargo.toml
Readme.md
src
lib.rs
model
chapter
mod.rs
reward.rs
character
class.rs
mod.rs
stats.rs
errors.rs
mod.rs
player
mod.rs
view.rs
score
high_score.rs
mod.rs
ranking.rs
storage.rs
static
Readme.md
tutorials
cargo.md
nearcli.md
rust.md
setup-nearcli.md
Readme.md
| # Tutorial_NEAR_Rust
[voltar](https://github.com/On0n0k1/Tutorial_NEAR_Rust/tree/main/)
Tutorial em etapas para desenvolvimento de contratos inteligentes em rust. Neste conjunto de tutoriais serรฃo discutidos todas as principais caracterรญsticas da linguagem, assim como seu uso na plataforma NEAR.
---
## Contato
[topo](#tutorial_near_rust)
Para dรบvidas, reclamaรงรตes ou sugestรตes, por favor me adicione no discord On0n0k1#3800. Se este tutorial facilitar a sua vida, considere comprar um cafรฉ para mim enviando uma fraรงรฃo de NEAR para stiltztinkerstein.near .
---
## Tรณpicos
[topo](#tutorial_near_rust)
- [O Que รฉ a linguagem Rust](#o-que-รฉ-a-linguagem-rust)
- [Usos da linguagem Rust](#usos-da-linguagem-rust)
- [Aprendendo a Linguagem Rust](#aprendendo-a-linguagem-rust)
- [Comparaรงรตes com Javascript e Python](#compara%C3%A7%C3%B5es-com-javascript-e-python)
- [Instalaรงรฃo](#instala%C3%A7%C3%A3o)
- [Liรงรตes](#li%C3%A7%C3%B5es)
---
## O que รฉ a linguagem Rust
[topo](#tutorial_near_rust)
De forma bem resumida, รฉ uma linguagem de programaรงรฃo de baixo nรญvel com as seguintes caracterรญsticas:
- Execuรงรฃo aproximadamente tรฃo rรกpida quanto linguagem c ou c++.
- Nรฃo tem os riscos de vazamento de memรณria que outras linguagens de baixo nรญvel possuem.
- ร dificil de comeรงar a aprender.
- Nรฃo **usa** e nem **precisa** de coleta de lixo de memรณria. Pois no periodo de compilaรงรฃo, o compilador sabe exatamente quando variรกveis sรฃo criadas e liberadas.
- Processamento em paralelo รฉ fรกcil.
- Processamento assรญncrono รฉ de dificuldade semelhante a outras linguagens populares.
- Muito mais simples organizaรงรฃo de projeto e dependรชncias do que python e javascript.
- Ganhou repetidos anos consecutivos como a linguagem mais popular do stackoverflow.
---
## Usos da linguagem Rust
[topo](#tutorial_near_rust)
Um desenvolvedor Rust pode:
- Criar apps decentralizados em plataformas web3 como NEAR.
- Pode criar aplicativos que nรฃo precisam de uma mรกquina virtual para serem executados. Precisa do compilador Rust para compilar, mas nรฃo precisa para executar.
- Criar servidores compactos e rรกpidos em conteineres docker.
- Criar aplicaรงรตes potentes como funรงรตes lambda para serem implantados em servidores aws (web3 รฉ melhor porรฉm).
- Usar o linker para criar bibliotecas que podem ser usadas por um compilador como c.
- Compilar bibliotecas que podem ser importadas em um browser javascript ou em um runtime nodejs com o formato WebAssembly.
- Compilar bibliotecas potentes e eficientes para Python usando a crate PyO3.
- Compilar cรณdigo para dispositivos embarcados (embedded).
- Competir em um mercado de trabalho que possui 1 ou 2 inscritos por vaga (incluindo internacional).
---
## Aprendendo a linguagem Rust
[topo](#tutorial_near_rust)
No meu ponto de vista, aprender a linguagem rust รฉ semelhante a idรฉia de domar um dragรฃo em um mundo de fantasia. ร demorado, รฉ dificil, existem muitas alternativas diferentes e mais simples do que essa. Mas, se conseguir, vocรช vai ter um terrรญvel dragรฃo ao seu lado.
Existem estudos que destacaram que o tempo para escrever uma certa quantidade de linhas de cรณdigo em linguagens de baixo nรญvel (como c) รฉ atรฉ 30 vezes mais devagar do que as de alto nรญvel (como python e javascript). Pela minha prรกtica, รฉ mais demorado ainda para uma pessoa aprendendo Rust escrever cรณdigo do que c.
Mas, com prรกtica, ficamos mais รกgeis em tudo. Com o tempo acostumamos com o que o compilador precisa e espera de nรณs. Podemos tambรฉm configurar snippets para gerar cรณdigos de "boilerplate" (forma) automaticamente. Entรฃo, รฉ apenas uma questรฃo de entendimento, memorizaรงรฃo e paciรชncia para o desenvolvedor. Houveram vezes em que eu escrevi 800 linhas de cรณdigo Rust em 2 dias.
Quase sempre teremos que dar pausas para estudar o nosso mรฉtodo e garantir que estamos fazendo as decisรตes corretas. Porรฉm, cada tentativa seguinte serรก mais fรกcil que a anterior.
---
## Comparaรงรตes com javascript e Python
[topo](#tutorial_near_rust)
Porรฉm uma pessoa astuta perguntaria "Porque eu iria aprender uma linguagem dessas se eu ja posso resolver os mesmos problemas com as linguagens que sei?" . ร uma รณtima pergunta, se eu ja posso conseguir o resultado escrevendo algumas linhas de cรณdigo em python no terminal, porque eu iria querer aprender Rust?
Facilidade de uso e resoluรงรฃo de problemas. Este รฉ o foco principal dessas linguagens. Como conseguir a soluรงรฃo para o nosso problema da forma mais simples possivel. Os processadores ficavam cada vez mais rรกpido cada geraรงรฃo, entรฃo bastava comprar as geraรงรตes de hardware mais recentes.
Porรฉm a lei de Moore nรฃo se aplica mais. Os desenvolvedores estรฃo precisando de algoritmos mais eficientes. Esta necessidade nos faz olhar para nossas linhas de cรณdigo e perguntar "O que estรก instruรงรฃo estรก fazendo exatamente?"
Quando escrevemos uma instruรงรฃo em python "a = 3". A mรกquina virtual python estรก criando um objeto numero, criando um ponteiro mutex que aponta para o numero, e associando "a" a este ponteiro. Por isso que python normalmente รฉ limitado a um core do processador. Quando tentamos aproveitar mais a capacidade de processamento de nossa mรกquina, a complexidade de cรณdigo em javascript e python cresce exponencialmente.
O foco da linguagem Rust nรฃo รฉ o resultado final dessa execuรงรฃo. E sim, o caminho que o processador e memรณria levam atรฉ alcanรงar este resultado. Um(a) desenvolvedor(a) rust experiente sabe olhar um bloco de cรณdigo e dizer:
- "Essa memรณria vai ser liberada nessa linha de cรณdigo";
- "O processador irรก pedir pra liberar um espaรงo de memรณria nessa linha e criar uma cรณpia dessa variรกvel aqui.";
- "Essa funรงรฃo irรก pegar esse endereรงo emprestado, usar este valor nessa parte, e retornar o endereรงo para o dono ao fim.";
---
## Instalaรงรฃo
[topo](#tutorial_near_rust)
Antes de comeรงarmos, devemos realizar os seguintes passos:
- Instalar [near-cli](https://github.com/On0n0k1/Tutorial_NEAR_Rust/blob/main/ES/static/tutorials/setup-nearcli.md) para interagir com a plataforma NEAR.
- Instalar [rust](https://github.com/On0n0k1/Tutorial_NEAR_Rust/blob/main/ES/static/tutorials/rust.md) para compilar e testar os projetos.
---
## Liรงรตes
[topo](#tutorial_near_rust)
- [Liรงรฃo 1: Contratos](https://github.com/On0n0k1/Tutorial_NEAR_Rust/tree/main/ES/lesson_1_contract)
- [Liรงรฃo 2: Ownership](https://github.com/On0n0k1/Tutorial_NEAR_Rust/tree/main/ES/lesson_2_ownership)
- [Liรงรฃo 3: Structs](https://github.com/On0n0k1/Tutorial_NEAR_Rust/tree/main/ES/lesson_3_structs)
- [Liรงรฃo 4: Mรณdulos](https://github.com/On0n0k1/Tutorial_NEAR_Rust/tree/main/ES/lesson_4_modules)
- [Licรฃo 5: Usando Macros](https://github.com/On0n0k1/Tutorial_NEAR_Rust/tree/main/ES/lesson_5_macro_usage)
- [Liรงรฃo 6: Enums](https://github.com/On0n0k1/Tutorial_NEAR_Rust/tree/main/ES/lesson_6_enums)
- Liรงรฃo 7: Traits
- Liรงรฃo 8: Coleรงรตes
# Tutorial_NEAR_Rust
[back](https://github.com/On0n0k1/Tutorial_NEAR_Rust/tree/main/)
A step-by-step course for learning Smart Contract development using Rust. In this set of lessons, we will discuss the main features of the Rust language,
as well as going over the NEAR platform.
---
## Contact
[top](#tutorial_near_rust)
For any questions, complaints or suggestions, look me up on Discord On0n0k1#3800. If this course makes your life easier, feel free to buy me a cup of coffe by sending a bit of $NEAR to stiltztinkerstein.near . Thank you!
---
## Topics
[top](#tutorial_near_rust)
- [What is the Rust language](#what-is-the-rust-language)
- [Using Rust](#using-rust)
- [Learning Rust](#learning-rust)
- [Comparing Rust to Javascript and Python](#comparing-rust-to-javascript-and-python)
- [Installing](#installing)
- [Lessons](#lessons)
---
## What is the Rust language
[topo](#tutorial_near_rust)
In short, Rust is a low-level systems programming language with the following features:
- Execution time in the likes of C or C++.
- Doesn't have the risk involved with memory management as other low-level languages.
- It has a steep learning curve (but is is well worth it!).
- Doesn't have and doesn't need garbage collection. At compile time, the compiler can determine when variables are created and freed.
- Easy to do parallel programming.
- Async programming has about the same level of difficult as other popular languages.
- Project and Dependency management is way easier than Python or JavaScript.
- Has been, for years, the most loved language by the developer community!
---
## Using Rust
[top](#tutorial_near_rust)
A Rust developer can:
- Create web3 applications using decentralized platforms such as NEAR.
- Create applications that don't need a virtual machine to run them. Only the compiler is needed to produce an executable.
- Create fast and compact server software hosted in Docker containers.
- Create robust applications like Lambda functions that can be hosted on AWS (better web3 performance).
- Create dynamic libs that can used from C.
- Compile modules to WebAssembly, which can then be imported in a browser that supports javascript or a runtime (like node.js).
- Compile robust and fast modules for Python using the PyO3 crate.
- Compile code that target Embedded systems.
- Have an edge in the job market where there's very few Rust developers worlwide.
---
## Learning Rust
[top](#tutorial_near_rust)
In my opinion, learning Rust is similar to taming a dragon in a fantasy-world. It is slow, difficult, with a lot of different, and simpler, alternatives.
But if you do tame it, you will have a **powerful** dragon by your side.
Studies show that it takes as much as 30 times more to write code in a low-level language (like C), than in a higher lever language (like Python or JavaScript).
It is my experience that for a newcomer learning Rust, it is even slower than writing C.
But, with practice, we get better at everything. With time, we learn what the compiler expects from us. We can leverage code snippets to generate "boilerplate" code automatically. Then, for the developer, everything just becomes a matter of understanding, memory and patience. There were times when I wrote 800 lines of Rust code
in just 2 days.
We must always take a break to assess our process and make sure we are making the right calls. if we do, every future step will be easier than the one that came before it.
---
## Comparing Rust to Javascript and Python
[top](#tutorial_near_rust)
A clever person might ask: "Why would I learn a difficult language if I can already solve the same problems in another language I already know?"... and that is a good question! if I already get good results writing a few lines of code in Python, why would I learn Rust?
Easy of use and quick problem solving: that is the main focus of those languages. How to get to a solution for our problem the most easiest way.
Processors were getting faster with each generation, so you could just buy new hardware that was faster and better and increase performance.
But Moore's Law doesn't apply anymore. So, developers are needing better and more efficient algorithms. This need makes them take a closer look at the code and ask
"What is this instruction doing, exactly?".
When we write `"a = 3"` in Python, a virtual machine is creating a number object, which entails creating a pointer to that number and then associating variable `a` to that pointer. That's why Python is generally limited to one processor core. When we want to take advantage of larger processing power on our machine, the code complexity increases exponentially in both JavaScript and Python.
Rust's focus isn't about the final result of that execution. It is about the path the processor and memory take to reach that result. An experienced Rust developer can take a look at a block of code and say:
- "That memory is going to be freed at this point in code";
- "The processor is going to request freeing memory here and create a shallow copy of that variable here.";
- "This function is going to borrow this address, use the value in this part of the code, and then give back that address to the owner.";
---
## Installing
[top](#tutorial_near_rust)
You need to install the following before starting the lessons:
- Install [near-cli](https://github.com/On0n0k1/Tutorial_NEAR_Rust/blob/main/PT-BR/static/tutorials/setup-nearcli.md) to interact with the NEAR platform.
- Install [rust](https://github.com/On0n0k1/Tutorial_NEAR_Rust/blob/main/PT-BR/static/tutorials/rust.md) to be able to compile and test projects.
---
## Lessons
[top](#tutorial_near_rust)
- [Lesson 1: Smart Contracts](https://github.com/On0n0k1/Tutorial_NEAR_Rust/tree/main/EN/lesson_1_contract)
- [Lesson 2: Ownership](https://github.com/On0n0k1/Tutorial_NEAR_Rust/tree/main/EN/lesson_2_ownership)
- [Lesson 3: Structs](https://github.com/On0n0k1/Tutorial_NEAR_Rust/tree/main/EN/lesson_3_structs)
- [Lesson 4: Modules](https://github.com/On0n0k1/Tutorial_NEAR_Rust/tree/main/EN/lesson_4_modules)
- [Lesson 5: Using Macros](https://github.com/On0n0k1/Tutorial_NEAR_Rust/tree/main/EN/lesson_5_macro_usage)
- [Lesson 6: Enums](https://github.com/On0n0k1/Tutorial_NEAR_Rust/tree/main/EN/lesson_6_enums)
# Tutorial_NEAR_Rust
[voltar](https://github.com/On0n0k1/Tutorial_NEAR_Rust/tree/main/)
Tutorial em etapas para desenvolvimento de contratos inteligentes em rust. Neste conjunto de tutoriais serรฃo discutidos todas as principais caracterรญsticas da linguagem, assim como seu uso na plataforma NEAR.
---
## Contato
[topo](#tutorial_near_rust)
Para dรบvidas, reclamaรงรตes ou sugestรตes, por favor me adicione no discord On0n0k1#3800. Se este tutorial facilitar a sua vida, considere comprar um cafรฉ para mim enviando uma fraรงรฃo de NEAR para stiltztinkerstein.near .
---
## Tรณpicos
[topo](#tutorial_near_rust)
- [O Que รฉ a linguagem Rust](#o-que-รฉ-a-linguagem-rust)
- [Usos da linguagem Rust](#usos-da-linguagem-rust)
- [Aprendendo a Linguagem Rust](#aprendendo-a-linguagem-rust)
- [Comparaรงรตes com Javascript e Python](#compara%C3%A7%C3%B5es-com-javascript-e-python)
- [Instalaรงรฃo](#instala%C3%A7%C3%A3o)
- [Liรงรตes](#li%C3%A7%C3%B5es)
---
## O que รฉ a linguagem Rust
[topo](#tutorial_near_rust)
De forma bem resumida, รฉ uma linguagem de programaรงรฃo de baixo nรญvel com as seguintes caracterรญsticas:
- Execuรงรฃo aproximadamente tรฃo rรกpida quanto linguagem c ou c++.
- Nรฃo tem os riscos de vazamento de memรณria que outras linguagens de baixo nรญvel possuem.
- ร dificil de comeรงar a aprender.
- Nรฃo **usa** e nem **precisa** de coleta de lixo de memรณria. Pois no periodo de compilaรงรฃo, o compilador sabe exatamente quando variรกveis sรฃo criadas e liberadas.
- Processamento em paralelo รฉ fรกcil.
- Processamento assรญncrono รฉ de dificuldade semelhante a outras linguagens populares.
- Muito mais simples organizaรงรฃo de projeto e dependรชncias do que python e javascript.
- Ganhou repetidos anos consecutivos como a linguagem mais popular do stackoverflow.
---
## Usos da linguagem Rust
[topo](#tutorial_near_rust)
Um desenvolvedor Rust pode:
- Criar apps decentralizados em plataformas web3 como NEAR.
- Pode criar aplicativos que nรฃo precisam de uma mรกquina virtual para serem executados. Precisa do compilador Rust para compilar, mas nรฃo precisa para executar.
- Criar servidores compactos e rรกpidos em conteineres docker.
- Criar aplicaรงรตes potentes como funรงรตes lambda para serem implantados em servidores aws (web3 รฉ melhor porรฉm).
- Usar o linker para criar bibliotecas que podem ser usadas por um compilador como c.
- Compilar bibliotecas que podem ser importadas em um browser javascript ou em um runtime nodejs com o formato WebAssembly.
- Compilar bibliotecas potentes e eficientes para Python usando a crate PyO3.
- Compilar cรณdigo para dispositivos embarcados (embedded).
- Competir em um mercado de trabalho que possui 1 ou 2 inscritos por vaga (incluindo internacional).
---
## Aprendendo a linguagem Rust
[topo](#tutorial_near_rust)
No meu ponto de vista, aprender a linguagem rust รฉ semelhante a idรฉia de domar um dragรฃo em um mundo de fantasia. ร demorado, รฉ dificil, existem muitas alternativas diferentes e mais simples do que essa. Mas, se conseguir, vocรช vai ter um terrรญvel dragรฃo ao seu lado.
Existem estudos que destacaram que o tempo para escrever uma certa quantidade de linhas de cรณdigo em linguagens de baixo nรญvel (como c) รฉ atรฉ 30 vezes mais devagar do que as de alto nรญvel (como python e javascript). Pela minha prรกtica, รฉ mais demorado ainda para uma pessoa aprendendo Rust escrever cรณdigo do que c.
Mas, com prรกtica, ficamos mais รกgeis em tudo. Com o tempo acostumamos com o que o compilador precisa e espera de nรณs. Podemos tambรฉm configurar snippets para gerar cรณdigos de "boilerplate" (forma) automaticamente. Entรฃo, รฉ apenas uma questรฃo de entendimento, memorizaรงรฃo e paciรชncia para o desenvolvedor. Houveram vezes em que eu escrevi 800 linhas de cรณdigo Rust em 2 dias.
Quase sempre teremos que dar pausas para estudar o nosso mรฉtodo e garantir que estamos fazendo as decisรตes corretas. Porรฉm, cada tentativa seguinte serรก mais fรกcil que a anterior.
---
## Comparaรงรตes com javascript e Python
[topo](#tutorial_near_rust)
Porรฉm uma pessoa astuta perguntaria "Porque eu iria aprender uma linguagem dessas se eu ja posso resolver os mesmos problemas com as linguagens que sei?" . ร uma รณtima pergunta, se eu ja posso conseguir o resultado escrevendo algumas linhas de cรณdigo em python no terminal, porque eu iria querer aprender Rust?
Facilidade de uso e resoluรงรฃo de problemas. Este รฉ o foco principal dessas linguagens. Como conseguir a soluรงรฃo para o nosso problema da forma mais simples possivel. Os processadores ficavam cada vez mais rรกpido cada geraรงรฃo, entรฃo bastava comprar as geraรงรตes de hardware mais recentes.
Porรฉm a lei de Moore nรฃo se aplica mais. Os desenvolvedores estรฃo precisando de algoritmos mais eficientes. Esta necessidade nos faz olhar para nossas linhas de cรณdigo e perguntar "O que estรก instruรงรฃo estรก fazendo exatamente?"
Quando escrevemos uma instruรงรฃo em python "a = 3". A mรกquina virtual python estรก criando um objeto numero, criando um ponteiro mutex que aponta para o numero, e associando "a" a este ponteiro. Por isso que python normalmente รฉ limitado a um core do processador. Quando tentamos aproveitar mais a capacidade de processamento de nossa mรกquina, a complexidade de cรณdigo em javascript e python cresce exponencialmente.
O foco da linguagem Rust nรฃo รฉ o resultado final dessa execuรงรฃo. E sim, o caminho que o processador e memรณria levam atรฉ alcanรงar este resultado. Um(a) desenvolvedor(a) rust experiente sabe olhar um bloco de cรณdigo e dizer:
- "Essa memรณria vai ser liberada nessa linha de cรณdigo";
- "O processador irรก pedir pra liberar um espaรงo de memรณria nessa linha e criar uma cรณpia dessa variรกvel aqui.";
- "Essa funรงรฃo irรก pegar esse endereรงo emprestado, usar este valor nessa parte, e retornar o endereรงo para o dono ao fim.";
---
## Instalaรงรฃo
[topo](#tutorial_near_rust)
Antes de comeรงarmos, devemos realizar os seguintes passos:
- Instalar [near-cli](https://github.com/On0n0k1/Tutorial_NEAR_Rust/blob/main/PT-BR/static/tutorials/setup-nearcli.md) para interagir com a plataforma NEAR.
- Instalar [rust](https://github.com/On0n0k1/Tutorial_NEAR_Rust/blob/main/PT-BR/static/tutorials/rust.md) para compilar e testar os projetos.
---
## Liรงรตes
[topo](#tutorial_near_rust)
- [Liรงรฃo 1: Contratos](https://github.com/On0n0k1/Tutorial_NEAR_Rust/tree/main/PT-BR/lesson_1_contract)
- [Liรงรฃo 2: Ownership](https://github.com/On0n0k1/Tutorial_NEAR_Rust/tree/main/PT-BR/lesson_2_ownership)
- [Liรงรฃo 3: Structs](https://github.com/On0n0k1/Tutorial_NEAR_Rust/tree/main/PT-BR/lesson_3_structs)
- [Liรงรฃo 4: Mรณdulos](https://github.com/On0n0k1/Tutorial_NEAR_Rust/tree/main/PT-BR/lesson_4_modules)
- [Licรฃo 5: Usando Macros](https://github.com/On0n0k1/Tutorial_NEAR_Rust/tree/main/PT-BR/lesson_5_macro_usage)
- [Liรงรฃo 6: Enums](https://github.com/On0n0k1/Tutorial_NEAR_Rust/tree/main/PT-BR/lesson_6_enums)
- Liรงรฃo 7: Traits
- Liรงรฃo 8: Coleรงรตes
|
kharioki_crossword-puzzle-contract | Cargo.toml
README.md
build.bat
build.sh
src
lib.rs
test.sh
| # Rust Smart Contract Template
## Getting started
To get started with this template:
1. Click the "Use this template" button to create a new repo based on this template
2. Update line 2 of `Cargo.toml` with your project name
3. Update line 4 of `Cargo.toml` with your project author names
4. Set up the [prerequisites](https://github.com/near/near-sdk-rs#pre-requisites)
5. Begin writing your smart contract in `src/lib.rs`
6. Test the contract
`cargo test -- --nocapture`
8. Build the contract
`RUSTFLAGS='-C link-arg=-s' cargo build --target wasm32-unknown-unknown --release`
**Get more info at:**
* [Rust Smart Contract Quick Start](https://docs.near.org/docs/develop/contracts/rust/intro)
* [Rust SDK Book](https://www.near-sdk.io/)
|
KirillShantin_NearApp_template | 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.
[](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.
[](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
```
[](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
```
|
frol_near-birthday-quest | README.md
contract
Cargo.toml
README.md
compile.js
src
lib.rs
package.json
| birthday-quest 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
birthday-quest
==============
This app was initialized with [create-near-app]
Quick Start
===========
The most automated way to run this project locally:
1. Prerequisites: Make sure you've installed [Node.js] โฅ 12
2. Install dependencies: `npm install`
3. Compile your contract `npm run build:contract`
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
==================
The "backend" code lives in the `/contract` folder. See the README there for more info.
Deploy
======
Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `npm run dev:deploy:contract`, 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:
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 `birthday-quest.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `birthday-quest.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 birthday-quest.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 || 'birthday-quest.YOUR-NAME.testnet'
Step 3: deploy!
---------------
Two commands:
npm run build:contract
npm run deploy:contract
As you can see in `package.json`, this builds & deploys smart contract to NEAR 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/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
# Happy Birthday Quest!
In order to crack this quest you will need to have at least one FT token (`lolcoin.qbit.near`), at least one NFT token (https://paras.id), and a secret code.
Learn your way through how to transfer tokens to `birthday-quest.near` with [FT](https://nomicon.io/Standards/Tokens/FungibleToken/Core) and [NFT](https://nomicon.io/Standards/Tokens/NonFungibleToken/Core) standards (`ft_transfer_call` and `nft_transfer_call`).
[NEAR CLI RS](https://near.cli.rs) is all you need to hack the quest.
|
freewind-demos_typescript-webpack-near-view-my-nft-demo | README.md
package.json
src
apis
config.ts
fetchLikelyNftContractNames.ts
global.d.ts
tsconfig.json
webpack.config.ts
| TypeScript Webpack Near View My NFT Demo
=================================
Suppose we already know self accountId, we can get our NFTs by `near-js-api`
Question:
Do we have to use an indexer to get the nft-like contract names?
Can we just use `near-js-api` to do all the things?
```
npm install
npm start
```
It will open page on browser automatically.
|
humans-meta_sef-near | .gitpod.yml
README.md
contract
README.md
babel.config.json
build.sh
deploy.sh
package-lock.json
package.json
src
contract.ts
tsconfig.json
frontend
App.js
assets
logo-black.svg
logo-white.svg
firebase.json
index.html
index.js
input.css
near-interface.js
near-wallet.js
package-lock.json
package.json
start.sh
tailwind.config.js
ui-components.js
integration-tests
package-lock.json
package.json
src
main.ava.ts
package-lock.json
package.json
| 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.
```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_seed-recovery | .github
ISSUE_TEMPLATE
BOUNTY.yml
README.md
index.html
ledger.js
package-lock.json
package.json
script.js
style.css
| # Seed Phrase Recovery Tool
This is a simple tool that allows you to retrieve your public and secret keys from NEAR seed phrases.
#### DISCLAIMER: This tool and source code are public, hosted by Github and NOT malicious. We are not responsible if Github pages has a vulnerability where malicious code is injected into the page or you are using a malicious browser or extension.
## Instructions
1. Open the tool
2. Enter your seed phrase
3. Click "Recover Public and Secret Key"
4. Optionally reveal secret key
|
ngocducedu_ranking-donate | .gitpod.yml
README.md
babel.config.js
contract
Cargo.toml
README.md
compile.js
src
lib.rs
target
.rustc_info.json
debug
.fingerprint
Inflector-be35511d7f434fc0
lib-inflector.json
ahash-f03cf74e4c01b8b5
lib-ahash.json
aho-corasick-a2255d3d13dde3f5
lib-aho_corasick.json
autocfg-99353e4847a2d22f
lib-autocfg.json
base64-30a9c96a5e4ef562
lib-base64.json
block-buffer-3478163e0cdbfbae
lib-block-buffer.json
block-buffer-89c1bc9cd66dac37
lib-block-buffer.json
block-padding-f989971f0b683c3a
lib-block-padding.json
borsh-03f48a8b10e63329
lib-borsh.json
borsh-derive-25db1fad22bba24d
lib-borsh-derive.json
borsh-derive-internal-fe315a1d6c0826b5
lib-borsh-derive-internal.json
borsh-schema-derive-internal-8b46faf39943a066
lib-borsh-schema-derive-internal.json
bs58-88fabaef62ed6bb0
lib-bs58.json
byte-tools-1b9d15d5eab81221
lib-byte-tools.json
byteorder-4bce751b2b438fb2
run-build-script-build-script-build.json
byteorder-af81091cb43b53b2
build-script-build-script-build.json
byteorder-bb707688d316815d
lib-byteorder.json
cfg-if-4f6d3d3c4041621c
lib-cfg-if.json
cfg-if-ecf7941c62f5b44e
lib-cfg-if.json
convert_case-613c83b7a192fcc8
lib-convert_case.json
cpuid-bool-bd72739ed57cee53
lib-cpuid-bool.json
derive_more-80467e513c82382b
lib-derive_more.json
digest-780c3b4fd0ab0b90
lib-digest.json
digest-a10916e05d427c9d
lib-digest.json
generic-array-358504fc98640552
lib-generic_array.json
generic-array-45610d8ffe842bc6
build-script-build-script-build.json
generic-array-ae7bdced67448cd3
lib-generic_array.json
generic-array-f641db900a8ffa94
run-build-script-build-script-build.json
greeter-99c8723d82cdc54f
test-lib-greeter.json
greeter-fadc17102a87ef33
lib-greeter.json
hashbrown-1558fbfd221d993a
lib-hashbrown.json
hashbrown-7d1d684498608806
run-build-script-build-script-build.json
hashbrown-8a1afd25b05b86e0
lib-hashbrown.json
hashbrown-a53e495f6d37067b
lib-hashbrown.json
hashbrown-caee1f771e73b445
build-script-build-script-build.json
hex-9e5fdbf9c3ab0473
lib-hex.json
indexmap-1e22bf79ed040414
build-script-build-script-build.json
indexmap-555dec6ada56cc70
lib-indexmap.json
indexmap-5af85ec6e77fddbf
run-build-script-build-script-build.json
indexmap-a9211190d0f7277a
lib-indexmap.json
itoa-473579430705fbbb
lib-itoa.json
itoa-aa1bdc6012c8d6db
lib-itoa.json
keccak-412396eb7f36b7f6
lib-keccak.json
lazy_static-e30305d6b4a8cafe
lib-lazy_static.json
memchr-2db5e054a560e347
build-script-build-script-build.json
memchr-a6ed367a284cab1b
run-build-script-build-script-build.json
memchr-c921576b1c24834c
lib-memchr.json
memory_units-2696e14363d09b91
lib-memory_units.json
near-primitives-core-af932f1faad4f26d
lib-near-primitives-core.json
near-rpc-error-core-b72a8f978e8ba4d9
lib-near-rpc-error-core.json
near-rpc-error-macro-c0c424d69c6bbf39
lib-near-rpc-error-macro.json
near-runtime-utils-8775b3ceeca3acea
lib-near-runtime-utils.json
near-sdk-101ce0f0ad683162
lib-near-sdk.json
near-sdk-core-22a0717e25524b70
lib-near-sdk-core.json
near-sdk-macros-5136bab3884cae82
lib-near-sdk-macros.json
near-vm-errors-1370b8df3df8b649
lib-near-vm-errors.json
near-vm-logic-bd8c039a1a477f27
lib-near-vm-logic.json
num-bigint-0bcdb5babb2269c0
run-build-script-build-script-build.json
num-bigint-7399793dbb7fffd1
lib-num-bigint.json
num-bigint-91e797a43337991f
build-script-build-script-build.json
num-integer-1b775de33a1bd773
run-build-script-build-script-build.json
num-integer-6e5f685a6f23fed3
build-script-build-script-build.json
num-integer-d0678dfea5325a74
lib-num-integer.json
num-rational-236701c72dce304c
build-script-build-script-build.json
num-rational-2e81fc6e6406be37
run-build-script-build-script-build.json
num-rational-c95b81649268eb3f
lib-num-rational.json
num-traits-95816eb0f6ef2427
build-script-build-script-build.json
num-traits-a83bbad3e4da7615
lib-num-traits.json
num-traits-ad7dd7c7b996be29
run-build-script-build-script-build.json
opaque-debug-ceb21770cc20b5d0
lib-opaque-debug.json
opaque-debug-ec7d17210988d017
lib-opaque-debug.json
proc-macro-crate-1a0fd0450914eb9a
lib-proc-macro-crate.json
proc-macro2-04870af5e50e5d3b
lib-proc-macro2.json
proc-macro2-8babd96339d79f05
build-script-build-script-build.json
proc-macro2-c6831e92cb73a037
run-build-script-build-script-build.json
quote-d02742c9cb38ac6f
lib-quote.json
regex-9b56d4875304d740
lib-regex.json
regex-syntax-c9b0ac7eb1b65ab0
lib-regex-syntax.json
ryu-3912f0ceb58bfef4
lib-ryu.json
ryu-6aa0a733b5ad5239
run-build-script-build-script-build.json
ryu-884b798a1aa2b2d9
lib-ryu.json
ryu-f44811fbe3f3e344
build-script-build-script-build.json
serde-5d8b8e3bb7771b1e
run-build-script-build-script-build.json
serde-5eb8fa0abc7ec794
build-script-build-script-build.json
serde-73f46e4ff1780ba4
lib-serde.json
serde-b92c077a14d8eba0
lib-serde.json
serde_derive-0d551e0a020828dc
run-build-script-build-script-build.json
serde_derive-99af9ad32d177cce
build-script-build-script-build.json
serde_derive-bb6cb5b81163b82d
lib-serde_derive.json
serde_json-16fe0c258542c30d
run-build-script-build-script-build.json
serde_json-6b7587112a62b4a0
build-script-build-script-build.json
serde_json-c9e4c0ac8e08a711
lib-serde_json.json
serde_json-f992a03a997ec9a6
lib-serde_json.json
sha2-00d1b23d065dd32a
lib-sha2.json
sha3-39ae0dbe7cc7044e
lib-sha3.json
syn-809acd8af4b1188f
run-build-script-build-script-build.json
syn-a8ca0d0ca7977b1f
build-script-build-script-build.json
syn-aff25f38f9f6129f
lib-syn.json
toml-21a52ce4fde9c920
lib-toml.json
typenum-093c30f3ee5a5c8e
build-script-build-script-main.json
typenum-6a0465159e1c0522
run-build-script-build-script-main.json
typenum-7d8272503b980f1e
lib-typenum.json
unicode-xid-7513ec0e8926616c
lib-unicode-xid.json
version_check-9675f8fa471b1d46
lib-version_check.json
wee_alloc-01289d3e0c848e80
run-build-script-build-script-build.json
wee_alloc-0374814e8e1eba2b
build-script-build-script-build.json
wee_alloc-337b2f25845bff37
lib-wee_alloc.json
winapi-24f7abdfc10b2ad0
build-script-build-script-build.json
winapi-3bc03ae1db0d7899
run-build-script-build-script-build.json
winapi-506608f31984d3a0
lib-winapi.json
build
num-bigint-0bcdb5babb2269c0
out
radix_bases.rs
typenum-6a0465159e1c0522
out
consts.rs
op.rs
tests.rs
wee_alloc-01289d3e0c848e80
out
wee_alloc_static_array_backend_size_bytes.txt
release
.fingerprint
Inflector-483ce91ff5aa15f8
lib-inflector.json
autocfg-ce85a218b1540152
lib-autocfg.json
borsh-derive-08207ac7260a4f69
lib-borsh-derive.json
borsh-derive-internal-bd6cd83eed1052a3
lib-borsh-derive-internal.json
borsh-schema-derive-internal-90798b4954bfd0e2
lib-borsh-schema-derive-internal.json
byteorder-e70357c20eab4e30
build-script-build-script-build.json
convert_case-6b5c266699258eee
lib-convert_case.json
derive_more-290d795f4828851e
lib-derive_more.json
generic-array-231dd7a95bc639bc
build-script-build-script-build.json
hashbrown-2a01efa688d68940
lib-hashbrown.json
hashbrown-66d29660a537aa3b
run-build-script-build-script-build.json
hashbrown-a2855436e53cc2f5
build-script-build-script-build.json
indexmap-2a3e96cb3b3cb857
run-build-script-build-script-build.json
indexmap-3c9eea8fd2f21fb1
lib-indexmap.json
indexmap-4b037eb798c5cee5
build-script-build-script-build.json
itoa-ff62a1efc82724ae
lib-itoa.json
memchr-0758b8dfc1b09760
build-script-build-script-build.json
near-rpc-error-core-2b1ca7f334247211
lib-near-rpc-error-core.json
near-rpc-error-macro-3efc07006af257cf
lib-near-rpc-error-macro.json
near-sdk-core-021c1ed1a8a9f552
lib-near-sdk-core.json
near-sdk-macros-74083bd4695d5ddd
lib-near-sdk-macros.json
num-bigint-b36d31ea94cf087e
build-script-build-script-build.json
num-integer-0b5892dc1d7e7ca2
build-script-build-script-build.json
num-rational-728f11d7e07d860b
build-script-build-script-build.json
num-traits-d53f7c16941e8c9b
build-script-build-script-build.json
proc-macro-crate-c5c0ac8c0f68c87e
lib-proc-macro-crate.json
proc-macro2-4e1447d1e7e5b7b3
lib-proc-macro2.json
proc-macro2-7db300a2ec246bfc
run-build-script-build-script-build.json
proc-macro2-eca4c7d459aca8e6
build-script-build-script-build.json
quote-31542fc938f05641
lib-quote.json
ryu-c2861a53025b06c6
lib-ryu.json
ryu-d041e4f8962f73ab
run-build-script-build-script-build.json
ryu-e3dd95f5efad34aa
build-script-build-script-build.json
serde-36f2cf739df794c0
run-build-script-build-script-build.json
serde-6d4e2b17c606c41c
lib-serde.json
serde-b37711e9e601ac03
build-script-build-script-build.json
serde_derive-53b756dd90385b7c
build-script-build-script-build.json
serde_derive-73ddec1649131747
run-build-script-build-script-build.json
serde_derive-c7d4445813275930
lib-serde_derive.json
serde_json-5c1050a46f85ef72
run-build-script-build-script-build.json
serde_json-7ac5d3881dbe6653
lib-serde_json.json
serde_json-dc2afaf64ab788e1
build-script-build-script-build.json
syn-0adc3c9dedfe2e8d
build-script-build-script-build.json
syn-7ff873656c09a046
run-build-script-build-script-build.json
syn-fd609c235de7731b
lib-syn.json
toml-2df19f76d99ea8da
lib-toml.json
typenum-fdeca83e9ab9c667
build-script-build-script-main.json
unicode-xid-3ba8feec3cb8f2a9
lib-unicode-xid.json
version_check-ee458fef17d07038
lib-version_check.json
wee_alloc-1e6206207f333d70
build-script-build-script-build.json
rls
.rustc_info.json
debug
.fingerprint
Inflector-be35511d7f434fc0
lib-inflector.json
ahash-f03cf74e4c01b8b5
lib-ahash.json
aho-corasick-a2255d3d13dde3f5
lib-aho_corasick.json
autocfg-99353e4847a2d22f
lib-autocfg.json
base64-30a9c96a5e4ef562
lib-base64.json
block-buffer-3478163e0cdbfbae
lib-block-buffer.json
block-buffer-89c1bc9cd66dac37
lib-block-buffer.json
block-padding-f989971f0b683c3a
lib-block-padding.json
borsh-03f48a8b10e63329
lib-borsh.json
borsh-derive-25db1fad22bba24d
lib-borsh-derive.json
borsh-derive-internal-fe315a1d6c0826b5
lib-borsh-derive-internal.json
borsh-schema-derive-internal-8b46faf39943a066
lib-borsh-schema-derive-internal.json
bs58-88fabaef62ed6bb0
lib-bs58.json
byte-tools-1b9d15d5eab81221
lib-byte-tools.json
byteorder-4bce751b2b438fb2
run-build-script-build-script-build.json
byteorder-af81091cb43b53b2
build-script-build-script-build.json
byteorder-bb707688d316815d
lib-byteorder.json
cfg-if-4f6d3d3c4041621c
lib-cfg-if.json
cfg-if-ecf7941c62f5b44e
lib-cfg-if.json
convert_case-613c83b7a192fcc8
lib-convert_case.json
cpuid-bool-bd72739ed57cee53
lib-cpuid-bool.json
derive_more-80467e513c82382b
lib-derive_more.json
digest-780c3b4fd0ab0b90
lib-digest.json
digest-a10916e05d427c9d
lib-digest.json
generic-array-358504fc98640552
lib-generic_array.json
generic-array-45610d8ffe842bc6
build-script-build-script-build.json
generic-array-ae7bdced67448cd3
lib-generic_array.json
generic-array-f641db900a8ffa94
run-build-script-build-script-build.json
greeter-99c8723d82cdc54f
test-lib-greeter.json
greeter-fadc17102a87ef33
lib-greeter.json
hashbrown-1558fbfd221d993a
lib-hashbrown.json
hashbrown-7d1d684498608806
run-build-script-build-script-build.json
hashbrown-8a1afd25b05b86e0
lib-hashbrown.json
hashbrown-a53e495f6d37067b
lib-hashbrown.json
hashbrown-caee1f771e73b445
build-script-build-script-build.json
hex-9e5fdbf9c3ab0473
lib-hex.json
indexmap-1e22bf79ed040414
build-script-build-script-build.json
indexmap-555dec6ada56cc70
lib-indexmap.json
indexmap-5af85ec6e77fddbf
run-build-script-build-script-build.json
indexmap-a9211190d0f7277a
lib-indexmap.json
itoa-473579430705fbbb
lib-itoa.json
itoa-aa1bdc6012c8d6db
lib-itoa.json
keccak-412396eb7f36b7f6
lib-keccak.json
lazy_static-e30305d6b4a8cafe
lib-lazy_static.json
memchr-2db5e054a560e347
build-script-build-script-build.json
memchr-a6ed367a284cab1b
run-build-script-build-script-build.json
memchr-c921576b1c24834c
lib-memchr.json
memory_units-2696e14363d09b91
lib-memory_units.json
near-primitives-core-af932f1faad4f26d
lib-near-primitives-core.json
near-rpc-error-core-b72a8f978e8ba4d9
lib-near-rpc-error-core.json
near-rpc-error-macro-c0c424d69c6bbf39
lib-near-rpc-error-macro.json
near-runtime-utils-8775b3ceeca3acea
lib-near-runtime-utils.json
near-sdk-101ce0f0ad683162
lib-near-sdk.json
near-sdk-core-22a0717e25524b70
lib-near-sdk-core.json
near-sdk-macros-5136bab3884cae82
lib-near-sdk-macros.json
near-vm-errors-1370b8df3df8b649
lib-near-vm-errors.json
near-vm-logic-bd8c039a1a477f27
lib-near-vm-logic.json
num-bigint-0bcdb5babb2269c0
run-build-script-build-script-build.json
num-bigint-7399793dbb7fffd1
lib-num-bigint.json
num-bigint-91e797a43337991f
build-script-build-script-build.json
num-integer-1b775de33a1bd773
run-build-script-build-script-build.json
num-integer-6e5f685a6f23fed3
build-script-build-script-build.json
num-integer-d0678dfea5325a74
lib-num-integer.json
num-rational-236701c72dce304c
build-script-build-script-build.json
num-rational-2e81fc6e6406be37
run-build-script-build-script-build.json
num-rational-c95b81649268eb3f
lib-num-rational.json
num-traits-95816eb0f6ef2427
build-script-build-script-build.json
num-traits-a83bbad3e4da7615
lib-num-traits.json
num-traits-ad7dd7c7b996be29
run-build-script-build-script-build.json
opaque-debug-ceb21770cc20b5d0
lib-opaque-debug.json
opaque-debug-ec7d17210988d017
lib-opaque-debug.json
proc-macro-crate-1a0fd0450914eb9a
lib-proc-macro-crate.json
proc-macro2-04870af5e50e5d3b
lib-proc-macro2.json
proc-macro2-8babd96339d79f05
build-script-build-script-build.json
proc-macro2-c6831e92cb73a037
run-build-script-build-script-build.json
quote-d02742c9cb38ac6f
lib-quote.json
regex-9b56d4875304d740
lib-regex.json
regex-syntax-c9b0ac7eb1b65ab0
lib-regex-syntax.json
ryu-3912f0ceb58bfef4
lib-ryu.json
ryu-6aa0a733b5ad5239
run-build-script-build-script-build.json
ryu-884b798a1aa2b2d9
lib-ryu.json
ryu-f44811fbe3f3e344
build-script-build-script-build.json
serde-5d8b8e3bb7771b1e
run-build-script-build-script-build.json
serde-5eb8fa0abc7ec794
build-script-build-script-build.json
serde-73f46e4ff1780ba4
lib-serde.json
serde-b92c077a14d8eba0
lib-serde.json
serde_derive-0d551e0a020828dc
run-build-script-build-script-build.json
serde_derive-99af9ad32d177cce
build-script-build-script-build.json
serde_derive-bb6cb5b81163b82d
lib-serde_derive.json
serde_json-16fe0c258542c30d
run-build-script-build-script-build.json
serde_json-6b7587112a62b4a0
build-script-build-script-build.json
serde_json-c9e4c0ac8e08a711
lib-serde_json.json
serde_json-f992a03a997ec9a6
lib-serde_json.json
sha2-00d1b23d065dd32a
lib-sha2.json
sha3-39ae0dbe7cc7044e
lib-sha3.json
syn-809acd8af4b1188f
run-build-script-build-script-build.json
syn-a8ca0d0ca7977b1f
build-script-build-script-build.json
syn-aff25f38f9f6129f
lib-syn.json
toml-21a52ce4fde9c920
lib-toml.json
typenum-093c30f3ee5a5c8e
build-script-build-script-main.json
typenum-6a0465159e1c0522
run-build-script-build-script-main.json
typenum-7d8272503b980f1e
lib-typenum.json
unicode-xid-7513ec0e8926616c
lib-unicode-xid.json
version_check-9675f8fa471b1d46
lib-version_check.json
wee_alloc-01289d3e0c848e80
run-build-script-build-script-build.json
wee_alloc-0374814e8e1eba2b
build-script-build-script-build.json
wee_alloc-337b2f25845bff37
lib-wee_alloc.json
winapi-24f7abdfc10b2ad0
build-script-build-script-build.json
winapi-3bc03ae1db0d7899
run-build-script-build-script-build.json
winapi-506608f31984d3a0
lib-winapi.json
build
byteorder-af81091cb43b53b2
save-analysis
build_script_build-af81091cb43b53b2.json
generic-array-45610d8ffe842bc6
save-analysis
build_script_build-45610d8ffe842bc6.json
hashbrown-caee1f771e73b445
save-analysis
build_script_build-caee1f771e73b445.json
indexmap-1e22bf79ed040414
save-analysis
build_script_build-1e22bf79ed040414.json
memchr-2db5e054a560e347
save-analysis
build_script_build-2db5e054a560e347.json
num-bigint-0bcdb5babb2269c0
out
radix_bases.rs
num-bigint-91e797a43337991f
save-analysis
build_script_build-91e797a43337991f.json
num-integer-6e5f685a6f23fed3
save-analysis
build_script_build-6e5f685a6f23fed3.json
num-rational-236701c72dce304c
save-analysis
build_script_build-236701c72dce304c.json
num-traits-95816eb0f6ef2427
save-analysis
build_script_build-95816eb0f6ef2427.json
proc-macro2-8babd96339d79f05
save-analysis
build_script_build-8babd96339d79f05.json
ryu-f44811fbe3f3e344
save-analysis
build_script_build-f44811fbe3f3e344.json
serde-5eb8fa0abc7ec794
save-analysis
build_script_build-5eb8fa0abc7ec794.json
serde_derive-99af9ad32d177cce
save-analysis
build_script_build-99af9ad32d177cce.json
serde_json-6b7587112a62b4a0
save-analysis
build_script_build-6b7587112a62b4a0.json
syn-a8ca0d0ca7977b1f
save-analysis
build_script_build-a8ca0d0ca7977b1f.json
typenum-093c30f3ee5a5c8e
save-analysis
build_script_main-093c30f3ee5a5c8e.json
typenum-6a0465159e1c0522
out
consts.rs
op.rs
tests.rs
wee_alloc-01289d3e0c848e80
out
wee_alloc_static_array_backend_size_bytes.txt
wee_alloc-0374814e8e1eba2b
save-analysis
build_script_build-0374814e8e1eba2b.json
winapi-24f7abdfc10b2ad0
save-analysis
build_script_build-24f7abdfc10b2ad0.json
deps
save-analysis
greeter-99c8723d82cdc54f.json
libahash-f03cf74e4c01b8b5.json
libaho_corasick-a2255d3d13dde3f5.json
libautocfg-99353e4847a2d22f.json
libbase64-30a9c96a5e4ef562.json
libblock_buffer-3478163e0cdbfbae.json
libblock_padding-f989971f0b683c3a.json
libborsh-03f48a8b10e63329.json
libbs58-88fabaef62ed6bb0.json
libbyte_tools-1b9d15d5eab81221.json
libbyteorder-bb707688d316815d.json
libcfg_if-ecf7941c62f5b44e.json
libconvert_case-613c83b7a192fcc8.json
libcpuid_bool-bd72739ed57cee53.json
libderive_more-80467e513c82382b.json
libdigest-a10916e05d427c9d.json
libgeneric_array-358504fc98640552.json
libgeneric_array-ae7bdced67448cd3.json
libgreeter-fadc17102a87ef33.json
libhashbrown-8a1afd25b05b86e0.json
libhashbrown-a53e495f6d37067b.json
libhex-9e5fdbf9c3ab0473.json
libindexmap-555dec6ada56cc70.json
libindexmap-a9211190d0f7277a.json
libinflector-be35511d7f434fc0.json
libitoa-473579430705fbbb.json
libkeccak-412396eb7f36b7f6.json
liblazy_static-e30305d6b4a8cafe.json
libmemchr-c921576b1c24834c.json
libmemory_units-2696e14363d09b91.json
libnear_primitives_core-af932f1faad4f26d.json
libnear_rpc_error_core-b72a8f978e8ba4d9.json
libnear_rpc_error_macro-c0c424d69c6bbf39.json
libnear_runtime_utils-8775b3ceeca3acea.json
libnear_sdk-101ce0f0ad683162.json
libnear_vm_errors-1370b8df3df8b649.json
libnear_vm_logic-bd8c039a1a477f27.json
libnum_bigint-7399793dbb7fffd1.json
libnum_integer-d0678dfea5325a74.json
libnum_rational-c95b81649268eb3f.json
libnum_traits-a83bbad3e4da7615.json
libopaque_debug-ec7d17210988d017.json
libproc_macro2-04870af5e50e5d3b.json
libproc_macro_crate-1a0fd0450914eb9a.json
libquote-d02742c9cb38ac6f.json
libregex-9b56d4875304d740.json
libryu-3912f0ceb58bfef4.json
libryu-884b798a1aa2b2d9.json
libsha2-00d1b23d065dd32a.json
libsha3-39ae0dbe7cc7044e.json
libtoml-21a52ce4fde9c920.json
libunicode_xid-7513ec0e8926616c.json
libversion_check-9675f8fa471b1d46.json
libwee_alloc-337b2f25845bff37.json
wasm32-unknown-unknown
debug
.fingerprint
ahash-b6f68701058cdd1e
lib-ahash.json
aho-corasick-d0148712a42b633c
lib-aho_corasick.json
base64-1ccb1a64d5497fe7
lib-base64.json
block-buffer-6832402aecbde361
lib-block-buffer.json
block-buffer-f4c71c4597c7f5d0
lib-block-buffer.json
block-padding-f3ec46f7955de1da
lib-block-padding.json
borsh-cbd075c1b69f0643
lib-borsh.json
bs58-62a18fcd5617b7a9
lib-bs58.json
byte-tools-21f7f0d22ac08cac
lib-byte-tools.json
byteorder-0d8095d29932b98d
lib-byteorder.json
byteorder-9f67077edf55a876
run-build-script-build-script-build.json
cfg-if-77b9f630aef51dee
lib-cfg-if.json
cfg-if-92c6de196da09b85
lib-cfg-if.json
digest-9cb8606c033b4fb0
lib-digest.json
digest-b536550ba54a9e4f
lib-digest.json
generic-array-252143b6dcf80624
run-build-script-build-script-build.json
generic-array-293155d4c849dc4a
lib-generic_array.json
generic-array-42b3041e5d9bc925
lib-generic_array.json
greeter-98ace302c5fafa12
lib-greeter.json
hashbrown-0a7ce66fa84b61ad
lib-hashbrown.json
hashbrown-162971156c41ef36
run-build-script-build-script-build.json
hashbrown-c421f805a4bc6c1d
lib-hashbrown.json
hex-aab7caf5bcc591e9
lib-hex.json
indexmap-5cd8ba9ac0a739ef
run-build-script-build-script-build.json
indexmap-d2b6d6b9c3794212
lib-indexmap.json
itoa-4bd00904e0c35f99
lib-itoa.json
keccak-f8b7bf70419c02a1
lib-keccak.json
lazy_static-596ce4fdfdb8b2d2
lib-lazy_static.json
memchr-3900b871927aacb9
lib-memchr.json
memchr-66f354cd7e9ad8e2
run-build-script-build-script-build.json
memory_units-728598c66049965b
lib-memory_units.json
near-primitives-core-38eb963e3ee34cf9
lib-near-primitives-core.json
near-runtime-utils-d42ca82072cae6ab
lib-near-runtime-utils.json
near-sdk-062fee94b6e2344f
lib-near-sdk.json
near-vm-errors-c1bb5d530164fd9a
lib-near-vm-errors.json
near-vm-logic-fc3f78d82a702f3c
lib-near-vm-logic.json
num-bigint-45b371aa8679b599
run-build-script-build-script-build.json
num-bigint-cbd1728d890ccac9
lib-num-bigint.json
num-integer-2dc1a1c215748efc
run-build-script-build-script-build.json
num-integer-6c0e38d979c8eebe
lib-num-integer.json
num-rational-084baed7e6c46733
lib-num-rational.json
num-rational-5366d1d4269fad37
run-build-script-build-script-build.json
num-traits-9578246d28c841f9
lib-num-traits.json
num-traits-b20d626531461867
run-build-script-build-script-build.json
opaque-debug-719070c993077c37
lib-opaque-debug.json
opaque-debug-ed44a1f36f2c054b
lib-opaque-debug.json
regex-d1f31dca25707159
lib-regex.json
regex-syntax-350d97b340367358
lib-regex-syntax.json
ryu-47453c9f45142af0
run-build-script-build-script-build.json
ryu-b77c2e262fb19f8d
lib-ryu.json
serde-af01ceb35620551a
run-build-script-build-script-build.json
serde-d816659e77461766
lib-serde.json
serde_json-a2600e4f5e3ba320
run-build-script-build-script-build.json
serde_json-c6c711c0faac898a
lib-serde_json.json
sha2-b06d21522adc5e1f
lib-sha2.json
sha3-3601fc3ec0c4d86f
lib-sha3.json
typenum-57ec82ad682f538b
run-build-script-build-script-main.json
typenum-6118c895b7697afa
lib-typenum.json
wee_alloc-072a990b5f6dafc9
run-build-script-build-script-build.json
wee_alloc-4c0ed88e4cbbfb78
lib-wee_alloc.json
build
num-bigint-45b371aa8679b599
out
radix_bases.rs
typenum-57ec82ad682f538b
out
consts.rs
op.rs
tests.rs
wee_alloc-072a990b5f6dafc9
out
wee_alloc_static_array_backend_size_bytes.txt
release
.fingerprint
ahash-fad9afba40a14e03
lib-ahash.json
aho-corasick-d9d7b148e91ae646
lib-aho_corasick.json
base64-9d9084926bf72180
lib-base64.json
block-buffer-2a7261eb717442c2
lib-block-buffer.json
block-buffer-815bd0cd1f6cbe5e
lib-block-buffer.json
block-padding-f642f86bca4ed6bd
lib-block-padding.json
borsh-8aa325fbb726d591
lib-borsh.json
bs58-858fcbd5c2709696
lib-bs58.json
byte-tools-f1181d58756bb919
lib-byte-tools.json
byteorder-789228101856e15b
lib-byteorder.json
byteorder-cb6e66b7549ebd80
run-build-script-build-script-build.json
cfg-if-283260330df7f479
lib-cfg-if.json
cfg-if-776501a25ece13bf
lib-cfg-if.json
digest-cdd333cfa3593bd7
lib-digest.json
digest-f328c5b9a3e65f48
lib-digest.json
generic-array-205a67e8628f57fc
lib-generic_array.json
generic-array-6e30963090370fcd
lib-generic_array.json
generic-array-d806511e049f512e
run-build-script-build-script-build.json
greeter-98ace302c5fafa12
lib-greeter.json
hashbrown-7bf88564a6b65934
run-build-script-build-script-build.json
hashbrown-8b5f0132300f6c45
lib-hashbrown.json
hashbrown-bd50cf0b1670be7d
lib-hashbrown.json
hex-8901338006dc52f1
lib-hex.json
indexmap-4a8eec93a542c9b9
lib-indexmap.json
indexmap-9891278662b62c23
run-build-script-build-script-build.json
itoa-6c3d6a5ba66f429e
lib-itoa.json
keccak-badf58af404fc385
lib-keccak.json
lazy_static-71db0edb898689b3
lib-lazy_static.json
memchr-3c6702715ea5df01
run-build-script-build-script-build.json
memchr-fe4643097c373d43
lib-memchr.json
memory_units-2b061acaa248b417
lib-memory_units.json
near-primitives-core-8e6a8d0a104974f5
lib-near-primitives-core.json
near-runtime-utils-c9992eb3fde83e7f
lib-near-runtime-utils.json
near-sdk-e8659c975b658f18
lib-near-sdk.json
near-vm-errors-ad7864b248f531d5
lib-near-vm-errors.json
near-vm-logic-e988caf0a44d57f0
lib-near-vm-logic.json
num-bigint-8b5c58d214d87a17
run-build-script-build-script-build.json
num-bigint-a1820cb58c92cd01
lib-num-bigint.json
num-integer-4438e2714ce28da1
lib-num-integer.json
num-integer-8cd63d7f3b89ac33
run-build-script-build-script-build.json
num-rational-08b1bb95062a4095
lib-num-rational.json
num-rational-dde446293f151202
run-build-script-build-script-build.json
num-traits-1fa445ae716c00a2
lib-num-traits.json
num-traits-d79015f39b141326
run-build-script-build-script-build.json
opaque-debug-0cc194d1de207b91
lib-opaque-debug.json
opaque-debug-802ecee97daf6c5c
lib-opaque-debug.json
regex-dbb0b202c9105505
lib-regex.json
regex-syntax-803f9b974056d78e
lib-regex-syntax.json
ryu-5bcc91b69b851c43
run-build-script-build-script-build.json
ryu-fafa867ebf95f0f0
lib-ryu.json
serde-9a42bcd95f35b0a1
run-build-script-build-script-build.json
serde-b4e6c90d336acb78
lib-serde.json
serde_json-b6cb9caf85dd58c7
run-build-script-build-script-build.json
serde_json-ce83a6d47369f384
lib-serde_json.json
sha2-2b4edcf279ea9c0b
lib-sha2.json
sha3-246855b67abb77cd
lib-sha3.json
typenum-0092018f098c9d7d
run-build-script-build-script-main.json
typenum-87539a86acd1e7dd
lib-typenum.json
wee_alloc-75f7cb658a6a1813
run-build-script-build-script-build.json
wee_alloc-994fc70e7a8d4b3c
lib-wee_alloc.json
build
num-bigint-8b5c58d214d87a17
out
radix_bases.rs
typenum-0092018f098c9d7d
out
consts.rs
op.rs
tests.rs
wee_alloc-75f7cb658a6a1813
out
wee_alloc_static_array_backend_size_bytes.txt
|
|","span":{"file_name":"C:\\Users\\ohmyg\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\base64-0.13.0\\src\\lib.rs","byte_start":1038,"byte_end":1133,"line_start":22,"line_end":22,"column_start":1,"column_end":96}},{"value":"
| `encode` | Returns a new `String` | Always |","span":{"file_name":"C:\\Users\\ohmyg\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\base64-0.13.0\\src\\lib.rs","byte_start":1134,"byte_end":1229,"line_start":23,"line_end":23,"column_start":1,"column_end":96}},{"value":"
| `encode_config` | Returns a new `String` | Always |","span":{"file_name":"C:\\Users\\ohmyg\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\base64-0.13.0\\src\\lib.rs","byte_start":1230,"byte_end":1325,"line_start":24,"line_end":24,"column_start":1,"column_end":96}},{"value":"
| `encode_config_buf` | Appends to provided `String` | Only if `String` needs to grow |","span":{"file_name":"C:\\Users\\ohmyg\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\base64-0.13.0\\src\\lib.rs","byte_start":1326,"byte_end":1421,"line_start":25,"line_end":25,"column_start":1,"column_end":96}},{"value":"
| `encode_config_slice` | Writes to provided `&[u8]` | Never |","span":{"file_name":"C:\\Users\\ohmyg\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\base64-0.13.0\\src\\lib.rs","byte_start":1422,"byte_end":1517,"line_start":26,"line_end":26,"column_start":1,"column_end":96}},{"value":"
","span":{"file_name":"C:\\Users\\ohmyg\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\base64-0.13.0\\src\\lib.rs","byte_start":1518,"byte_end":1521,"line_start":27,"line_end":27,"column_start":1,"column_end":4}},{"value":"
All of the encoding functions that take a `Config` will pad as per the config.","span":{"file_name":"C:\\Users\\ohmyg\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\base64-0.13.0\\src\\lib.rs","byte_start":1522,"byte_end":1604,"line_start":28,"line_end":28,"column_start":1,"column_end":83}},{"value":"
","span":{"file_name":"C:\\Users\\ohmyg\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\base64-0.13.0\\src\\lib.rs","byte_start":1605,"byte_end":1608,"line_start":29,"line_end":29,"column_start":1,"column_end":4}},{"value":"
# Decoding","span":{"file_name":"C:\\Users\\ohmyg\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\base64-0.13.0\\src\\lib.rs","byte_start":1609,"byte_end":1623,"line_start":30,"line_end":30,"column_start":1,"column_end":15}},{"value":"
","span":{"file_name":"C:\\Users\\ohmyg\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\base64-0.13.0\\src\\lib.rs","byte_start":1624,"byte_end":1627,"line_start":31,"line_end":31,"column_start":1,"column_end":4}},{"value":"
Just as for encoding, there are different decoding functions available.","span":{"file_name":"C:\\Users\\ohmyg\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\base64-0.13.0\\src\\lib.rs","byte_start":1628,"byte_end":1703,"line_start":32,"line_end":32,"column_start":1,"column_end":76}},{"value":"
","span":{"file_name":"C:\\Users\\ohmyg\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\base64-0.13.0\\src\\lib.rs","byte_start":1704,"byte_end":1707,"line_start":33,"line_end":33,"column_start":1,"column_end":4}},{"value":"
| Function | Output | Allocates |","span":{"file_name":"C:\\Users\\ohmyg\\.cargo\\registry\\src\\github.com-1ecc6299db9ec823\\base64-0.13.0\\src\\lib.rs","byte_start":1708,"byte_end":1804,"line_start":34,"line_end":34,"column_start":1,"column_end":97}},{"value":"
|
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
| HelloNear 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
HelloNear
==================
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 `HelloNear.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `HelloNear.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 HelloNear.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 || 'HelloNear.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
# ranking-donate
|
PotLock_changelog | .github
ISSUE_TEMPLATE
BOUNTY.yml
README.md
| # changelog
Temporary repo to express deployed contracts and accounts by Potluck Foundation. Will later be updated via on chain updates through DAO.
# Current Versions
registry.potlock.near| Purpose: add project accounts to registyr to display on front ends and set as a requirement for future funding strategies | Blockchain: Deployment Date | Update Status: Not Locked, Last Updated on | Admins: External addresses can set statuses of project | Financial: Pass Through Contract
donate.potlock.near| Purpose: pass through contract for direct donations. Blockchain: Deployment Date | Update Status: Not Locked, Last Updated on | Financial: Non-Financial / Takes Fees | Permssions Owner can update fee
## Testing
# Wallets
potlock.near
# Other Contracts Uses
social.near |
# Best Practices
- All contracts will be under the potlock.near name space
- Contracts will be deployed by version. Contracts will be locked in future name space and indicated on change log.
|
muhammedalibilgin_order-management-with-near | README.md
contract
as-pect.config.js
asconfig.json
assembly
__tests__
as-pect.d.ts
index.spec.ts
as_types.d.ts
index.ts
model.ts
tsconfig.json
index.html
index.js
neardev
dev-account.env
package.json
tests
index.js
frontend
README.md
package.json
public
index.html
manifest.json
robots.txt
src
App.js
App.test.js
components
CreateOrder.js
CurrentUser.js
Head.js
Order.js
OrderList.js
config.js
css
App.css
Head.css
orderlist.css
index.css
index.js
reportWebVitals.js
setupTests.js
package-lock.json
package.json
| # Order-Management-With-NEAR
Managing product orders over the Near blockchain.
This project is written in AssemblyScript, which is a derivative of TypeScript.
# 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)
|
nasko929_NEARttik | README.md
attik-mongodb-query-executor
.env
index.ts
package-lock.json
package.json
tsconfig.json
utils
mongoWrappers.ts
query.ts
utils.ts
attik-sdk-js
database.ts
model.ts
package-lock.json
package.json
query.ts
schema.ts
attik-transaction-interceptor
index.js
package-lock.json
package.json
utils
all_contracts.json
fetch_contract_ids.js
last_read_contract_transaction.json
example-contract
.gitpod.yml
README.md
contract
README.md
babel.config.json
build.sh
build
builder.c
code.h
hello_near.js
methods.h
deploy.sh
neardev
dev-account.env
package-lock.json
package.json
src
CoordinateModel.ts
contract.ts
coordinate.ts
tsconfig.json
integration-tests
package-lock.json
package.json
src
main.ava.ts
package-lock.json
package.json
| 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.
```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>`.
# NEARttik
Project concentrated on providing protocol that smart contracts would use to create MongoDB
databases, schemas and queries on the go without having to deal with Chainlink nodes and adapters.
## The project's architecture

### 1) Attik's Smart Contract Library (Attik SDK - JS)
- This library serves the purpose of providing Mongoose-like architecture,
containing methods and structures to interact with MongoDB in a seamless way;
- It is written with NEAR's JavaScript SDK and TypeScript;
- It provides methods like: createCollection, save, find, delete;
- It also provides functionality to combine a few queries and treat them as one transaction.
### 2) Example Contract
- Contract that uses **Attik Smart Contract Library** as its base;
- It shows how exactly would an Attik smart contract model look like (hint: the same as in Web2 NodeJS Mongoose code);
- Implements Coordinate(x, y) as model and defines basic CRUD operations.
### 3) Attik Transaction Interceptor
- **The transaction interceptor** looks for transactions executed by the Smart Contracts that
are using **Attik's Smart Contract Library** in real-time, filters the logs in each transaction and
sends only mongo-query-related logs as queries to the **Attik MongoDB Query Executor**;
- Once **Attik MongoDB Query Executor** is ready with the execution of the queries, **the Transaction Interceptor**
calls the appropriate callbacks that were set in the initial queries in the Smart Contracts.
- It uses **NEAR Indexer** to track the flow of new transactions.
### 4) Attik MongoDB Query Executor
- **The MongoDB Query Executor** is taking all the queries that come from the **Transaction Interceptor**,
runs them in-order of arrival, then forwards the response back to Interceptor.
- Translates the JSON objects to MongoDB queries.
## Next steps
- Uploading backup versions of each MongoDB to IPFS as the first step towards decentralization;
- A protocol that is completely decentralized (perhaps a chain on Cosmos);
- Roadmap - TBD..
|
haoxiang14_near-horizon | README.md
index.html
manifest.json
package-lock.json
package.json
public
vite.svg
src
App.css
assets
react.svg
index.css
vite.config.js
| # TipZoNear
## Intro
TipZoNear is a chrome extension that allows you to tip NEAR tokens on the posts on Near (https://near.org/). It has built-in functionalities to detect the posts on Near and display a tip button on the post. It also has a popup page that allows you to tip NEAR tokens to the post author.

## Tech Stack
* React
* Vite
* crxjs Vite Plugin
* Near JS API
## Development
```bash
$ git clone https://github.com/haoxiang14/near-horizon.git
$ cd near-horizon
$ pnpm i
$ pnpm dev # run dev server
$ pnpm build # build extension
```
|
near-ndc_voting-v1 | .clippy.toml
.github
workflows
lint.yml
rust.yml
.markdownlint.json
Cargo.toml
README.md
common
Cargo.toml
README.md
src
errors.rs
events.rs
lib.rs
congress
CHANGELOG.md
Cargo.toml
README.md
src
constants.rs
errors.rs
events.rs
ext.rs
lib.rs
migrate.rs
proposal.rs
storage.rs
view.rs
tests
integration.rs
elections
CHANGELOG.md
Cargo.toml
README.md
helper.sh
src
constants.rs
errors.rs
events.rs
ext.rs
lib.rs
migrate.rs
proposal.rs
storage.rs
view.rs
tests
iah.rs
integrations
Cargo.toml
src
lib.rs
nominations
Cargo.toml
README.md
helper.sh
src
constants.rs
ext.rs
lib.rs
storage.rs
tests
workspaces.rs
rust-toolchain.toml
voting_body
CHANGELOG.md
Cargo.toml
README.md
src
constants.rs
errors.rs
events.rs
ext.rs
impls.rs
lib.rs
migrate.rs
proposal.rs
storage.rs
types.rs
view.rs
tests
integration.rs
| # Voting Body
- [Diagrams](https://miro.com/app/board/uXjVMqJRr_U=/)
- [Framework Specification](https://www.notion.so/NDC-V1-Framework-V3-2-Updated-1af84fe7cc204087be70ea7ffee4d23f)
Voting Body is governance structure of all non-blacklisted human participants in the NEAR Ecosystem. There are no requirements for being a member of the voting body beyond completing โI am Humanโ and not being on the blacklist.
Deployed Contracts
- mainnet: `voting-body-v1.ndc-gwg.near`
- testnet: `voting-body-v1.gwg.testnet`, IAH registry: `registry-unstable-v2.i-am-human.testnet`
## Contract Parameters
- `quorum`: a minimum amount of members that need to vote to approve a proposal.
- `pre_vote_support`: minimum amount of support, a proposal has to receive in order to move it to the active queue, where users can vote to approve a proposal.
- `pre_vote_duration`: max amount of time, users can express support to move a proposal to the active queue, before it will be removed.
- `pre_vote_bond`: amount of N required to add a proposal to the pre-vote queue.
- `active_queue_bond`: amount of N required to move a proposal directly to the active queue.
- `vote_duration`: max amount of time a proposal can be active in the active queue. If a proposal didn't get enough approvals by that time, it will be removed and bond returned.
You can query the parameters with:
```shell
near view VOTING_BODY config ''
```
## Creating proposals
Every human can create a proposal. The proposals are organized in 2 queues (pre-vote queue and active queue) in order to filter out spam proposals.
When creating a proposal, the submitter must stake a bond. If `pre-vote bond` is attached, then the proposal goes to the pre-vote queue. If `active_queue_bond` is attached then the proposal goes directly to active queue (_fast track_ - no need for getting a pre-vote support, but the proposer takes a responsibility of being slashed if the proposal is marked as spam).
Proposal can only be created by an IAH verified account. We use `is_human_call` method. Example call:
```shell
near call IAH_REGISTRY is_human_call \
'{"ctr": "VB.near", "function": "create_proposal", "payload": "{\"kind\": {\"Veto\": {\"dao\": \"hom.near\", \"prop_id\": 12}}, \"description\": \"this proposal is against the budget objectives\"}"}' \
--accountId YOU \
--depositYocto $pre_vote_bond
# Creating a text proposal with with a active_queue_bond (making it automatically advancing to the active queue)
near call IAH_REGISTRY is_human_call \
'{"ctr": "VB.near", "function": "create_proposal", "payload": "{\"kind\": \"Text\", \"description\": \"lets go\"}"}' \
--accountId YOU --deposit $active_queue_bond
```
### Pre-vote queue
Proposals in this queue are not active. VB members can't vote for proposals in the pre-vote queue and UI doesn't display them by default. Instead, members can send a _pre_vote_support_ transaction. There are 3 ways to move a proposal to the active queue:
- get `pre_vote_support` support transactions from VB members;
- top up with more NEAR to reach `active_queue_bond`;
- get a support by one of the Congress members using `support_proposal_by_congress` method.
Note: originally only a congress support was required to move a proposal to the active queue. However, that creates a strong subjectivity and censorship (example: VB wants to dismiss a house - obviously house may not be happy and not "support" such a proposal).
Voting Body Support can only be made by an IAH verified account. We use `is_human_call_lock` method, which will lock the caller for soul transfers, to avoid double support. Example call:
```shell
lock_duration=pre_vote_duration+1
near call IAH_REGISTRY is_human_call_lock \
'{"ctr": "VB.near", "function": "support_proposal", "payload": "1", "lock_duration": '$lock_duration', "with_proof": false}' \
--accountId YOU
```
### Active queue
Proposals in this queue are eligible for voting and displayed by the default in the UI. Proposals from the active queue are not removed unless they are marked as spam (more about it in the voting section). They are preserved and anyone can query them, even when a proposal was rejected.
When a proposal is moved from the pre-vote queue to the active queue, the set of accounts that supported the proposal is cleared - it's not needed any more. We can save the space and proposal load time.
```mermaid
---
title: Proposal Queues
---
flowchart TB
PVQ[pre-vote queue]
AVQ[active queue]
Trash(Proposal burned)
Proposal-- stake \npre-vote bond -->PVQ
Proposal-- stake \nactive queue bond-->AVQ
PVQ-- top up bond -->AVQ
PVQ-- receive \n#pre-vote support -->AVQ
PVQ-- get a support from a \nCongress member -->AVQ
PVQ-- timeout -->Trash
```
### Proposal Types
There are several types of proposals with specific functionalities and limitations:
1. **Dismiss Proposal**
- Arguments: `dao`: `AccountId`, `member`: `AccountId`
- Description: This proposal calls the `Dismiss` hook in the provided DAO when executed, resulting in the removal of the specified member.
2. **Dissolve Proposal**
- Arguments: `dao`: `AccountId`
- Description: Executing this proposal triggers the `Dissolve` hook in the provided DAO, dissolving the DAO itself.
3. **Veto Proposal**
- Arguments: `dao`: `AccountId`, `prop_id`: `u32`
- Description: When executed, this proposal invokes the `Veto` hook in the provided DAO and vetoes the proposal identified by the specified `prop_id`.
4. **Approve Budget Proposal**
- Arguments: `dao`: `AccountId`, `prop_id`: `u32`
- Description: This type of proposal serves as an approval mechanism for budget proposals without making any method calls.
5. **Text Proposal**
- Description: A text proposal for general purposes, without specific arguments. It doesn't involve any method calls.
6. **TextSuper Proposal**
- Description: same as `Text` proposal, but requires Near Supermajority Consent to approve.
7. **FunctionCall Proposal**
- Arguments: `receiver_id`: `AccountId`, `actions`: `Vec<ActionCall>`
- Description: This proposal enables you to call the `receiver_id` with a list of method names in a single promise. It allows your contract to execute various actions in other contracts, excluding congress contracts. Attempting to create a proposal that calls any congress DAOs will result in an error, preventing the proposal from being created.
8. **UpdateBonds**
- Arguments: `pre_vote_bond: U128`, `active_queue_bond: U128`
- Description: allows VB to update contract configuration.
9. **UpdateVoteDuration**
- Arguments: `pre_vote_duration: u64`, `vote_duration: u64`
- Description: allows VB to update contract configuration.
## Proposal Lifecycle
```mermaid
---
title: Possible Proposal Status Flows
---
flowchart TB
Trash([Trash])
PreVote --> InProgress
InProgress --> Approved
InProgress --> Rejected
InProgress --> Spam
Approved --> Executed
Executed -- tx fail --> Failed
Failed -- re-execute --> Executed
PreVote -- slashed --> Trash
Spam -- slashed --> Trash
```
When proposal is created, but the creator doesn't deposit `active_queue_bond` immediately, then the status of a proposal is `PreVote`.
A proposal that doesn't advance to the active queue by the `pre_vote_duration` is eligible for slashing. In such case, any account can call `slash_prevote_proposal(id)` method: the proposal will be removed, `SLASH_REWARD` will be transferred (as in incentive) to the caller and the remainder bond will be sent to the community fund.
Proposal, that is moved to the active queue has status `InProgress` and keeps that status until the voting period is over (`proposal.start_time + vote_duration`). During that time all Members can vote for the proposal.
Once the voting period is over, a proposal will have `Approved`, `Rejected` or `Spam` status, based on the voting result.
During this time, anyone can call `execute(id)`. Note these statuses are only visible when we query a proposal and: a) voting is over b) and was not executed. Executing a proposal will set the `proposal.executed_at` property to the current time in milliseconds and will have the following effects:
- Approved: bonds are returned. If a proposal involves a function call, then the call is scheduled. If the call fails, the proposal will have status `Failed` and anyone will be able to re-execute it again.
- Rejected: bonds are removed, and proposal won't be able to be re-executed.
- Spam: executor will receive a `SLASH_REWARD`, and the proposal will be slashed: removed, and the remaining bond (including the top-up) send to the community fund.
## Voting
Any VB member can vote on any _in progress_ proposal in the active queue. Voter can change his/her vote multiple times. Vote options:
- approve
- reject
- spam: strong conviction that the proposal is spam, should be removed and a deposit slashed.
A proposal voting is in progress when `now <= proposal.start_time + vote_duration`, where `proposal.start_time` is a time when the proposal is added to the active queue.
Syntax: #vote_type denotes number of votes of the specified type, eg: #approve means number of approve votes.
A proposal is **approved** when:
- voting time is over;
- AND consent is reached (quorum + threshold).
A proposal is marked as **spam** when:
- voting time is over;
- `#spam > #reject`;
- AND `#reject + #spam >= (1-threshold) * (#approve + #reject + #spam)`.
Spam proposals are removed, and the bond is slashed (sent to the community treasury).
A proposal is **rejected** if voting time is over (proposal is not in progress anymore), and it was not approved nor marked as spam.
Voting Body intentionally doesn't support optimistic execution, that is approving or rejecting a proposal once sufficient amount of votes are cast. We want to give a chance to every member vote and express their opinion providing more clear outcome of the voting.
Vote can only be made by an IAH verified account. We use `is_human_call_lock` method, which will lock the caller for soul transfers, to avoid double vote. Example call:
```shell
lock_duration=vote_duration+1 # minimum value is the time in milliseconds remaining to the voting end + 1.
near call IAH_REGISTRY is_human_call_lock \
'{"ctr": "VB.near", "function": "vote", "payload": "{\"prop_id\": 3, \"vote\": \"Approve\"}", "lock_duration": '$lock_duration', "with_proof": false}' \
--accountId YOU \
--deposit 0.01 # used for vote storage, reminder will be returned.
near call VOTING_BODY get_vote \
'{"id": 3, "voter": "YOU"}'
```
### Quorums and Thresholds
**Quorum** assures that enough of the VB members voted.
**Majority Threshold** assures that enough VB members approved a proposal. It is a fractional value. Proposal is approved when: `#approve > threshold * (#approve + #reject + #spam)`. It is either a simple majority or a super majority.
- **Near Consent:** quorum=(7% of the voting body) + **simple majority**=50%.
- **Near Supermajority Consent**: quorum=(12% of the voting body) + **super majority**=60%.
### Events
This smart contract emits several events to notify external systems or components about specific actions or state changes. Here's a breakdown of the events and the functions emitting them:
#### `proposal-create`
- **Description:** Emitted when a proposal is created.
- **Payload:**
- `prop_id`: The ID of the created proposal.
- `kind`: The kind of proposal.
- `active`: Set to true if the proposal was added to an active queue directly.
Functions that invoke `emit_prop_created`: `create_proposal`.
#### `proposal-activate`
- **Description:** Emitted when a proposal is moved from pre-vote to the active queue.
- **Payload:**
- `prop_id`: The ID of the activated proposal.
Functions that invoke `emit_prop_active`: `top_up_proposal`, `support_proposal`, `support_proposal_by_congress`.
#### `proposal-prevote-slash`
- **Description:** Emitted when a pre-vote proposal is removed and slashed for not getting enough support.
- **Payload:**
- `prop_id`: The ID of the slashed pre-vote proposal.
- `bond`: The bond amount being slashed (in `U128` format).
List of functions that invoke `emit_prevote_prop_slashed`: `top_up_proposal`, `slash_prevote_proposal`, `support_proposal`, `support_proposal_by_congress`.
#### `proposal-slash`
- **Description:** Emitted when a proposal is slashed.
- **Payload:**
- `prop_id`: The ID of the slashed proposal.
- `bond`: The bond amount being slashed (in `U128` format).
List of functions that invoke `emit_prop_slashed`: `execute`.
#### `vote`
- **Description:** Emitted when a vote is cast for a proposal.
- **Payload:**
- `prop_id`: The ID of the proposal being voted on.
List of functions that invoke `emit_vote`: `vote`.
#### `execute`
- **Description:** Emitted when a proposal is executed.
- **Payload:**
- `prop_id`: The ID of the executed proposal.
List of functions that invoke `emit_executed`: `on_execute`.
## Cheat Sheet
### Creating a Budget Approval proposal
1. HoM must create a Budget Proposal and approve it.
2. CoA must not veto it.
3. Once cooldown is over (cooldown starts once the proposal is internally approved), and it was not vetoed, then it's finalized.
4. Any human can can now create a VB Text proposal, referencing original HoM Budget proposal, example:
```shell
near call IAH_REGISTRY is_human_call \
'{"ctr": "VB.near", "function": "create_proposal", "payload": "{\"kind\": {\"ApproveBudget\": {\"dao\": \"HOM.near\", \"prop_id\": 12}}, \"description\": \"ADDITIONAL INFORMATION\"}"}' \
--accountId YOU \
--depositYocto $pre_vote_bond
```
5. Now we need to advance the proposal to the active queue. The easiest way is to ask any Congress member (HoM or other house) to support it. Below, `prop_id` must be the id of the proposal created above, `dao` must be the house address and the caller is member of (eg: `congress-hom-v1.ndc-gwg.near`).
```shell
near call VB support_proposal_by_congress \
'{"prop_id": 5, `dao`: "HOM"}' \
--accountId YOU
```
6. Share the proposal ID with others and ask the VB to vote.
### Slashing a proposal
Any proposal with _Spam_ status or _PreVote_ and being overdue (see [Proposal Lifecycle](#proposal-lifecycle) section) is slasheable. Any account can trigger a slash, and in exchange he will receive the [`SLASH_REWARD`](https://github.com/near-ndc/voting-v1/blob/master/voting_body/src/constants.rs#L5).
Slashing pre vote proposal:
```shell
near call VB slash_prevote_proposal '{"id": 5}' \
--accountId YOU
```
Slashing proposal in the active queue is as simple as executing it:
```shell
near call VB execute '{"id": 5}' \
--accountId YOU
```
# Congress
- [Diagrams](https://miro.com/app/board/uXjVMqJRr_U=/)
- [Framework Specification](https://near-ndc.notion.site/NDC-V1-Framework-V3-1-Updated-1af84fe7cc204087be70ea7ffee4d23f?pvs=4)
## Creating a Proposal
Each Congress house specifies which proposal kinds are allowed to be created. It is a subset of:
- `FunctionCall`: if approved, proposal execution will create a cross contract call.
- `Text`: text based proposal, no automated action is performed.
- `FundingRequest(Balance)`: request to fund a specific project. Balance is the amount of Near provided as funding. If Balance is bigger or equal than `big_funding_threshold` then it is eligible for `VetoBigOrReccurentFundingReq`. Proposal execution will fail if the total budget spend (including the one from the proposal) goes above the `contract.budget_cap`.
NOTE: The contract doesn't track the monthly budget limit. That should be tracked off-chain.
- `RecurrentFundingRequest(Balance)`: funding request that will renew every month until the end of the terms. The balance parameter is the size of the single month spending for this funding request. The proposal is eligible for
`VetoBigOrReccurentFundingReq`. Proposal execution will fail if the total budget spend (including the one from the proposal multiplied by the amount of remaining months) goes above the `contract.budget_cap`.
- `DismissAndBan(member, house)`: requests I Am Human registry to ban the member account (set `GovBan` flag in the IAH registry) and calls the dismiss hook on the house.
Each proposal comes with a description, which should provide motivation and a background.
### Cheat sheet
Below we present how to make a proposal for every possible Congress motion:
#### Veto
Veto is created by a separate account or DAO that has a permission to call the `veto_hook`. `VetoAll` permission allows to veto any proposal, while `VetoBigOrReccurentFundingReq` only allows to veto recurrent funding proposals or funding proposals above `big_funding_threshold`.
In NDC Gov v1 the following entities have permission to veto HoM proposals:
- `voting-body-v1.ndc-gwg.near`: `VetoBigOrReccurentFundingReq`
- `congress-coa-v1.ndc-gwg.near`: `VetoAl`
To create a veto within the congress houses, use the `create_proposal` function:
```json
near call congress-coa-v1.ndc-gwg.near create proposal '{
"kind": {
"FunctionCall": {
"receiver_id": "congress-hom-v1.ndc-gwg.near",
"actions": [
{
"method_name": "veto_hook",
"args": {"id": "proposal_id to be vetoed"},
"deposit": "100000000000000000000000",
"gas": "300000000000000"
}
]
}
},
"description": "Your description"
}' --accountId your_account.near
```
See also the `Voting Body` documentation.
#### Dismiss
To initiate a dismiss, the executing house must have `Dismiss` permission. In NDC Gov v1, the authority to dismiss any member of the `HoM` and `CoA` rests with the `TC` (Transparency Commision).
To propose a dismiss proposal, call the `create_proposal` function:
```json
near call congress-coa-v1.ndc-gwg.near create proposal '{
"kind": {
"FunctionCall": {
"receiver_id": "congress-hom-v1.ndc-gwg.near",
"actions": [
{
"method_name": "dismiss_hook",
"args": {"member": "member_to_dismiss.near"},
"deposit": "100000000000000000000000",
"gas": "300000000000000"
}
]
}
},
"description": "Your description"
}' --accountId your_account.near
```
#### Dismiss and Ban
To initiate a dismiss and ban action, the executing house must have `DismissAndBan` permission. In NDC Gov v1, the authority to dismiss any member of the `HoM` and `CoA` rests with the `TC` (Transparency Commision).
To propose a dismiss and ban proposal, call the `create_proposal` function:
```json
near call congress-tc-v1.ndc-gwg.near create proposal '{
"kind": {
"DismissAndBan": {
"member": "member_to_dismiss_and_ban.near",
"house": "congress-hom-v1.ndc-gwg.near",
},
},
"description": "Your description"
}' --accountId your_account.near
```
## Proposal Lifecycle
When a proposal is created it will have `InProgress` status and the `submission_time` will be set.
```mermaid
---
title: Possible Proposal Status Flows
---
flowchart TB
Create_Proposal --> InProgress
InProgress --> Approved
InProgress --> Rejected
InProgress --> Vetoed
Approved --> Executed
Approved --> Failed
Approved --> Vetoed
Failed -- re-execute --> Executed
```
### Voting
Any member can vote for any `InProgress` proposal. Members can't overwrite their votes. Proposal is in progress until:
- all votes were cast
- OR `vote_duration` passed
- OR `min_vote_duration` passed and the tally can be finalized (proposal reached min amount of approval votes or have enough abstain + reject votes to block the approval).
Example CLI command to vote for a proposal:
``` shell
# vote must be one of: "Approve", "Reject", "Abstain"
near call HOUSE vote '{"id": PROP_ID, "vote": "Approve"}' --accountId YOU
```
### Vetoing
Any proposal can be vetoed (even an in progress one) until the cooldown is over.
A DAO `A` can veto a proposal `P` of house `H` if:
- `P` cooldown is not over (is in progress, approved or rejected).
- `H` gives veto permission to `A`: `contract.hook_auth[A]` contains `VetoAll` or `VetoBigOrReccurentFundingReq`. The latter will only allow `A` to veto big funding proposals or recurrent funding proposals.
### Execution
Anyone (not only a house member) can execute a proposal when a proposal that is:
- min vote duration passed;
- cooldown is over;
- proposal is _approved_ or _failed_.
A proposal is **approved** when:
- is not in progress;
- AND got enough #approved votes (`>= contract.threshold`).
Proposal reaches _failed_ status when it was approved, but the execution failed. In that can be re-executed again.
If proposal execution breaks an invariant check (eg: crossing the budget cap), then the transaction will succeed and a composed error will be returned: the `Ok(Err(ExecRespErr::**))` of `Result<PromiseOrValue<Result<(), ExecRespErr>>, ExecError>` type.
Example CLI command to execute a proposal:
``` shell
near call HOUSE execute '{"id": PROP_ID}' --gas 300000000000000 --accountId YOU
```
## Queries
- `get_proposals`: Query all proposals
- `near view $CTR get_proposals '{"from_index": 0, "limit": 10}'`
- `get_proposal`: Query a specific proposal
- `near view $CTR get_proposal '{"id": 1}'`
- `number_of_proposals`: Query a specific proposal
- `near view $CTR number_of_proposals ''`
- `is_dissolved`: Check if contract is dissolved
- `near view $CTR is_dissolved ''`
- `get_members`: Query all members with permissions
- `near view $CTR get_members ''`
- `member_permissions`: Returns permissions for a specific member
- `near view $CTR member_permissions '{"member": "user.testnet"}'`
- `hook_permissions`: Returns permissions for a specific member
- `near view $CTR hook_permissions '{"user": "user.testnet"}'`
# Nominations
Smart contract for nominations.
[Specification](https://near-ndc.notion.site/Nominations-b4281e30ac4e44cfbd894f0e2443bc88?pvs=4)
Smart contract is primally used for NDC v1 Elections, but can be used also for other use cases (eg Kudos).
## Transactions
- `self_nominate(house: HouseType, comment: String,link: Option<String>)` - allows OG members to submit a nomination.
- `self_revoke()` - enables candidates to revoke their nomination.
- `upvote(candidate: AccountId)` - enables IAH token holders to upvote existing nominations.
- `remove_upvote(candiate: AccountId)` - removes the upvote from the caller for the specified candidate.
- `comment(candidate: AccountId, comment: String)` - enables IAH token holders to comment on existing nominations
## Queries
- `nominations(&self, house: HouseType) -> Vec<(AccountId, u32)>` - returns all the nominations for the given house with the numbers of upvotes received eg. `[("candidate1.near", 16), ("candidate2.near", 5), ...]`.
Comment and upvote queries should be go through an indexer.
## Deployed Contracts
### Mainnet Production
**nominations.ndc-gwg.near** @ nominations/v1.0.0
```yaml
sbt_registry: registry.i-am-human.near,
og_sbt: ["community.i-am-human.near", 1],
start_time: 1689778800000,
end_time: 1694995199000
```
### Mainnet Testing
**nominations-v1.gwg-testing.near** @ nominations/v1.0.0
```yaml
sbt_registry: registry-v1.gwg-testing.near,
iah_issuer: fractal.i-am-human.near,
og_sbt: [fractal.i-am-human.near, 2],
start_time: 1687792608708,
end_time: 1787792508708
```
### Testnet
- **nominations-v1**: `nominations-v1.gwg.testnet`, initialized with values:
```yaml
sbt_registry: registry-unstable.i-am-human.testnet,
iah_issuer: i-am-human-staging.testnet,
og_class: 1,
og_issuer: community-v1.i-am-human.testnet,
start_time: 0,
end_time: 1844674407370955300`
```
# NDC v1 Smart Contracts
In NDC v1, there will be only two mechanisms to vote: simple proposal voting and elections. Both are based on stake weight.
- Details about the Framework: [near-ndc/gov](https://github.com/near-ndc/gov).
This repository provides smart contracts for NDC v1 Voting Body.
## Proposal types
| Proposal | Voting Entity | Contract |
| :------------------------------------------- | :------------ | :---------- |
| Elect house representatives | Voting Body | elections |
| Constitution ratification | Voting Body | voting body |
| Dissolve a house and call for new elections | Voting Body | voting body |
| Setup Package | Voting Body | voting body |
| Budget ratification | Voting Body | voting body |
| Veto HoM Recurrent and Big Funding Proposals | Voting Body | voting body |
| Budget | HoM | congress |
| Transfer Funds | HoM | congress |
| Funding proposal | HoM | congress |
| Veto any HoM proposal | CoA | congress |
| Reinstate representative | TC / CoA | congress |
| Investigate | TC | congress |
| Remove representative | TC | congress |
In NDC v1, Voting Body can't make proposal for budget management. They can only veto budget proposals.
### General voting rules
- user can only vote for active proposals
- user can not overwrite his vote
### Elections
Elections for NDC v1 Houses.
๐ [**Voting Process**](https://github.com/near-ndc/gov/blob/main/framework-v1/elections-voting.md)
### Voting Body
Voting Body is set of human verified NEAR accounts constituting NDC.
Voting mechanisms as well as Powers, Checks and Balances of the Voting Body is described in the [NDC Gov v1 Framework](https://github.com/near-ndc/gov/blob/main/framework-v1/gov-framework.md).
- Propose and approve HoM **setup package**: a request to deploy funds from the [Community Treasury](https://github.com/near-ndc/gov/blob/main/framework-v1/community-treasury.md) to HoM DAO.
- **Voting Body Veto** is a special proposal to veto other proposal made by a house. When a HoM or CoA proposal will pass it must not be executed immediately. There must be an challenge period, where a Voting Body or the TC can stop the proposal execution by successfully submitting a Veto proposal.
# Elections Smart Contract
## Deployments
| environment | address |
| :-------------: | --------------------------------: |
| mainnet prod | `elections.ndc-gwg.near` |
| mainnet testing | `elections-v1-1.gwg-testing.near` |
| testnet | `elections-v1.gwg.testnet` |
## Requirements
- Only I Am Human verified accounts can vote.
- Each account can vote at most one time. Votes are not revocable, and can't be changed.
- Contract has a fair voting `policy` attribute. Each user, before voting, has to firstly accept the policy by making a transaction matching the contract policy.
- Only the authority (set during contract initialization) can create proposals. Each proposal specifies:
- `typ`: must be HouseType variant
- `start`: voting start time as UNIX time (in miliseconds)
- `end`: voting start time as UNIX time (in miliseconds)
- `cooldown`: cooldown duration when votes from blacklisted accounts can be revoked by an authority (in miliseconds)
- `ref_link`: string (can't be empty) - a link to external resource with more details (eg near social post). Max length is 120 characters.
- `quorum`: minimum amount of legit accounts to vote to legitimize the elections.
- `seats`: max number of candidates to elect, also max number of credits each user has when casting a vote.
- `min_candidate_support`: minimum amount of votes a candidate needs to receive to be considered a winner.
## Flow
- GWG deploys the elections smart contract and sets authority for creating new proposals.
- GWG authority creates new proposals before the election starts, with eligible candidates based on the `nominations` result. All proposals are created before the elections start.
- NOTE: we may consider querying the candidates directly from the nominations contract.
- Once the proposals are created and the elections start (`now >= proposal.start`), all human verified near accounts can vote according to the NDC Elections [v1 Framework](../README.md#elections).
- Anyone can query the proposal and the ongoing result at any time.
- Voting is active until the `proposal.end` time.
- Vote revocation is active until the `proposal.end` + `cooldown` time.
## Bonding
- [SPEC](https://github.com/near-ndc/gov/blob/main/framework-v1/elections-voting.md#bonding)
- Each verified voter must bond 3N to cast their vote. Each Non-verified voter must bond 300N to cast their vote.
- Bond can be deposited using `bond` function that must be used via is_human_call.
```rust
near call REGISTRY is_human_call '{"ctr": "elections.near", "function": "bond", "payload": "{}"}' --accountId YOU.near --deposit 3
```
- One bond is enough to cast votes for all proposals.
- `finish_time`: max(`finish_time`, `end` + `cooldown`) of all the proposals.
- User can unbond after the `finish_time`. All tokens minus storage fees will be returned.
- Bonded tokens can be slashed by executing `vote_revoke`. 100% of bonded tokens will be slashed and will be tracked in `total_slashed` variable.
- `unbond`: To unbond deposit, unbond function needs to be called via IAH `registry.is_human_call`.
```rust
near call REGISTRY is_human_call '{"ctr": "elections.near", "function": "unbond", "payload": "{}"}' --accountId YOU.near
```
The `unbond` will also mint I VOTED SBT for [eligible voters](https://github.com/near-ndc/gov/blob/main/framework-v1/elections-voting.md#i-voted-sbt).
## Voting
User who made sufficient bond and accepted Fair Voting Policy can call `vote` function to vote for an active proposal.
User can vote at most once for each proposal, votes can not be updated. [Full specification](https://github.com/near-ndc/gov/blob/main/framework-v1/elections-voting.md)
### Setup Package
Setup Package proposal is a proposal with `seats=1` (at most one option can be selected) and `candidates = ["yes", "no", "abstain"]`.
Voting for setup package uses the same API as voting for candidates. The vote must be list of exactly one element: `["yes"]` or `["no"]` or `["abstain"]`.
## Usage
Below we show few CLI snippets:
```shell
CTR=elections-v1.gwg.testnet
REGISTRY=registry-1.i-am-human.testnet
# create proposal
# note: start time, end time and cooldown must be in milliseconds
near call $CTR create_proposal '{"start": 1686221747000, "end": 1686653747000, "cooldown": 604800000 "ref_link": "example.com", "quorum": 10, "candidates": ["candidate1.testnet", "candidate2.testnet", "candidate3.testnet", "candidate4.testnet"], "typ": "HouseOfMerit", "seats": 3, "min_candidate_support": 5}' --accountId $CTR
# fetch all proposal
near view $CTR proposals ''
# query proposal by ID
near view $CTR proposals '{"prop_id": 2}'
# accept fair voting policy
near call $CTR accept_fair_voting_policy '{"policy": "f1c09f8686fe7d0d798517111a66675da0012d8ad1693a47e0e2a7d3ae1c69d4"}' --deposit 0.001 --accountId me.testnet
# query the accepted policy by user. Returns the latest policy user accepted or `None` if user did not accept any policy
near call $CTR accepted_policy '{"user": "alice.testnet"}' --accountId me.testnet
# bonding - see a section above how to bond and unbond
# query if a IAH holder bonded (by IAH SBT)
near view $CTR has_voted_on_all_proposals '{"sbt": 123}'
# vote
near call $CTR vote '{"prop_id": 1, "vote": ["candidate1.testnet", "candidate3.testnet"]}' --gas 70000000000000 --deposit 0.0005 --accountId me.testnet
# revoke vote (authority only)
near call $CTR admin_revoke_vote '{"prop_id": 1, "token_id": 1}'
# revoke vote (anyone can call this method)
near call $CTR revoke_vote '{"prop_id": 1, "user": "alice.testnet"}'
# check if a user voted for all proposals (note user votes with SBTs, so it may happen that
# we should query by TokenID instead)
near view $CTR has_voted_on_all_proposals '{"user": "alice.testnet"}'
# query winners by a proposal
# NOTE: the function doesn't return "ongoing" winners, it only returns a valid response once
# the proposal finished (voting ended and is past the cooldown).
near view $CTR winners_by_proposal '{"prop_id": 1}'
```
## Deployed Contracts
### Mainnet
Coming Soon
- mainnet testing: `elections-v1.gwg-testing.near` - [deployment tx](https://explorer.mainnet.near.org/transactions/k8CYckfdqrubJovPTX8UreZkdxgwxkxjaFTv955aJbS)
registry: `registry-v1.gwg-testing.near`
### Testnet
- `elections-v1.gwg.testnet` - [deployment tx](https://explorer.testnet.near.org/transactions/6mQVLLsrEkBithTf1ys36SHCUAhDK9gVDEyCrgV1VWoR).
registry: `registry-1.i-am-human.testnet`
# Set of common functions and structures
- event handling
|
Peersyst_symbol-file-system | README.md
example
css
global.css
index.html
js
alert.js
index.ts
package-lock.json
package.json
src
IFileSystem.ts
SymbolFileSystem.ts
Synchronizer.ts
cli
Clone.ts
Push.ts
Questions.ts
index.ts
entity
Blocks.ts
Directory.ts
File.ts
NodeType.ts
helper
FileHelper.ts
Path.ts
Progress.ts
sleep.ts
service
DividerService.ts
EncodingService.ts
FileSystemTableService.ts
SymbolService.ts
test
SymbolFileSystem.ts
Synchronizer.ts
service
EncodingService.ts
FileSystemTableService.ts
tsconfig.json
| # Symbol File System
[](https://opensource.org/licenses/Apache-2.0)
Symbol File System is a tool that allows you to create, read update and delete files and directories
inside the Symbol blockchain
## Installation
Use the package manager [npm](https://www.npmjs.com/) to install symbol file system.
Development environment
```bash
npm install symbol-file-system
```
Global cli environment
```bash
npm install symbol-file-system -g
```
## Usage
### symbol-fs CLI
symbol-fs CLI allows cloning and pushing remote and directories to the Symbol blockchain.
The CLI has an interactive mode so there's no need to specify all the parameters at the beginning.
#### Clone a directory:
```shell
$ sfs clone -a TDXKGLNBCVXIB5QIPDLX2QB4VIRQ54YEG2IJIXY -d ./localdir
```
Parameters:
- address [-a]: Specify the address of the remote directory
- directory [-d]: Specify the local directory to store the downloaded files
- node [-n]: Specify a symbol node to connect
#### Push a directory
```shell
$ sfs push -a TDXKGLNBCVXIB5QIPDLX2QB4VIRQ54YEG2IJIXY -d ./localdir
```
Parameters:
- address [-a]: Specify the address of the remote directory
- directory [-d]: Specify the remote directory where the files will be uploaded
- node [-n]: Specify a symbol node to connect
- file [-f]: File system private key of the address specified above
- payer [-p]: Payer private key that will assume the cost of the network fees
### SymbolFileSystem
SymbolFileSystem class allows to work in the file system using the following calls:
```typescript
import {SymbolFileSystem} from "../src/SymbolFileSystem";
const symbolFileSystem = new SymbolFileSystem(address, nodes, async () => {
console.log("I am ready to start using the Symbol file system!");
// Create a directory
await symbolFileSystem.mkdir("/data");
// Write a file to the directory
await symbolFileSystem.writeFile("/data/notes.txt", myNotesFileBuffer);
// Read a file from a directory
await symbolFileSystem.readFile("/data/notes.txt");
// Remove a file
await symbolFileSystem.removeFile("/trash.png");
// Commit changes to the Symbol blockchain
await symbolFileSystem.save(fileAccount, payerAccount);
});
```
### Synchronizer
Synchronizer class allows to automatically synchronize a remote and a local directories
```typescript
import {Synchronizer} from "../src/Synchronizer";
const symbolFileSystem = new SymbolFileSystem(account.address, nodes, async () => {
const synchronizer = new Synchronizer(symbolFileSystem, "./example");
// Upload all the files from the ./example directory to the chain
await synchronizer.up(account, payerAccount);
// Download all the files from the chain to the ./example directory
await synchronizer.clone();
});
```
## Contributing
This project is being build. Pull requests and new ideas are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate.
|
esaminu_console-boilerplate-temsasdapasdlate-rs-ss25dfghaafdghdfhg | .github
scripts
runfe.sh
workflows
deploy-to-console.yml
readme.yml
tests.yml
.gitpod.yml
README.md
contract
README.md
build.sh
deploy.sh
package-lock.json
package.json
src
contract.ts
model.ts
utils.ts
tsconfig.json
integration-tests
package-lock.json
package.json
src
main.ava.ts
package-lock.json
package.json
| # Donation Contract
The smart contract exposes methods to handle donating $NEAR to a `beneficiary`.
```ts
@call
donate() {
// Get who is calling the method and how much $NEAR they attached
let donor = near.predecessorAccountId();
let donationAmount: bigint = near.attachedDeposit() as bigint;
let donatedSoFar = this.donations.get(donor) === null? BigInt(0) : BigInt(this.donations.get(donor) as string)
let toTransfer = donationAmount;
// This is the user's first donation, lets register it, which increases storage
if(donatedSoFar == BigInt(0)) {
assert(donationAmount > STORAGE_COST, `Attach at least ${STORAGE_COST} yoctoNEAR`);
// Subtract the storage cost to the amount to transfer
toTransfer -= STORAGE_COST
}
// Persist in storage the amount donated so far
donatedSoFar += donationAmount
this.donations.set(donor, donatedSoFar.toString())
// Send the money to the beneficiary
const promise = near.promiseBatchCreate(this.beneficiary)
near.promiseBatchActionTransfer(promise, toTransfer)
// Return the total amount donated so far
return donatedSoFar.toString()
}
```
<br />
# Quickstart
1. Make sure you have installed [node.js](https://nodejs.org/en/download/package-manager/) >= 16.
2. Install the [`NEAR CLI`](https://github.com/near/near-cli#setup)
<br />
## 1. Build and Deploy the Contract
You can automatically compile and deploy the contract in the NEAR testnet by running:
```bash
npm run deploy
```
Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed:
```bash
cat ./neardev/dev-account
# e.g. dev-1659899566943-21539992274727
```
The contract will be automatically initialized with a default `beneficiary`.
To initialize the contract yourself do:
```bash
# Use near-cli to initialize contract (optional)
near call <dev-account> init '{"beneficiary":"<account>"}' --accountId <dev-account>
```
<br />
## 2. Get Beneficiary
`beneficiary` is a read-only method (`view` method) that returns the beneficiary of the donations.
`View` methods can be called for **free** by anyone, even people **without a NEAR account**!
```bash
near view <dev-account> beneficiary
```
<br />
## 3. Get Number of Donations
`donate` forwards any attached money to the `beneficiary` while keeping track of it.
`donate` is a payable method for which can only be invoked using a NEAR account. The account needs to attach money and pay GAS for the transaction.
```bash
# Use near-cli to donate 1 NEAR
near call <dev-account> donate --amount 1 --accountId <account>
```
**Tip:** If you would like to `donate` using your own account, first login into NEAR using:
```bash
# Use near-cli to login your NEAR account
near login
```
and then use the logged account to sign the transaction: `--accountId <your-account>`.
# Donation ๐ธ
[](https://docs.near.org/tutorials/welcome)
[](https://gitpod.io/#/https://github.com/near-examples/donation-js)
[](https://docs.near.org/develop/contracts/anatomy)
[](https://docs.near.org/develop/integrate/frontend)
[](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.

# 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).
|
NEAR-Edu_contract-registry-ci-test | .circleci
config.yml
checkout.txt
path.txt
repository.txt
| |
Learn-NEAR_NCD--tic-tac-toe | 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>
```
|
jboetticher_NEARFiefdom-smart-contracts | .openzeppelin
rinkeby.json
unknown-31337.json
README.md
hardhat.config.js
package-lock.json
package.json
scripts
ResourceGenerator
mintTile.js
upgradeBuilding.js
withdraw.js
contract-deployment.js
fd-up-deployment.js
test
resourceGenerator.js
| # NEAR Fiefdom Smart Contracts
Smart contracts for the decentralized city builder game NEAR Fiefdom, built for Aurora.
```
npm install
```
Try running some of the following tasks:
```shell
npx hardhat accounts
npx hardhat compile
npx hardhat clean
npx hardhat test
npx hardhat node
node scripts/sample-script.js
npx hardhat help
```
|
jeKnowledge_near-bot | README.md
contract dentro
Cargo.toml
README.md
build.sh
src
lib.rs
contract
Cargo.toml
README.md
build.sh
del_build.sh
src
approval.rs
enumeration.rs
internal.rs
lib.rs
metadata.rs
mint.rs
nft_core.rs
royalty.rs
neardev
shared-test
test.near.json
node_modules
.bin
sha.js
.package-lock.json
@ampproject
remapping
README.md
dist
remapping.umd.js
types
build-source-map-tree.d.ts
remapping.d.ts
source-map-tree.d.ts
source-map.d.ts
types.d.ts
package.json
@babel
code-frame
README.md
lib
index.js
package.json
compat-data
README.md
corejs2-built-ins.js
corejs3-shipped-proposals.js
data
corejs2-built-ins.json
corejs3-shipped-proposals.json
native-modules.json
overlapping-plugins.json
plugin-bugfixes.json
plugins.json
native-modules.js
overlapping-plugins.js
package.json
plugin-bugfixes.js
plugins.js
core
README.md
lib
config
cache-contexts.js
caching.js
config-chain.js
config-descriptors.js
files
configuration.js
import-meta-resolve.js
import.js
index-browser.js
index.js
module-types.js
package.js
plugins.js
types.js
utils.js
full.js
helpers
config-api.js
deep-array.js
environment.js
index.js
item.js
partial.js
pattern-to-regex.js
plugin.js
printer.js
resolve-targets-browser.js
resolve-targets.js
util.js
validation
option-assertions.js
options.js
plugins.js
removed.js
gensync-utils
async.js
fs.js
index.js
parse.js
parser
index.js
util
missing-plugin-helper.js
tools
build-external-helpers.js
transform-ast.js
transform-file-browser.js
transform-file.js
transform.js
transformation
block-hoist-plugin.js
file
file.js
generate.js
merge-map.js
index.js
normalize-file.js
normalize-opts.js
plugin-pass.js
util
clone-deep.js
vendor
import-meta-resolve.js
package.json
src
config
files
index-browser.ts
index.ts
resolve-targets-browser.ts
resolve-targets.ts
transform-file-browser.ts
transform-file.ts
generator
README.md
lib
buffer.js
generators
base.js
classes.js
expressions.js
flow.js
index.js
jsx.js
methods.js
modules.js
statements.js
template-literals.js
types.js
typescript.js
index.js
node
index.js
parentheses.js
whitespace.js
printer.js
source-map.js
node_modules
@jridgewell
gen-mapping
README.md
dist
gen-mapping.umd.js
types
gen-mapping.d.ts
sourcemap-segment.d.ts
types.d.ts
package.json
src
gen-mapping.ts
sourcemap-segment.ts
types.ts
package.json
helper-annotate-as-pure
README.md
lib
index.js
package.json
helper-builder-binary-assignment-operator-visitor
README.md
lib
index.js
package.json
helper-compilation-targets
README.md
lib
debug.js
filter-items.js
index.js
options.js
pretty.js
targets.js
types.js
utils.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-polyfill-provider
README.md
lib
browser
dependencies.js
debug-utils.js
define-provider.js
imports-cache.js
index.js
meta-resolver.js
node
dependencies.js
normalize-options.js
types.js
utils.js
visitors
entry.js
index.js
usage.js
package.json
src
browser
dependencies.js
node
dependencies.js
helper-environment-visitor
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-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-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-validator-option
README.md
lib
find-suggestion.js
index.js
validator.js
package.json
helper-wrap-function
README.md
lib
index.js
package.json
helpers
README.md
lib
helpers-generated.js
helpers.js
helpers
applyDecs.js
asyncIterator.js
jsx.js
objectSpread2.js
regeneratorRuntime.js
typeof.js
wrapRegExp.js
index.js
package.json
scripts
generate-helpers.js
generate-regenerator-runtime.js
package.json
highlight
README.md
lib
index.js
package.json
parser
CHANGELOG.md
README.md
bin
babel-parser.js
lib
index.js
package.json
typings
babel-parser.d.ts
plugin-bugfix-safari-id-destructuring-collision-in-function-expression
README.md
lib
index.js
package.json
plugin-bugfix-v8-spread-parameters-in-optional-chaining
README.md
lib
index.js
package.json
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-class-static-block
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-private-property-in-object
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-class-properties
README.md
lib
index.js
package.json
plugin-syntax-class-static-block
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-import-assertions
README.md
lib
index.js
package.json
src
index.ts
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-private-property-in-object
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-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-display-name
README.md
lib
index.js
package.json
plugin-transform-react-jsx-development
README.md
lib
index.js
package.json
plugin-transform-react-jsx
README.md
lib
create-plugin.js
development.js
index.js
package.json
plugin-transform-react-pure-annotations
README.md
lib
index.js
package.json
plugin-transform-regenerator
README.md
lib
index.js
package.json
plugin-transform-reserved-words
README.md
lib
index.js
package.json
plugin-transform-shorthand-properties
README.md
lib
index.js
package.json
plugin-transform-spread
README.md
lib
index.js
package.json
plugin-transform-sticky-regex
README.md
lib
index.js
package.json
plugin-transform-template-literals
README.md
lib
index.js
package.json
plugin-transform-typeof-symbol
README.md
lib
index.js
package.json
plugin-transform-unicode-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
core-js-compat.js
corejs2-built-ins.js
corejs2-built-ins.json.js
package.json
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
babel-polyfill.js
regenerator.js
utils.js
shipped-proposals.js
targets-parser.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
preset-react
README.md
lib
index.js
package.json
runtime
README.md
helpers
AsyncGenerator.js
AwaitValue.js
applyDecoratedDescriptor.js
applyDecs.js
arrayLikeToArray.js
arrayWithHoles.js
arrayWithoutHoles.js
assertThisInitialized.js
asyncGeneratorDelegate.js
asyncIterator.js
asyncToGenerator.js
awaitAsyncGenerator.js
checkPrivateRedeclaration.js
classApplyDescriptorDestructureSet.js
classApplyDescriptorGet.js
classApplyDescriptorSet.js
classCallCheck.js
classCheckPrivateStaticAccess.js
classCheckPrivateStaticFieldDescriptor.js
classExtractFieldDescriptor.js
classNameTDZError.js
classPrivateFieldDestructureSet.js
classPrivateFieldGet.js
classPrivateFieldInitSpec.js
classPrivateFieldLooseBase.js
classPrivateFieldLooseKey.js
classPrivateFieldSet.js
classPrivateMethodGet.js
classPrivateMethodInitSpec.js
classPrivateMethodSet.js
classStaticPrivateFieldDestructureSet.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
applyDecs.js
arrayLikeToArray.js
arrayWithHoles.js
arrayWithoutHoles.js
assertThisInitialized.js
asyncGeneratorDelegate.js
asyncIterator.js
asyncToGenerator.js
awaitAsyncGenerator.js
checkPrivateRedeclaration.js
classApplyDescriptorDestructureSet.js
classApplyDescriptorGet.js
classApplyDescriptorSet.js
classCallCheck.js
classCheckPrivateStaticAccess.js
classCheckPrivateStaticFieldDescriptor.js
classExtractFieldDescriptor.js
classNameTDZError.js
classPrivateFieldDestructureSet.js
classPrivateFieldGet.js
classPrivateFieldInitSpec.js
classPrivateFieldLooseBase.js
classPrivateFieldLooseKey.js
classPrivateFieldSet.js
classPrivateMethodGet.js
classPrivateMethodInitSpec.js
classPrivateMethodSet.js
classStaticPrivateFieldDestructureSet.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
identity.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
regeneratorRuntime.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
writeOnlyError.js
extends.js
get.js
getPrototypeOf.js
identity.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
regeneratorRuntime.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
writeOnlyError.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
generated
asserts.js
validators.js
virtual-types.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
traverse-node.js
types.js
visitors.js
package.json
scripts
generators
asserts.js
validators.js
virtual-types.js
package.json
types
README.md
lib
asserts
assertNode.js
generated
index.js
ast-types
generated
index.js
builders
flow
createFlowUnionType.js
createTypeAnnotationBasedOnTypeof.js
generated
index.js
uppercase.js
react
buildChildren.js
typescript
createTSUnionType.js
validateNode.js
clone
clone.js
cloneDeep.js
cloneDeepWithoutLoc.js
cloneNode.js
cloneWithoutLoc.js
comments
addComment.js
addComments.js
inheritInnerComments.js
inheritLeadingComments.js
inheritTrailingComments.js
inheritsComments.js
removeComments.js
constants
generated
index.js
index.js
converters
ensureBlock.js
gatherSequenceExpressions.js
toBindingIdentifierName.js
toBlock.js
toComputedKey.js
toExpression.js
toIdentifier.js
toKeyAlias.js
toSequenceExpression.js
toStatement.js
valueToNode.js
definitions
core.js
experimental.js
flow.js
index.js
jsx.js
misc.js
placeholders.js
typescript.js
utils.js
index-legacy.d.ts
index.d.ts
index.js
modifications
appendToMemberExpression.js
flow
removeTypeDuplicates.js
inherits.js
prependToMemberExpression.js
removeProperties.js
removePropertiesDeep.js
typescript
removeTypeDuplicates.js
retrievers
getBindingIdentifiers.js
getOuterBindingIdentifiers.js
traverse
traverse.js
traverseFast.js
utils
inherit.js
react
cleanJSXElementLiteralChild.js
shallowEqual.js
validators
buildMatchMemberExpression.js
generated
index.js
is.js
isBinding.js
isBlockScoped.js
isImmutable.js
isLet.js
isNode.js
isNodesEquivalent.js
isPlaceholderType.js
isReferenced.js
isScope.js
isSpecifierDefault.js
isType.js
isValidES3Identifier.js
isValidIdentifier.js
isVar.js
matchesPattern.js
react
isCompatTag.js
isReactComponent.js
validate.js
package.json
scripts
generators
asserts.js
ast-types.js
builders.js
constants.js
docs.js
flow.js
typescript-legacy.js
validators.js
package.json
utils
formatBuilderName.js
lowerFirst.js
stringifyValidator.js
toFunctionName.js
@cspotcode
source-map-support
LICENSE.md
README.md
browser-source-map-support.js
node_modules
@jridgewell
trace-mapping
README.md
dist
trace-mapping.umd.js
types
any-map.d.ts
binary-search.d.ts
by-source.d.ts
resolve.d.ts
sort.d.ts
sourcemap-segment.d.ts
strip-filename.d.ts
trace-mapping.d.ts
types.d.ts
package.json
package.json
register-hook-require.d.ts
register-hook-require.js
register.d.ts
register.js
source-map-support.d.ts
source-map-support.js
@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
node_modules
ansi-styles
index.d.ts
index.js
package.json
readme.md
chalk
index.d.ts
package.json
readme.md
source
index.js
templates.js
util.js
has-flag
index.d.ts
index.js
package.json
readme.md
supports-color
browser.js
index.js
package.json
readme.md
package.json
@jridgewell
gen-mapping
README.md
dist
gen-mapping.umd.js
types
gen-mapping.d.ts
sourcemap-segment.d.ts
types.d.ts
package.json
resolve-uri
README.md
dist
resolve-uri.umd.js
types
resolve-uri.d.ts
package.json
src
resolve-uri.ts
set-array
README.md
dist
set-array.umd.js
types
set-array.d.ts
package.json
src
set-array.ts
source-map
README.md
dist
source-map.umd.js
types
source-map.d.ts
node_modules
@jridgewell
gen-mapping
README.md
dist
gen-mapping.umd.js
types
gen-mapping.d.ts
sourcemap-segment.d.ts
types.d.ts
package.json
src
gen-mapping.ts
sourcemap-segment.ts
types.ts
package.json
sourcemap-codec
README.md
dist
sourcemap-codec.umd.js
types
sourcemap-codec.d.ts
package.json
src
sourcemap-codec.ts
trace-mapping
README.md
dist
trace-mapping.umd.js
types
any-map.d.ts
binary-search.d.ts
by-source.d.ts
resolve.d.ts
sort.d.ts
sourcemap-segment.d.ts
strip-filename.d.ts
trace-mapping.d.ts
types.d.ts
package.json
src
any-map.ts
binary-search.ts
by-source.ts
resolve.ts
sort.ts
sourcemap-segment.ts
strip-filename.ts
trace-mapping.ts
types.ts
@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
node_modules
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
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
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
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
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
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
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
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
@lezer
common
README.md
dist
index.d.ts
index.js
mix.d.ts
parse.d.ts
tree.d.ts
package.json
lr
README.md
dist
constants.d.ts
decode.d.ts
index.d.ts
index.js
parse.d.ts
stack.d.ts
token.d.ts
package.json
@lmdb
lmdb-darwin-arm64
README.md
index.js
package.json
@mischnic
json-sourcemap
README.md
dist
index.d.ts
index.js
package.json
@msgpackr-extract
msgpackr-extract-darwin-arm64
README.md
index.js
package.json
@nodelib
fs.scandir
README.md
out
adapters
fs.d.ts
fs.js
constants.d.ts
constants.js
index.d.ts
index.js
providers
async.d.ts
async.js
common.d.ts
common.js
sync.d.ts
sync.js
settings.d.ts
settings.js
types
index.d.ts
index.js
utils
fs.d.ts
fs.js
index.d.ts
index.js
package.json
fs.stat
README.md
out
adapters
fs.d.ts
fs.js
index.d.ts
index.js
providers
async.d.ts
async.js
sync.d.ts
sync.js
settings.d.ts
settings.js
types
index.d.ts
index.js
package.json
fs.walk
README.md
out
index.d.ts
index.js
providers
async.d.ts
async.js
index.d.ts
index.js
stream.d.ts
stream.js
sync.d.ts
sync.js
readers
async.d.ts
async.js
common.d.ts
common.js
reader.d.ts
reader.js
sync.d.ts
sync.js
settings.d.ts
settings.js
types
index.d.ts
index.js
package.json
@parcel
bundler-default
lib
DefaultBundler.js
package.json
src
DefaultBundler.js
cache
index.d.ts
lib
FSCache.js
IDBCache.browser.js
IDBCache.js
LMDBCache.js
index.js
types.d.ts
types.js
package.json
src
FSCache.js
IDBCache.browser.js
IDBCache.js
LMDBCache.js
index.js
types.js
codeframe
node_modules
ansi-styles
index.d.ts
index.js
package.json
readme.md
chalk
index.d.ts
package.json
readme.md
source
index.js
templates.js
util.js
has-flag
index.d.ts
index.js
package.json
readme.md
supports-color
browser.js
index.js
package.json
readme.md
package.json
src
codeframe.js
test
codeframe.test.js
fixtures
a.js
compressor-raw
lib
RawCompressor.js
package.json
src
RawCompressor.js
config-default
index.json
package.json
test
config.test.js
core
index.d.ts
lib
AssetGraph.js
BundleGraph.js
CommittedAsset.js
Dependency.js
Environment.js
InternalConfig.js
PackagerRunner.js
Parcel.js
ParcelConfig.js
ParcelConfig.schema.js
ReporterRunner.js
RequestTracker.js
TargetDescriptor.schema.js
Transformation.js
UncommittedAsset.js
Validation.js
applyRuntimes.js
assetUtils.js
buildCache.js
constants.js
dumpGraphToGraphViz.js
index.js
loadDotEnv.js
loadParcelPlugin.js
projectPath.js
public
Asset.js
Bundle.js
BundleGraph.js
BundleGroup.js
Config.js
Dependency.js
Environment.js
MutableBundleGraph.js
PluginOptions.js
Symbols.js
Target.js
requests
AssetGraphRequest.js
AssetRequest.js
BundleGraphRequest.js
ConfigRequest.js
DevDepRequest.js
EntryRequest.js
PackageRequest.js
ParcelBuildRequest.js
ParcelConfigRequest.js
PathRequest.js
TargetRequest.js
ValidationRequest.js
WriteBundleRequest.js
WriteBundlesRequest.js
resolveOptions.js
serializer.js
serializerCore.browser.js
serializerCore.js
summarizeRequest.js
types.js
utils.js
worker.js
node_modules
semver
CHANGELOG.md
README.md
package.json
semver.js
package.json
src
AssetGraph.js
BundleGraph.js
CommittedAsset.js
Dependency.js
Environment.js
InternalConfig.js
PackagerRunner.js
Parcel.js
ParcelConfig.js
ParcelConfig.schema.js
ReporterRunner.js
RequestTracker.js
TargetDescriptor.schema.js
Transformation.js
UncommittedAsset.js
Validation.js
applyRuntimes.js
assetUtils.js
buildCache.js
constants.js
dumpGraphToGraphViz.js
index.js
loadDotEnv.js
loadParcelPlugin.js
projectPath.js
public
Asset.js
Bundle.js
BundleGraph.js
BundleGroup.js
Config.js
Dependency.js
Environment.js
MutableBundleGraph.js
PluginOptions.js
Symbols.js
Target.js
requests
AssetGraphRequest.js
AssetRequest.js
BundleGraphRequest.js
ConfigRequest.js
DevDepRequest.js
EntryRequest.js
PackageRequest.js
ParcelBuildRequest.js
ParcelConfigRequest.js
PathRequest.js
TargetRequest.js
ValidationRequest.js
WriteBundleRequest.js
WriteBundlesRequest.js
resolveOptions.js
serializer.js
serializerCore.browser.js
serializerCore.js
summarizeRequest.js
types.js
utils.js
worker.js
test
AssetGraph.test.js
BundleGraph.test.js
EntryRequest.test.js
Environment.test.js
InternalAsset.test.js
PackagerRunner.test.js
Parcel.test.js
ParcelConfig.test.js
ParcelConfigRequest.test.js
PublicAsset.test.js
PublicBundle.test.js
PublicDependency.test.js
PublicMutableBundleGraph.test.js
RequestTracker.test.js
TargetRequest.test.js
fixtures
application-targets
package.json
bundle.js
common-targets-ignore
package.json
common-targets
package.json
context
package.json
custom-format-infer-ext
package.json
custom-format-infer-type
package.json
custom-format-mismatch
package.json
custom-targets-distdir
package.json
custom-targets
package.json
duplicate-targets
package.json
invalid-distpath
package.json
invalid-engines
package.json
invalid-source-missing
package.json
invalid-source-not-file
package.json
src
index.js
invalid-target-source-missing
package.json
invalid-target-source-not-file
package.json
src
index.js
invalid-targets
package.json
library-custom-scopehoist
package.json
library-scopehoist
package.json
main-format-mismatch
package.json
main-global
package.json
main-mjs
package.json
module-a.js
module-b.js
parcel
index.js
package.json
plugins
node_modules
parcel-transformer-bad-engines
index.js
package.json
parcel-transformer-no-engines
index.js
package.json
targets-default-distdir-none
package.json
targets-default-distdir-one
package.json
targets-default-distdir-two
package.json
serializer.test.js
test-utils.js
utils.test.js
css-darwin-arm64
README.md
package.json
css
README.md
node
browserslistToTargets.js
index.d.ts
index.js
targets.d.ts
package.json
diagnostic
lib
diagnostic.d.ts
diagnostic.js
package.json
src
diagnostic.js
test
markdown.test.js
events
lib
Disposable.js
ValueEmitter.js
errors.js
index.js
types.js
package.json
src
Disposable.js
ValueEmitter.js
errors.js
index.js
types.js
test
Disposable.test.js
ValueEmitter.test.js
fs-search
index.js
package.json
fs
index.d.ts
lib
browser.js
index.js
types.d.ts
package.json
src
MemoryFS.js
NodeFS.browser.js
NodeFS.js
OverlayFS.js
find.js
index.js
types.js
graph
lib
AdjacencyList.js
ContentGraph.js
Graph.js
index.js
types.js
package.json
src
AdjacencyList.js
ContentGraph.js
Graph.js
index.js
types.js
test
AdjacencyList.test.js
ContentGraph.test.js
Graph.test.js
integration
adjacency-list-shared-array.js
hash
browser.js
index.js
package.json
logger
lib
Logger.js
package.json
src
Logger.js
test
Logger.test.js
markdown-ansi
lib
markdown-ansi.js
node_modules
ansi-styles
index.d.ts
index.js
package.json
readme.md
chalk
index.d.ts
package.json
readme.md
source
index.js
templates.js
util.js
has-flag
index.d.ts
index.js
package.json
readme.md
supports-color
browser.js
index.js
package.json
readme.md
package.json
src
markdown-ansi.js
test
markdown-ansi.js
namer-default
lib
DefaultNamer.js
package.json
src
DefaultNamer.js
node-resolver-core
lib
NodeResolver.js
_empty.js
builtins.js
node_modules
semver
CHANGELOG.md
README.md
package.json
semver.js
package.json
src
NodeResolver.js
_empty.js
builtins.js
test
fixture
bar.js
env-dep
package.json
foo.js
nested
index.js
test.js
node_modules
.pnpm
[email protected]
node_modules
source-pnpm
dist.js
package.json
source.js
@scope
pkg
foo
bar.js
index.js
package.json
aliased-file
index.js
package.json
aliased
index.js
package.json
foo
bar.js
index.js
nested
baz.js
package.json
package-alias-exclude
main.js
package.json
package-alias-glob
package.json
src
test.js
package-alias
bar.js
browser.js
foo.js
main.js
package.json
package-browser-alias
bar.js
browser.js
foo.js
main.js
nested.js
package.json
subfolder1
subfolder2
subfile.js
package-browser-exclude
main.js
package.json
package-browser
browser.js
main.js
package.json
package-fallback
index.js
package.json
package-main-directory
nested
index.js
package.json
package-main
main.js
package.json
package-module-fallback
main.js
package.json
package-module
main.js
module.js
package.json
side-effects-false-glob
a
index.js
b
index.js
package.json
sub
a
index.js
b
index.js
index.js
index.json
side-effects-false
package.json
src
index.js
side-effects-package-redirect-down
foo
bar
baz
package.json
real-bar.js
package.json
package.json
package.json
side-effects-package-redirect-up
foo
bar
package.json
package.json
real-bar.js
package.json
source-not-symlinked
dist.js
package.json
source.js
package.json
packages
source-alias-glob
package.json
src
test.js
source-alias
dist.js
other.js
package.json
source.js
source
dist.js
package.json
source.js
resolver.js
optimizer-css
lib
CSSOptimizer.js
package.json
src
CSSOptimizer.js
optimizer-htmlnano
lib
HTMLNanoOptimizer.js
svgMappings.js
package.json
src
HTMLNanoOptimizer.js
svgMappings.js
optimizer-image
lib
ImageOptimizer.js
loadNative.js
native.js
package.json
optimizer-svgo
lib
SVGOOptimizer.js
package.json
src
SVGOOptimizer.js
optimizer-terser
lib
TerserOptimizer.js
package.json
src
TerserOptimizer.js
package-manager
index.d.ts
lib
index.js
types.d.ts
node_modules
semver
CHANGELOG.md
README.md
package.json
semver.js
package.json
src
JSONParseStream.js
MockPackageInstaller.js
NodePackageManager.js
NodeResolver.js
NodeResolverBase.js
NodeResolverSync.js
Npm.js
Pnpm.js
Yarn.js
index.js
installPackage.js
promiseFromProcess.js
types.js
utils.js
validateModuleSpecifier.js
test
NodePackageManager.test.js
fixtures
empty
package.json
has-a-not-yet-installed
package.json
has-foo
node_modules
foo
index.js
package.json
index.js
package.json
subpackage
package.json
packages
a
index.js
package.json
foo-2.0
index.js
package.json
peers-2.0
index.js
package.json
peers
index.js
package.json
validateModuleSpecifiers.test.js
packager-css
lib
CSSPackager.js
package.json
src
CSSPackager.js
packager-html
lib
HTMLPackager.js
package.json
src
HTMLPackager.js
packager-js
lib
CJSOutputFormat.js
DevPackager.js
ESMOutputFormat.js
GlobalOutputFormat.js
ScopeHoistingPackager.js
dev-prelude.js
helpers.js
index.js
utils.js
node_modules
globals
globals.json
index.d.ts
index.js
package.json
readme.md
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
package.json
src
.eslintrc.json
CJSOutputFormat.js
DevPackager.js
ESMOutputFormat.js
GlobalOutputFormat.js
ScopeHoistingPackager.js
dev-prelude.js
helpers.js
index.js
utils.js
packager-raw
lib
RawPackager.js
package.json
src
RawPackager.js
packager-svg
lib
SVGPackager.js
package.json
src
SVGPackager.js
plugin
lib
PluginAPI.js
package.json
src
PluginAPI.d.ts
PluginAPI.js
reporter-cli
lib
CLIReporter.js
node_modules
ansi-styles
index.d.ts
index.js
package.json
readme.md
chalk
index.d.ts
package.json
readme.md
source
index.js
templates.js
util.js
has-flag
index.d.ts
index.js
package.json
readme.md
supports-color
browser.js
index.js
package.json
readme.md
package.json
src
CLIReporter.js
bundleReport.js
emoji.js
logLevels.js
render.js
utils.js
test
CLIReporter.test.js
reporter-dev-server
lib
ServerReporter.js
package.json
src
HMRServer.js
Server.js
ServerReporter.js
serverErrors.js
templates
404.html
500.html
resolver-default
lib
DefaultResolver.js
package.json
src
DefaultResolver.js
runtime-browser-hmr
lib
HMRRuntime.js
loaders
hmr-runtime.js
package.json
src
HMRRuntime.js
loaders
.eslintrc.json
hmr-runtime.js
runtime-js
lib
JSRuntime.js
helpers
browser
css-loader.js
html-loader.js
import-polyfill.js
js-loader.js
prefetch-loader.js
preload-loader.js
wasm-loader.js
bundle-manifest.js
bundle-url.js
cacheLoader.js
get-worker-url.js
node
css-loader.js
html-loader.js
js-loader.js
wasm-loader.js
worker
js-loader.js
wasm-loader.js
package.json
src
JSRuntime.js
helpers
.eslintrc.json
browser
css-loader.js
html-loader.js
import-polyfill.js
js-loader.js
prefetch-loader.js
preload-loader.js
wasm-loader.js
bundle-manifest.js
bundle-url.js
cacheLoader.js
get-worker-url.js
node
css-loader.js
html-loader.js
js-loader.js
wasm-loader.js
worker
js-loader.js
wasm-loader.js
runtime-react-refresh
lib
ReactRefreshRuntime.js
package.json
src
ReactRefreshRuntime.js
runtime-service-worker
lib
ServiceWorkerRuntime.js
package.json
src
ServiceWorkerRuntime.js
source-map
README.md
dist
SourceMap.js
node.js
types.js
utils.js
wasm-bindings-web.js
wasm-bindings.js
wasm.js
index.d.ts
package.json
parcel_sourcemap_node
Cargo.toml
build.js
build.rs
index.js
src
lib.rs
parcel_sourcemap_wasm
dist-node
package.json
parcel_sourcemap_wasm.js
dist-web
package.json
parcel_sourcemap_wasm.js
transformer-babel
README.md
lib
BabelTransformer.js
babel7.js
babelErrorUtils.js
config.js
constants.js
flow.js
jsx.js
remapAstLocations.js
types.js
utils.js
node_modules
semver
CHANGELOG.md
README.md
package.json
semver.js
package.json
src
BabelTransformer.js
babel7.js
babelErrorUtils.js
config.js
constants.js
flow.js
jsx.js
remapAstLocations.js
types.js
utils.js
transformer-css
lib
CSSTransformer.js
package.json
src
CSSTransformer.js
transformer-html
lib
HTMLTransformer.js
dependencies.js
inline.js
node_modules
semver
CHANGELOG.md
README.md
package.json
semver.js
package.json
src
HTMLTransformer.js
dependencies.js
inline.js
transformer-image
lib
ImageTransformer.js
loadSharp.js
validateConfig.js
package.json
src
ImageTransformer.js
loadSharp.js
validateConfig.js
transformer-js
lib
JSTransformer.js
esmodule-helpers.js
loadNative.js
native-browser.js
native.js
node_modules
semver
CHANGELOG.md
README.md
package.json
semver.js
package.json
src
JSTransformer.js
esmodule-helpers.js
loadNative.js
transformer-json
lib
JSONTransformer.js
package.json
src
JSONTransformer.js
transformer-postcss
lib
PostCSSTransformer.js
constants.js
loadConfig.js
loadPlugins.js
node_modules
semver
CHANGELOG.md
README.md
package.json
semver.js
package.json
src
PostCSSTransformer.js
constants.js
loadConfig.js
loadPlugins.js
transformer-posthtml
lib
PostHTMLTransformer.js
loadPlugins.js
node_modules
semver
CHANGELOG.md
README.md
package.json
semver.js
package.json
src
PostHTMLTransformer.js
loadPlugins.js
transformer-raw
lib
RawTransformer.js
package.json
src
RawTransformer.js
transformer-react-refresh-wrap
lib
ReactRefreshWrapTransformer.js
helpers
helpers.js
package.json
src
ReactRefreshWrapTransformer.js
helpers
.eslintrc.json
helpers.js
transformer-svg
lib
SVGTransformer.js
dependencies.js
inline.js
node_modules
semver
CHANGELOG.md
README.md
package.json
semver.js
package.json
src
SVGTransformer.js
dependencies.js
inline.js
test
parseFuncIRI.test.js
types
build-ts.js
index.js
lib
index.d.ts
unsafe.d.ts
package.json
unsafe.js
utils
.eslintrc.js
node_modules
ansi-styles
index.d.ts
index.js
package.json
readme.md
chalk
index.d.ts
package.json
readme.md
source
index.js
templates.js
util.js
has-flag
index.d.ts
index.js
package.json
readme.md
supports-color
browser.js
index.js
package.json
readme.md
package.json
src
DefaultMap.js
Deferred.js
PromiseQueue.js
TapStream.js
alternatives.js
ansi-html.js
blob.js
bundle-url.js
collection.js
config.js
countLines.js
debounce.js
dependency-location.js
escape-html.js
generateBuildMetrics.js
generateCertificate.js
getCertificate.js
getExisting.js
getRootDir.js
glob.js
hash.js
http-server.js
index.js
is-url.js
isDirectoryInside.js
objectHash.js
openInBrowser.js
parseCSSImport.js
path.js
prettifyTime.js
prettyDiagnostic.js
relativeBundlePath.js
relativeUrl.js
replaceBundleReferences.js
schema.js
shared-buffer.js
sourcemap.js
stream.js
throttle.js
urlJoin.js
test
DefaultMap.test.js
PromiseQueue.test.js
collection.test.js
config.test.js
input
config
config.json
empty.json
empty.toml
sourcemap
inline.js
no-sourcemap.js
referenced-min.js
source-root.js
objectHash.test.js
prettifyTime.test.js
replaceBundleReferences.test.js
sourcemap.test.js
throttle.test.js
urlJoin.test.js
watcher
README.md
index.d.ts
index.js
package.json
workers
index.d.ts
lib
Handle.js
Profiler.js
Trace.js
Worker.js
WorkerFarm.js
backend.js
bus.js
child.js
childState.js
cpuCount.js
index.js
process
ProcessChild.js
ProcessWorker.js
threads
ThreadsChild.js
ThreadsWorker.js
types.js
package.json
src
Handle.js
Profiler.js
Trace.js
Worker.js
WorkerFarm.js
backend.js
bus.js
child.js
childState.js
cpuCount.js
index.js
process
ProcessChild.js
ProcessWorker.js
threads
ThreadsChild.js
ThreadsWorker.js
types.js
test
cpuCount.test.js
integration
workerfarm
console.js
echo.js
ipc-pid.js
ipc.js
logging.js
master-process-id.js
master-sum.js
ping.js
resolve-shared-reference.js
reverse-handle.js
shared-reference.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
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
@swc
helpers
lib
_apply_decorated_descriptor.js
_array_like_to_array.js
_array_with_holes.js
_array_without_holes.js
_assert_this_initialized.js
_async_generator.js
_async_generator_delegate.js
_async_iterator.js
_async_to_generator.js
_await_async_generator.js
_await_value.js
_check_private_redeclaration.js
_class_apply_descriptor_destructure.js
_class_apply_descriptor_get.js
_class_apply_descriptor_set.js
_class_apply_descriptor_update.js
_class_call_check.js
_class_check_private_static_access.js
_class_check_private_static_field_descriptor.js
_class_extract_field_descriptor.js
_class_name_tdz_error.js
_class_private_field_destructure.js
_class_private_field_get.js
_class_private_field_init.js
_class_private_field_loose_base.js
_class_private_field_loose_key.js
_class_private_field_set.js
_class_private_field_update.js
_class_private_method_get.js
_class_private_method_init.js
_class_private_method_set.js
_class_static_private_field_destructure.js
_class_static_private_field_spec_get.js
_class_static_private_field_spec_set.js
_class_static_private_field_update.js
_construct.js
_create_class.js
_create_super.js
_decorate.js
_defaults.js
_define_enumerable_properties.js
_define_property.js
_export_star.js
_extends.js
_get.js
_get_prototype_of.js
_inherits.js
_inherits_loose.js
_initializer_define_property.js
_initializer_warning_helper.js
_instanceof.js
_interop_require_default.js
_interop_require_wildcard.js
_is_native_function.js
_is_native_reflect_construct.js
_iterable_to_array.js
_iterable_to_array_limit.js
_iterable_to_array_limit_loose.js
_jsx.js
_new_arrow_check.js
_non_iterable_rest.js
_non_iterable_spread.js
_object_spread.js
_object_spread_props.js
_object_without_properties.js
_object_without_properties_loose.js
_possible_constructor_return.js
_read_only_error.js
_set.js
_set_prototype_of.js
_skip_first_generator_next.js
_sliced_to_array.js
_sliced_to_array_loose.js
_super_prop_base.js
_tagged_template_literal.js
_tagged_template_literal_loose.js
_throw.js
_to_array.js
_to_consumable_array.js
_to_primitive.js
_to_property_key.js
_ts_decorate.js
_ts_metadata.js
_ts_param.js
_type_of.js
_unsupported_iterable_to_array.js
_wrap_async_generator.js
_wrap_native_super.js
index.js
package.json
scripts
build.sh
gen.sh
generator.sh
@szmarczak
http-timer
README.md
package.json
source
index.js
@trysound
sax
README.md
lib
sax.js
package.json
@tsconfig
node10
README.md
package.json
tsconfig.json
node12
README.md
package.json
tsconfig.json
node14
README.md
package.json
tsconfig.json
node16
README.md
package.json
tsconfig.json
@types
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
test.d.ts
timers.d.ts
timers
promises.d.ts
tls.d.ts
trace_events.d.ts
tty.d.ts
url.d.ts
util.d.ts
v8.d.ts
vm.d.ts
wasi.d.ts
worker_threads.d.ts
zlib.d.ts
parse-json
README.md
index.d.ts
package.json
stack-utils
README.md
index.d.ts
package.json
yargs-parser
README.md
index.d.ts
package.json
yargs
README.md
helpers.d.ts
index.d.ts
package.json
yargs.d.ts
abbrev
README.md
abbrev.js
package.json
abortcontroller-polyfill
README.md
dist
abortcontroller-polyfill-only.js
abortcontroller.js
cjs-ponyfill.js
polyfill-patch-fetch.js
umd-polyfill.js
package.json
src
abortableFetch.js
abortcontroller-polyfill.js
abortcontroller.js
polyfill.js
ponyfill.js
utils.js
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
README.md
dist
src
index.d.ts
index.js
promisify.d.ts
promisify.js
package.json
src
index.ts
promisify.ts
aggregate-error
index.d.ts
index.js
package.json
readme.md
ansi-align
CHANGELOG.md
README.md
index.js
node_modules
emoji-regex
LICENSE-MIT.txt
README.md
es2015
index.js
text.js
index.d.ts
index.js
package.json
text.js
is-fullwidth-code-point
index.d.ts
index.js
package.json
readme.md
string-width
index.d.ts
index.js
package.json
readme.md
strip-ansi
index.d.ts
index.js
package.json
readme.md
package.json
ansi-regex
index.d.ts
index.js
package.json
readme.md
ansi-styles
index.d.ts
index.js
package.json
readme.md
anymatch
README.md
index.d.ts
index.js
package.json
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
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
arg
LICENSE.md
README.md
index.d.ts
index.js
package.json
argparse
CHANGELOG.md
README.md
index.js
lib
action.js
action
append.js
append
constant.js
count.js
help.js
store.js
store
constant.js
false.js
true.js
subparsers.js
version.js
action_container.js
argparse.js
argument
error.js
exclusive.js
group.js
argument_parser.js
const.js
help
added_formatters.js
formatter.js
namespace.js
utils.js
package.json
array-find-index
index.js
package.json
readme.md
array-union
index.d.ts
index.js
package.json
readme.md
arrgv
.travis.yml
README.md
index.js
package.json
test.js
arrify
index.d.ts
index.js
package.json
readme.md
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
ava
index.d.ts
lib
api.js
assert.js
chalk.js
cli.js
code-excerpt.js
concordance-options.js
context-ref.js
create-chain.js
environment-variables.js
eslint-plugin-helper-worker.js
extensions.js
fork.js
globs.js
is-ci.js
like-selector.js
line-numbers.js
load-config.js
module-types.js
node-arguments.js
parse-test-args.js
plugin-support
shared-worker-loader.js
shared-workers.js
provider-manager.js
reporters
beautify-stack.js
colors.js
default.js
format-serialized-error.js
improper-usage-messages.js
prefix-title.js
tap.js
run-status.js
runner.js
scheduler.js
serialize-error.js
snapshot-manager.js
test.js
watcher.js
worker
base.js
dependency-tracker.js
line-numbers.js
node_modules
chalk
package.json
readme.md
source
index.d.ts
index.js
utilities.js
vendor
ansi-styles
index.d.ts
index.js
supports-color
browser.d.ts
browser.js
index.d.ts
index.js
package.json
plugin.d.ts
readme.md
types
assertions.d.ts
subscribable.d.ts
test-fn.d.ts
try-fn.d.ts
babel-plugin-dynamic-import-node
.travis.yml
CHANGELOG.md
README.md
lib
index.js
utils.js
package.json
utils.js
babel-plugin-polyfill-corejs2
README.md
lib
add-platform-specific-polyfills.js
built-in-definitions.js
helpers.js
index.js
package.json
babel-plugin-polyfill-corejs3
README.md
core-js-compat
README.md
data.js
entries.js
get-modules-list-for-target-version.js
lib
built-in-definitions.js
index.js
shipped-proposals.js
utils.js
package.json
babel-plugin-polyfill-regenerator
README.md
lib
index.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-extensions
binary-extensions.json
binary-extensions.json.d.ts
index.d.ts
index.js
package.json
readme.md
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
blueimp-md5
LICENSE.txt
README.md
js
md5.js
md5.min.js
package.json
bn.js
CHANGELOG.md
README.md
lib
bn.js
package.json
boolbase
README.md
index.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
ansi-styles
index.d.ts
index.js
package.json
readme.md
chalk
index.d.ts
package.json
readme.md
source
index.js
templates.js
util.js
emoji-regex
LICENSE-MIT.txt
README.md
es2015
index.js
text.js
index.d.ts
index.js
package.json
text.js
has-flag
index.d.ts
index.js
package.json
readme.md
is-fullwidth-code-point
index.d.ts
index.js
package.json
readme.md
string-width
index.d.ts
index.js
package.json
readme.md
strip-ansi
index.d.ts
index.js
package.json
readme.md
supports-color
browser.js
index.js
package.json
readme.md
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
package.json
readme.md
brace-expansion
README.md
index.js
package.json
braces
CHANGELOG.md
README.md
index.js
lib
compile.js
constants.js
expand.js
parse.js
stringify.js
utils.js
package.json
browserslist
README.md
browser.js
cli.js
error.d.ts
error.js
index.d.ts
index.js
node.js
package.json
parse.js
bs58
CHANGELOG.md
README.md
index.js
package.json
buffer-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
call-bind
.github
FUNDING.yml
CHANGELOG.md
README.md
callBound.js
index.js
package.json
test
callBound.js
index.js
callsites
index.d.ts
index.js
package.json
readme.md
camelcase
index.d.ts
index.js
package.json
readme.md
caniuse-lite
README.md
data
agents.js
browserVersions.js
browsers.js
features.js
features
aac.js
abortcontroller.js
ac3-ec3.js
accelerometer.js
addeventlistener.js
alternate-stylesheet.js
ambient-light.js
apng.js
array-find-index.js
array-find.js
array-flat.js
array-includes.js
arrow-functions.js
asmjs.js
async-clipboard.js
async-functions.js
atob-btoa.js
audio-api.js
audio.js
audiotracks.js
autofocus.js
auxclick.js
av1.js
avif.js
background-attachment.js
background-clip-text.js
background-img-opts.js
background-position-x-y.js
background-repeat-round-space.js
background-sync.js
battery-status.js
beacon.js
beforeafterprint.js
bigint.js
blobbuilder.js
bloburls.js
border-image.js
border-radius.js
broadcastchannel.js
brotli.js
calc.js
canvas-blending.js
canvas-text.js
canvas.js
ch-unit.js
chacha20-poly1305.js
channel-messaging.js
childnode-remove.js
classlist.js
client-hints-dpr-width-viewport.js
clipboard.js
colr-v1.js
colr.js
comparedocumentposition.js
console-basic.js
console-time.js
const.js
constraint-validation.js
contenteditable.js
contentsecuritypolicy.js
contentsecuritypolicy2.js
cookie-store-api.js
cors.js
createimagebitmap.js
credential-management.js
cryptography.js
css-all.js
css-animation.js
css-any-link.js
css-appearance.js
css-at-counter-style.js
css-autofill.js
css-backdrop-filter.js
css-background-offsets.js
css-backgroundblendmode.js
css-boxdecorationbreak.js
css-boxshadow.js
css-canvas.js
css-caret-color.js
css-cascade-layers.js
css-case-insensitive.js
css-clip-path.js
css-color-adjust.js
css-color-function.js
css-conic-gradients.js
css-container-queries.js
css-container-query-units.js
css-containment.js
css-content-visibility.js
css-counters.js
css-crisp-edges.js
css-cross-fade.js
css-default-pseudo.js
css-descendant-gtgt.js
css-deviceadaptation.js
css-dir-pseudo.js
css-display-contents.js
css-element-function.js
css-env-function.js
css-exclusions.js
css-featurequeries.js
css-file-selector-button.js
css-filter-function.js
css-filters.js
css-first-letter.js
css-first-line.js
css-fixed.js
css-focus-visible.js
css-focus-within.js
css-font-palette.js
css-font-rendering-controls.js
css-font-stretch.js
css-gencontent.js
css-gradients.js
css-grid-animation.js
css-grid.js
css-hanging-punctuation.js
css-has.js
css-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-lch-lab.js
css-letter-spacing.js
css-line-clamp.js
css-logical-props.js
css-marker-pseudo.js
css-masks.js
css-matches-pseudo.js
css-math-functions.js
css-media-interaction.js
css-media-resolution.js
css-media-scripting.js
css-mediaqueries.js
css-mixblendmode.js
css-motion-paths.js
css-namespaces.js
css-nesting.js
css-not-sel-list.js
css-nth-child-of.js
css-opacity.js
css-optional-pseudo.js
css-overflow-anchor.js
css-overflow-overlay.js
css-overflow.js
css-overscroll-behavior.js
css-page-break.js
css-paged-media.js
css-paint-api.js
css-placeholder-shown.js
css-placeholder.js
css-print-color-adjust.js
css-read-only-write.js
css-rebeccapurple.js
css-reflections.js
css-regions.js
css-repeating-gradients.js
css-resize.js
css-revert-value.js
css-rrggbbaa.js
css-scroll-behavior.js
css-scroll-timeline.js
css-scrollbar.js
css-sel2.js
css-sel3.js
css-selection.js
css-shapes.js
css-snappoints.js
css-sticky.js
css-subgrid.js
css-supports-api.js
css-table.js
css-text-align-last.js
css-text-indent.js
css-text-justify.js
css-text-orientation.js
css-text-spacing.js
css-textshadow.js
css-touch-action-2.js
css-touch-action.js
css-transitions.js
css-unicode-bidi.js
css-unset-value.js
css-variables.js
css-when-else.js
css-widows-orphans.js
css-width-stretch.js
css-writing-mode.js
css-zoom.js
css3-attr.js
css3-boxsizing.js
css3-colors.js
css3-cursors-grab.js
css3-cursors-newer.js
css3-cursors.js
css3-tabsize.js
currentcolor.js
custom-elements.js
custom-elementsv1.js
customevent.js
datalist.js
dataset.js
datauri.js
date-tolocaledatestring.js
declarative-shadow-dom.js
decorators.js
details.js
deviceorientation.js
devicepixelratio.js
dialog.js
dispatchevent.js
dnssec.js
do-not-track.js
document-currentscript.js
document-evaluate-xpath.js
document-execcommand.js
document-policy.js
document-scrollingelement.js
documenthead.js
dom-manip-convenience.js
dom-range.js
domcontentloaded.js
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.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-metrics-overrides.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
import-maps.js
imports.js
indeterminate-checkbox.js
indexeddb.js
indexeddb2.js
inline-block.js
innertext.js
input-autocomplete-onoff.js
input-color.js
input-datetime.js
input-email-tel-url.js
input-event.js
input-file-accept.js
input-file-directory.js
input-file-multiple.js
input-inputmode.js
input-minlength.js
input-number.js
input-pattern.js
input-placeholder.js
input-range.js
input-search.js
input-selection.js
insert-adjacent.js
insertadjacenthtml.js
internationalization.js
intersectionobserver-v2.js
intersectionobserver.js
intl-pluralrules.js
intrinsic-width.js
jpeg2000.js
jpegxl.js
jpegxr.js
js-regexp-lookbehind.js
json.js
justify-content-space-evenly.js
kerning-pairs-ligatures.js
keyboardevent-charcode.js
keyboardevent-code.js
keyboardevent-getmodifierstate.js
keyboardevent-key.js
keyboardevent-location.js
keyboardevent-which.js
lazyload.js
let.js
link-icon-png.js
link-icon-svg.js
link-rel-dns-prefetch.js
link-rel-modulepreload.js
link-rel-preconnect.js
link-rel-prefetch.js
link-rel-preload.js
link-rel-prerender.js
loading-lazy-attr.js
localecompare.js
magnetometer.js
matchesselector.js
matchmedia.js
mathml.js
maxlength.js
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
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
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
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
tabindex-attr.js
template-literals.js
template.js
temporal.js
testfeat.js
text-decoration.js
text-emphasis.js
text-overflow.js
text-size-adjust.js
text-stroke.js
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
vector-effect.js
vibration.js
video.js
videotracks.js
viewport-unit-variants.js
viewport-units.js
wai-aria.js
wake-lock.js
wasm.js
wav.js
wbr-element.js
web-animation.js
web-app-manifest.js
web-bluetooth.js
web-serial.js
web-share.js
webauthn.js
webgl.js
webgl2.js
webgpu.js
webhid.js
webkit-user-drag.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
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
cbor
LICENSE.md
README.md
lib
cbor.js
commented.js
constants.js
decoder.js
diagnose.js
encoder.js
map.js
simple.js
tagged.js
utils.js
package.json
types
lib
cbor.d.ts
commented.d.ts
constants.d.ts
decoder.d.ts
diagnose.d.ts
encoder.d.ts
map.d.ts
simple.d.ts
tagged.d.ts
utils.d.ts
vendor
binary-parse-stream
index.d.ts
vendor
binary-parse-stream
README.md
index.js
chalk
index.js
node_modules
ansi-styles
index.js
package.json
readme.md
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
readme.md
templates.js
types
index.d.ts
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
chrome-trace-event
CHANGES.md
LICENSE.txt
README.md
dist
trace-event.d.ts
trace-event.js
package.json
chunkd
README.md
dist
chunkd.d.ts
chunkd.js
package.json
ci-info
CHANGELOG.md
README.md
index.d.ts
index.js
package.json
vendors.json
ci-parallel-vars
README.md
index.js
package.json
cipher-base
.travis.yml
README.md
index.js
package.json
test.js
clean-stack
index.d.ts
index.js
node_modules
escape-string-regexp
index.d.ts
index.js
package.json
readme.md
package.json
readme.md
clean-yaml-object
index.js
package.json
readme.md
cli-boxes
boxes.json
index.d.ts
index.js
package.json
readme.md
cli-truncate
index.d.ts
index.js
package.json
readme.md
cliui
CHANGELOG.md
LICENSE.txt
README.md
build
lib
index.js
string-utils.js
node_modules
emoji-regex
LICENSE-MIT.txt
README.md
es2015
index.js
text.js
index.d.ts
index.js
package.json
text.js
is-fullwidth-code-point
index.d.ts
index.js
package.json
readme.md
string-width
index.d.ts
index.js
package.json
readme.md
strip-ansi
index.d.ts
index.js
package.json
readme.md
package.json
clone-response
README.md
node_modules
mimic-response
index.js
package.json
readme.md
package.json
src
index.js
clone
README.md
clone.js
package.json
code-excerpt
dist
index.d.ts
index.js
package.json
readme.md
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
common-path-prefix
README.md
index.d.ts
index.js
package.json
concat-map
.travis.yml
example
map.js
index.js
package.json
test
map.js
concordance
README.md
index.js
lib
Circular.js
Indenter.js
Registry.js
compare.js
complexValues
arguments.js
arrayBuffer.js
boxed.js
dataView.js
date.js
error.js
function.js
global.js
map.js
object.js
promise.js
regexp.js
set.js
typedArray.js
constants.js
describe.js
diff.js
encoder.js
format.js
formatUtils.js
getCtor.js
getObjectKeys.js
getStringTag.js
hasLength.js
isEnumerable.js
lineBuilder.js
metaDescriptors
item.js
mapEntry.js
pointer.js
property.js
stats.js
pluginRegistry.js
primitiveValues
bigInt.js
boolean.js
null.js
number.js
string.js
symbol.js
undefined.js
recursorUtils.js
serialize.js
shouldCompareDeep.js
symbolProperties.js
themeUtils.js
node_modules
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
package.json
configstore
index.js
node_modules
write-file-atomic
CHANGELOG.md
README.md
index.js
package.json
package.json
readme.md
console-control-strings
README.md
index.js
package.json
convert-source-map
README.md
index.js
package.json
convert-to-spaces
dist
index.d.ts
index.js
package.json
readme.md
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-util-is
README.md
lib
util.js
package.json
cosmiconfig
README.md
dist
Explorer.d.ts
Explorer.js
ExplorerBase.d.ts
ExplorerBase.js
ExplorerSync.d.ts
ExplorerSync.js
cacheWrapper.d.ts
cacheWrapper.js
getDirectory.d.ts
getDirectory.js
getPropertyByPath.d.ts
getPropertyByPath.js
index.d.ts
index.js
loaders.d.ts
loaders.js
readFile.d.ts
readFile.js
types.d.ts
types.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
create-require
CHANGELOG.md
README.md
create-require.d.ts
create-require.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
css-select
README.md
lib
attributes.d.ts
attributes.js
compile.d.ts
compile.js
general.d.ts
general.js
index.d.ts
index.js
procedure.d.ts
procedure.js
pseudo-selectors
aliases.d.ts
aliases.js
filters.d.ts
filters.js
index.d.ts
index.js
pseudos.d.ts
pseudos.js
subselects.d.ts
subselects.js
sort.d.ts
sort.js
types.d.ts
types.js
package.json
css-tree
CHANGELOG.md
README.md
data
index.js
patch.json
dist
csstree.js
csstree.min.js
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
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
Hash.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
commonjs
index.d.ts
index.js
parse.d.ts
parse.js
stringify.d.ts
stringify.js
types.d.ts
types.js
es
index.d.ts
index.js
parse.d.ts
parse.js
stringify.d.ts
stringify.js
types.d.ts
types.js
package.json
readme.md
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
package.json
currently-unhandled
browser.js
core.js
index.js
package.json
readme.md
date-time
index.d.ts
index.js
package.json
readme.md
debug
README.md
node_modules
ms
index.js
license.md
package.json
readme.md
package.json
src
browser.js
common.js
index.js
node.js
decompress-response
index.d.ts
index.js
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
define-properties
.github
FUNDING.yml
CHANGELOG.md
README.md
index.js
package.json
del
index.d.ts
index.js
node_modules
aggregate-error
index.d.ts
index.js
package.json
readme.md
clean-stack
index.d.ts
index.js
package.json
readme.md
globby
gitignore.js
index.d.ts
index.js
package.json
readme.md
stream-utils.js
indent-string
index.d.ts
index.js
package.json
readme.md
p-map
index.d.ts
index.js
package.json
readme.md
package.json
readme.md
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
diff.min.js
lib
convert
dmp.js
xml.js
diff
array.js
base.js
character.js
css.js
json.js
line.js
sentence.js
word.js
index.es6.js
index.js
patch
apply.js
create.js
merge.js
parse.js
util
array.js
distance-iterator.js
params.js
package.json
release-notes.md
runtime.js
dir-glob
index.js
package.json
readme.md
dom-serializer
README.md
lib
esm
foreignNames.d.ts
foreignNames.js
index.d.ts
index.js
package.json
foreignNames.d.ts
foreignNames.js
index.d.ts
index.js
node_modules
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
domelementtype
lib
esm
index.d.ts
index.js
package.json
index.d.ts
index.js
package.json
readme.md
domhandler
lib
index.d.ts
index.js
node.d.ts
node.js
package.json
readme.md
domutils
lib
feeds.d.ts
feeds.js
helpers.d.ts
helpers.js
index.d.ts
index.js
legacy.d.ts
legacy.js
manipulation.d.ts
manipulation.js
querying.d.ts
querying.js
stringify.d.ts
stringify.js
traversal.d.ts
traversal.js
package.json
readme.md
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
config.js
lib
cli-options.js
env-options.js
main.js
package.json
duplexer3
LICENSE.md
README.md
index.js
package.json
eastasianwidth
README.md
eastasianwidth.js
package.json
electron-to-chromium
CHANGELOG.md
README.md
chromium-versions.js
chromium-versions.json
full-chromium-versions.js
full-chromium-versions.json
full-versions.js
full-versions.json
index.js
package.json
versions.js
versions.json
emittery
index.d.ts
index.js
package.json
readme.md
emoji-regex
LICENSE-MIT.txt
README.md
RGI_Emoji.d.ts
RGI_Emoji.js
es2015
RGI_Emoji.d.ts
RGI_Emoji.js
index.d.ts
index.js
text.d.ts
text.js
index.d.ts
index.js
package.json
text.d.ts
text.js
end-of-stream
README.md
index.js
package.json
entities
lib
decode.d.ts
decode.js
decode_codepoint.d.ts
decode_codepoint.js
encode-trie.d.ts
encode-trie.js
encode.d.ts
encode.js
generated
decode-data-html.d.ts
decode-data-html.js
decode-data-xml.d.ts
decode-data-xml.js
index.d.ts
index.js
maps
entities.json
legacy.json
xml.json
package.json
readme.md
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
error-ex
README.md
index.js
package.json
error-polyfill
README.md
index.js
lib
index.js
non-v8
Frame.js
FrameStringParser.js
FrameStringSource.js
index.js
prepareStackTrace.js
unsupported.js
v8.js
package.json
escalade
dist
index.js
index.d.ts
package.json
readme.md
sync
index.d.ts
index.js
escape-goat
index.d.ts
index.js
package.json
readme.md
escape-string-regexp
index.js
package.json
readme.md
esprima
README.md
bin
esparse.js
esvalidate.js
dist
esprima.js
package.json
esutils
README.md
lib
ast.js
code.js
keyword.js
utils.js
package.json
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-diff
.travis.yml
README.md
diff.d.ts
diff.js
package.json
test.js
fast-glob
README.md
out
index.d.ts
index.js
managers
patterns.d.ts
patterns.js
tasks.d.ts
tasks.js
providers
async.d.ts
async.js
filters
deep.d.ts
deep.js
entry.d.ts
entry.js
error.d.ts
error.js
matchers
matcher.d.ts
matcher.js
partial.d.ts
partial.js
provider.d.ts
provider.js
stream.d.ts
stream.js
sync.d.ts
sync.js
transformers
entry.d.ts
entry.js
readers
reader.d.ts
reader.js
stream.d.ts
stream.js
sync.d.ts
sync.js
settings.d.ts
settings.js
types
index.d.ts
index.js
utils
array.d.ts
array.js
errno.d.ts
errno.js
fs.d.ts
fs.js
index.d.ts
index.js
path.d.ts
path.js
pattern.d.ts
pattern.js
stream.d.ts
stream.js
string.d.ts
string.js
package.json
fastq
.github
dependabot.yml
workflows
ci.yml
README.md
bench.js
example.js
index.d.ts
package.json
queue.js
test
example.ts
promise.js
test.js
tsconfig.json
figures
index.d.ts
index.js
node_modules
escape-string-regexp
index.d.ts
index.js
package.json
readme.md
package.json
readme.md
file-uri-to-path
.travis.yml
History.md
README.md
index.d.ts
index.js
package.json
test
test.js
tests.json
fill-range
README.md
index.js
package.json
find-up
index.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
fs-constants
README.md
browser.js
index.js
package.json
fs.realpath
README.md
index.js
old.js
package.json
fsevents
README.md
fsevents.d.ts
fsevents.js
package.json
function-bind
.jscs.json
.travis.yml
README.md
implementation.js
index.js
package.json
test
index.js
gauge
CHANGELOG.md
README.md
base-theme.js
error.js
has-color.js
index.js
node_modules
ansi-regex
index.js
package.json
readme.md
is-fullwidth-code-point
index.js
package.json
readme.md
string-width
index.js
package.json
readme.md
strip-ansi
index.js
package.json
readme.md
package.json
plumbing.js
process.js
progress-bar.js
render-template.js
set-immediate.js
set-interval.js
spin.js
template-item.js
theme-set.js
themes.js
wide-truncate.js
gensync
README.md
index.js
package.json
test
index.test.js
get-caller-file
LICENSE.md
README.md
index.d.ts
index.js
package.json
get-intrinsic
.github
FUNDING.yml
CHANGELOG.md
README.md
index.js
package.json
test
GetIntrinsic.js
get-port
index.d.ts
index.js
package.json
readme.md
get-stream
buffer-stream.js
index.js
package.json
readme.md
github-from-package
.travis.yml
example
package.json
url.js
index.js
package.json
test
a.json
b.json
c.json
d.json
e.json
url.js
glob-parent
CHANGELOG.md
README.md
index.js
package.json
glob
README.md
common.js
glob.js
package.json
sync.js
global-dirs
index.d.ts
index.js
node_modules
ini
README.md
ini.js
package.json
package.json
readme.md
globals
globals.json
index.js
package.json
readme.md
globby
ignore.js
index.d.ts
index.js
node_modules
slash
index.d.ts
index.js
package.json
readme.md
package.json
readme.md
utilities.js
got
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.js
package.json
readme.md
has-property-descriptors
.github
FUNDING.yml
CHANGELOG.md
README.md
index.js
package.json
test
index.js
has-symbols
.github
FUNDING.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-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
safe-buffer
README.md
index.d.ts
index.js
package.json
package.json
homedir-polyfill
README.md
index.js
package.json
polyfill.js
htmlnano
CHANGELOG.md
LICENSE.txt
README.md
docs
README.md
babel.config.js
docs
010-introduction.md
020-usage.md
030-config.md
040-presets.md
050-modules.md
060-contribute.md
docusaurus.config.js
netlify.toml
package-lock.json
package.json
sidebars.js
versioned_docs
version-1.1.1
010-introduction.md
020-usage.md
030-config.md
040-presets.md
050-modules.md
060-contribute.md
version-2.0.0
010-introduction.md
020-usage.md
030-config.md
040-presets.md
050-modules.md
060-contribute.md
versioned_sidebars
version-1.1.1-sidebars.json
version-2.0.0-sidebars.json
versions.json
index.js
lib
helpers.js
htmlnano.js
modules
collapseAttributeWhitespace.js
collapseBooleanAttributes.js
collapseWhitespace.js
custom.js
deduplicateAttributeValues.js
mergeScripts.js
mergeStyles.js
minifyConditionalComments.js
minifyCss.js
minifyJs.js
minifyJson.js
minifySvg.js
minifyUrls.js
normalizeAttributeValues.js
removeAttributeQuotes.js
removeComments.js
removeEmptyAttributes.js
removeOptionalTags.js
removeRedundantAttributes.js
removeUnusedCss.js
sortAttributes.js
sortAttributesWithLists.js
presets
ampSafe.js
max.js
safe.js
package.json
test.js
htmlparser2
README.md
lib
FeedHandler.d.ts
FeedHandler.js
Parser.d.ts
Parser.js
Tokenizer.d.ts
Tokenizer.js
WritableStream.d.ts
WritableStream.js
index.d.ts
index.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
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-by-default
README.md
index.js
package.json
ignore
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
indent-string
index.d.ts
index.js
package.json
readme.md
inflight
README.md
inflight.js
package.json
inherits
README.md
inherits.js
inherits_browser.js
package.json
ini
README.md
ini.js
package.json
ip-regex
index.d.ts
index.js
package.json
readme.md
irregular-plurals
index.d.ts
index.js
irregular-plurals.json
package.json
readme.md
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-ci
CHANGELOG.md
README.md
bin.js
index.js
node_modules
ci-info
CHANGELOG.md
README.md
index.js
package.json
vendors.json
package.json
is-core-module
CHANGELOG.md
README.md
core.json
index.js
package.json
test
index.js
is-docker
cli.js
index.d.ts
index.js
package.json
readme.md
is-error
.travis.yml
README.md
index.js
package.json
test
index.js
is-extglob
README.md
index.js
package.json
is-fullwidth-code-point
index.d.ts
index.js
package.json
readme.md
is-glob
README.md
index.js
package.json
is-installed-globally
index.d.ts
index.js
package.json
readme.md
is-json
.travis.yml
README.md
index.js
package.json
test
index.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-cwd
index.d.ts
index.js
package.json
readme.md
is-path-inside
index.d.ts
index.js
package.json
readme.md
is-plain-object
README.md
dist
is-plain-object.js
is-plain-object.d.ts
package.json
is-promise
index.d.ts
index.js
package.json
readme.md
is-typedarray
LICENSE.md
README.md
index.js
package.json
test.js
is-unicode-supported
index.d.ts
index.js
package.json
readme.md
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
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
ansi-styles
index.d.ts
index.js
package.json
readme.md
chalk
index.d.ts
package.json
readme.md
source
index.js
templates.js
util.js
has-flag
index.d.ts
index.js
package.json
readme.md
supports-color
browser.js
index.js
package.json
readme.md
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
ansi-styles
index.d.ts
index.js
package.json
readme.md
chalk
index.d.ts
package.json
readme.md
source
index.js
templates.js
util.js
has-flag
index.d.ts
index.js
package.json
readme.md
supports-color
browser.js
index.js
package.json
readme.md
package.json
js-sha256
CHANGELOG.md
LICENSE.txt
README.md
build
sha256.min.js
index.d.ts
package.json
src
sha256.js
js-string-escape
CHANGELOG.md
README.md
index.js
package.json
js-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
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-even-better-errors
CHANGELOG.md
LICENSE.md
README.md
index.js
package.json
json5
LICENSE.md
README.md
dist
index.js
index.min.js
lib
cli.js
index.d.ts
index.js
parse.d.ts
parse.js
register.js
require.js
stringify.d.ts
stringify.js
unicode.d.ts
unicode.js
util.d.ts
util.js
package.json
keyv
README.md
package.json
src
index.js
latest-version
index.d.ts
index.js
package.json
readme.md
lines-and-columns
README.md
build
index.d.ts
index.js
package.json
lmdb
README.md
SECURITY.md
caching.js
dependencies
lmdb-data-v1
libraries
liblmdb
lmdb.h
mdb.c
mdb_copy.c
mdb_drop.c
mdb_dump.c
mdb_load.c
mdb_stat.c
midl.c
midl.h
mtest.c
mtest2.c
mtest3.c
mtest4.c
mtest5.c
mtest6.c
sample-bdb.txt
sample-mdb.txt
lmdb
libraries
liblmdb
chacha8.c
chacha8.h
crypto.c
lmdb.h
mdb.c
mdb_copy.c
mdb_drop.c
mdb_dump.c
mdb_load.c
mdb_stat.c
midl.c
midl.h
module.c
module.h
mtest.c
mtest2.c
mtest3.c
mtest4.c
mtest5.c
mtest6.c
mtest_enc.c
mtest_enc2.c
mtest_remap.c
sample-bdb.txt
sample-mdb.txt
lz4
lib
README.md
dll
example
README.md
fullbench-dll.sln
lz4.c
lz4.h
lz4frame.c
lz4frame.h
lz4frame_static.h
lz4hc.c
lz4hc.h
xxhash.c
xxhash.h
v8
v8-fast-api-calls-v16.h
v8-fast-api-calls.h
dict
dict.txt
dict2.txt
index.d.ts
index.js
keys.js
level.js
native.js
node-index.js
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
open.js
package.json
read.js
rollup.config.js
src
compression.cpp
cursor.cpp
dbi.cpp
env.cpp
lmdb-js.cpp
lmdb-js.h
misc.cpp
ordered-binary.cpp
txn.cpp
v8-functions.cpp
windows.c
writer.cpp
util
RangeIterable.js
when.js
write.js
load-json-file
index.d.ts
index.js
package.json
readme.md
locate-path
index.d.ts
index.js
package.json
readme.md
lodash.debounce
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
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
lru-cache
README.md
index.js
package.json
make-dir
index.d.ts
index.js
package.json
readme.md
make-error
README.md
dist
make-error.js
index.d.ts
index.js
package.json
map-age-cleaner
dist
index.d.ts
index.js
package.json
readme.md
matcher
index.d.ts
index.js
node_modules
escape-string-regexp
index.d.ts
index.js
package.json
readme.md
package.json
readme.md
md5-hex
browser.js
index.d.ts
index.js
package.json
readme.md
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
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
mem
dist
index.d.ts
index.js
package.json
readme.md
merge2
README.md
index.js
package.json
micromatch
README.md
index.js
package.json
mimic-fn
index.d.ts
index.js
package.json
readme.md
mimic-response
index.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
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
ms
index.js
license.md
package.json
readme.md
msgpackr-extract
README.md
index.js
node_modules
node-gyp-build-optional-packages
README.md
bin.js
build-test.js
index.js
optional.js
package.json
package.json
src
extract.cpp
msgpackr
README.md
SECURITY.md
benchmark.md
dist
index.js
index.min.js
test.js
index.d.ts
index.js
iterators.js
node-index.js
pack.d.ts
pack.js
package.json
rollup.config.js
stream.js
unpack.d.ts
unpack.js
mustache
CHANGELOG.md
README.md
mustache.js
mustache.min.js
package.json
napi-build-utils
README.md
index.js
index.md
package.json
ncp
.travis.yml
LICENSE.md
README.md
lib
ncp.js
package.json
test
ncp.js
near-api-js
README.md
browser-exports.js
dist
near-api-js.js
near-api-js.min.js
lib
account.d.ts
account.js
account_creator.d.ts
account_creator.js
account_multisig.d.ts
account_multisig.js
browser-connect.d.ts
browser-connect.js
browser-index.d.ts
browser-index.js
common-index.d.ts
common-index.js
connect.d.ts
connect.js
connection.d.ts
connection.js
constants.d.ts
constants.js
contract.d.ts
contract.js
generated
rpc_error_schema.json
index.d.ts
index.js
key_stores
browser-index.d.ts
browser-index.js
browser_local_storage_key_store.d.ts
browser_local_storage_key_store.js
in_memory_key_store.d.ts
in_memory_key_store.js
index.d.ts
index.js
keystore.d.ts
keystore.js
merge_key_store.d.ts
merge_key_store.js
unencrypted_file_system_keystore.d.ts
unencrypted_file_system_keystore.js
near.d.ts
near.js
providers
index.d.ts
index.js
json-rpc-provider.d.ts
json-rpc-provider.js
provider.d.ts
provider.js
res
error_messages.d.ts
error_messages.json
signer.d.ts
signer.js
transaction.d.ts
transaction.js
utils
enums.d.ts
enums.js
errors.d.ts
errors.js
exponential-backoff.d.ts
exponential-backoff.js
format.d.ts
format.js
index.d.ts
index.js
key_pair.d.ts
key_pair.js
network.d.ts
network.js
rpc_errors.d.ts
rpc_errors.js
serialize.d.ts
serialize.js
setup-node-fetch.d.ts
setup-node-fetch.js
web.d.ts
web.js
validators.d.ts
validators.js
wallet-account.d.ts
wallet-account.js
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
node_modules
ansi-styles
index.d.ts
index.js
package.json
readme.md
chalk
index.d.ts
package.json
readme.md
source
index.js
templates.js
util.js
emoji-regex
LICENSE-MIT.txt
README.md
es2015
index.js
text.js
index.d.ts
index.js
package.json
text.js
has-flag
index.d.ts
index.js
package.json
readme.md
is-fullwidth-code-point
index.d.ts
index.js
package.json
readme.md
string-width
index.d.ts
index.js
package.json
readme.md
strip-ansi
index.d.ts
index.js
package.json
readme.md
supports-color
browser.js
index.js
package.json
readme.md
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.json
test_environment.js
utils
capture-login-success.js
check-credentials.js
check-version.js
connect.js
create-dev-account.js
deprecation-warning.js
error-handlers.js
eventtracking.js
exit-on-error.js
explorer.js
implicit-accountid.js
inspect-response.js
log-event.js
readline.js
settings.js
validators-info.js
verify-account.js
x-api-key-settings.js
near-hd-key
README.md
dist
index.d.ts
index.js
utils.d.ts
utils.js
package.json
near-ledger-js
.travis.yml
README.md
demo
demo.js
index.html
index.js
package.json
supportedTransports.js
near-seed-phrase
.eslintrc.yml
.fossa.yml
.travis.yml
index.js
package.json
test
index.test.js
node-abi
.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-optional-packages
README.md
bin.js
build-test.js
index.js
optional.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
node-releases
README.md
data
processed
envs.json
release-schedule
release-schedule.json
package.json
nodemon
.eslintrc.json
.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
node.js
package.json
src
browser.js
common.js
index.js
node.js
ignore-by-default
README.md
index.js
package.json
semver
CHANGELOG.md
README.md
package.json
semver.js
package.json
nofilter
LICENSE.md
README.md
lib
index.js
package.json
types
index.d.ts
nopt
README.md
bin
nopt.js
examples
my-program.js
lib
nopt.js
package.json
normalize-path
README.md
index.js
package.json
normalize-url
index.d.ts
index.js
package.json
readme.md
npmlog
CHANGELOG.md
README.md
log.js
package.json
nth-check
README.md
lib
compile.d.ts
compile.js
esm
compile.d.ts
compile.js
index.d.ts
index.js
package.json
parse.d.ts
parse.js
index.d.ts
index.js
parse.d.ts
parse.js
package.json
nullthrows
README.md
nullthrows.d.ts
nullthrows.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
object-keys
.travis.yml
CHANGELOG.md
README.md
implementation.js
index.js
isArguments.js
package.json
test
index.js
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
once
README.md
once.js
package.json
open
index.d.ts
index.js
package.json
readme.md
ordered-binary
README.md
index.d.ts
index.js
package.json
rollup.config.js
tests
test.js
uuid.js
p-cancelable
index.d.ts
index.js
package.json
readme.md
p-defer
index.js
package.json
readme.md
p-event
index.d.ts
index.js
package.json
readme.md
p-limit
index.d.ts
index.js
package.json
readme.md
p-locate
index.d.ts
index.js
package.json
readme.md
p-map
index.d.ts
index.js
package.json
readme.md
p-timeout
index.d.ts
index.js
package.json
readme.md
package-json
index.d.ts
index.js
package.json
readme.md
parcel
README.md
lib
bin.js
cli.js
node_modules
ansi-styles
index.d.ts
index.js
package.json
readme.md
chalk
index.d.ts
package.json
readme.md
source
index.js
templates.js
util.js
commander
CHANGELOG.md
Readme.md
index.js
package-support.json
package.json
typings
index.d.ts
has-flag
index.d.ts
index.js
package.json
readme.md
supports-color
browser.js
index.js
package.json
readme.md
package.json
src
.eslintrc.json
bin.js
cli.js
parent-module
index.js
node_modules
callsites
index.d.ts
index.js
package.json
readme.md
package.json
readme.md
parse-json
index.js
package.json
readme.md
parse-ms
index.d.ts
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
path-parse
README.md
index.js
package.json
path-type
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
picocolors
README.md
package.json
picocolors.browser.js
picocolors.d.ts
picocolors.js
types.ts
picomatch
CHANGELOG.md
README.md
index.js
lib
constants.js
parse.js
picomatch.js
scan.js
utils.js
package.json
pkg-conf
index.d.ts
index.js
package.json
readme.md
platform
README.md
package.json
platform.js
plur
index.d.ts
index.js
package.json
readme.md
postcss-value-parser
README.md
lib
index.d.ts
index.js
parse.js
stringify.js
unit.js
walk.js
package.json
posthtml-parser
changelog.md
dist
chunk.T6SARJYH.js
index.d.ts
index.js
location-tracker.d.ts
location-tracker.js
package.json
readme.md
posthtml-render
changelog.md
dist
index.d.ts
index.js
package.json
readme.md
posthtml
lib
api.js
index.js
node_modules
posthtml-parser
dist
chunk.2UQLUWPH.js
index.d.ts
index.js
location-tracker.d.ts
location-tracker.js
package.json
readme.md
package.json
readme.md
types
posthtml.d.ts
prebuild-install
CHANGELOG.md
CONTRIBUTING.md
README.md
asset.js
bin.js
download.js
error.js
help.txt
index.js
log.js
package.json
proxy.js
rc.js
util.js
prepend-http
index.js
package.json
readme.md
pretty-format
README.md
build
collections.d.ts
collections.js
index.d.ts
index.js
plugins
AsymmetricMatcher.d.ts
AsymmetricMatcher.js
ConvertAnsi.d.ts
ConvertAnsi.js
DOMCollection.d.ts
DOMCollection.js
DOMElement.d.ts
DOMElement.js
Immutable.d.ts
Immutable.js
ReactElement.d.ts
ReactElement.js
ReactTestComponent.d.ts
ReactTestComponent.js
lib
escapeHTML.d.ts
escapeHTML.js
markup.d.ts
markup.js
types.d.ts
types.js
node_modules
ansi-styles
index.d.ts
index.js
package.json
readme.md
package.json
pretty-ms
index.d.ts
index.js
package.json
readme.md
process-nextick-args
index.js
license.md
package.json
readme.md
process
README.md
browser.js
index.js
package.json
test.js
pstree.remy
.travis.yml
README.md
lib
index.js
tree.js
utils.js
package.json
tests
fixtures
index.js
index.test.js
pump
.travis.yml
README.md
index.js
package.json
test-browser.js
test-node.js
pupa
index.d.ts
index.js
package.json
readme.md
queue-microtask
README.md
index.d.ts
index.js
package.json
randombytes
.travis.yml
.zuul.yml
README.md
browser.js
index.js
package.json
test.js
rc
README.md
browser.js
cli.js
index.js
lib
utils.js
package.json
test
ini.js
nested-env-vars.js
test.js
react-dom
README.md
cjs
react-dom-server-legacy.browser.development.js
react-dom-server-legacy.browser.production.min.js
react-dom-server-legacy.node.development.js
react-dom-server-legacy.node.production.min.js
react-dom-server.browser.development.js
react-dom-server.browser.production.min.js
react-dom-server.node.development.js
react-dom-server.node.production.min.js
react-dom-test-utils.development.js
react-dom-test-utils.production.min.js
react-dom.development.js
react-dom.production.min.js
react-dom.profiling.min.js
client.js
index.js
package.json
profiling.js
server.browser.js
server.js
server.node.js
test-utils.js
umd
react-dom-server-legacy.browser.development.js
react-dom-server-legacy.browser.production.min.js
react-dom-server.browser.development.js
react-dom-server.browser.production.min.js
react-dom-test-utils.development.js
react-dom-test-utils.production.min.js
react-dom.production.min.js
react-dom.profiling.min.js
react-error-overlay
README.md
lib
index.js
package.json
react-is
README.md
build-info.json
cjs
react-is.development.js
react-is.production.min.js
index.js
package.json
umd
react-is.development.js
react-is.production.min.js
react-refresh
README.md
babel.js
build-info.json
cjs
react-refresh-babel.development.js
react-refresh-babel.production.min.js
react-refresh-runtime.development.js
react-refresh-runtime.production.min.js
package.json
runtime.js
react-shallow-renderer
README.md
cjs
react-shallow-renderer.js
esm
index.js
react-shallow-renderer.js
index.js
package.json
umd
react-shallow-renderer.js
react-test-renderer
README.md
cjs
react-test-renderer.development.js
react-test-renderer.production.min.js
index.js
node_modules
react-is
README.md
cjs
react-is.development.js
react-is.production.min.js
index.js
package.json
umd
react-is.development.js
react-is.production.min.js
package.json
shallow.js
umd
react-test-renderer.development.js
react-test-renderer.production.min.js
react
README.md
cjs
react-jsx-dev-runtime.development.js
react-jsx-dev-runtime.production.min.js
react-jsx-dev-runtime.profiling.min.js
react-jsx-runtime.development.js
react-jsx-runtime.production.min.js
react-jsx-runtime.profiling.min.js
react.development.js
react.production.min.js
react.shared-subset.development.js
react.shared-subset.production.min.js
index.js
jsx-dev-runtime.js
jsx-runtime.js
package.json
react.shared-subset.js
umd
react.development.js
react.production.min.js
react.profiling.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
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
Property_of_Strings
Basic_Emoji.js
Emoji_Keycap_Sequence.js
RGI_Emoji.js
RGI_Emoji_Flag_Sequence.js
RGI_Emoji_Modifier_Sequence.js
RGI_Emoji_Tag_Sequence.js
RGI_Emoji_ZWJ_Sequence.js
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
Cypro_Minoan.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
Old_Uyghur.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
Tangsa.js
Tangut.js
Telugu.js
Thaana.js
Thai.js
Tibetan.js
Tifinagh.js
Tirhuta.js
Toto.js
Ugaritic.js
Vai.js
Vithkuqi.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
Cypro_Minoan.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
Old_Uyghur.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
Tangsa.js
Tangut.js
Telugu.js
Thaana.js
Thai.js
Tibetan.js
Tifinagh.js
Tirhuta.js
Toto.js
Ugaritic.js
Vai.js
Vithkuqi.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
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
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.d.ts
parser.js
require-directory
.travis.yml
index.js
package.json
resolve-cwd
index.d.ts
index.js
node_modules
resolve-from
index.d.ts
index.js
package.json
readme.md
package.json
readme.md
resolve-from
index.js
package.json
readme.md
resolve
.github
FUNDING.yml
SECURITY.md
async.js
example
async.js
sync.js
index.js
lib
async.js
caller.js
core.js
core.json
homedir.js
is-core.js
node-modules-paths.js
normalize-options.js
sync.js
package.json
sync.js
test
core.js
dotdot.js
dotdot
abc
index.js
index.js
faulty_basedir.js
filter.js
filter_sync.js
home_paths.js
home_paths_sync.js
mock.js
mock_sync.js
module_dir.js
module_dir
xmodules
aaa
index.js
ymodules
aaa
index.js
zmodules
bbb
main.js
package.json
node-modules-paths.js
node_path.js
node_path
x
aaa
index.js
ccc
index.js
y
bbb
index.js
ccc
index.js
nonstring.js
pathfilter.js
pathfilter
deep_ref
main.js
precedence.js
precedence
aaa.js
aaa
index.js
main.js
bbb.js
bbb
main.js
resolver.js
resolver
baz
doom.js
package.json
quux.js
browser_field
a.js
b.js
package.json
cup.coffee
dot_main
index.js
package.json
dot_slash_main
index.js
package.json
false_main
index.js
package.json
foo.js
incorrect_main
index.js
package.json
invalid_main
package.json
malformed_package_json
index.js
package.json
mug.coffee
mug.js
multirepo
lerna.json
package.json
packages
package-a
index.js
package.json
package-b
index.js
package.json
nested_symlinks
mylib
async.js
package.json
sync.js
other_path
lib
other-lib.js
root.js
quux
foo
index.js
same_names
foo.js
foo
index.js
symlinked
_
node_modules
foo.js
package
bar.js
package.json
without_basedir
main.js
resolver_sync.js
shadowed_core.js
shadowed_core
node_modules
util
index.js
subdirs.js
symlinks.js
responselike
README.md
package.json
src
index.js
reusify
.coveralls.yml
.travis.yml
README.md
benchmarks
createNoCodeFunction.js
fib.js
reuseNoCodeFunction.js
package.json
reusify.js
test.js
rimraf
CHANGELOG.md
README.md
bin.js
package.json
rimraf.js
ripemd160
CHANGELOG.md
README.md
index.js
package.json
run-parallel
README.md
index.js
package.json
rxjs
AsyncSubject.d.ts
AsyncSubject.js
BehaviorSubject.d.ts
BehaviorSubject.js
InnerSubscriber.d.ts
InnerSubscriber.js
LICENSE.txt
Notification.d.ts
Notification.js
Observable.d.ts
Observable.js
Observer.d.ts
Observer.js
Operator.d.ts
Operator.js
OuterSubscriber.d.ts
OuterSubscriber.js
README.md
ReplaySubject.d.ts
ReplaySubject.js
Rx.d.ts
Rx.js
Scheduler.d.ts
Scheduler.js
Subject.d.ts
Subject.js
SubjectSubscription.d.ts
SubjectSubscription.js
Subscriber.d.ts
Subscriber.js
Subscription.d.ts
Subscription.js
_esm2015
LICENSE.txt
README.md
ajax
index.js
fetch
index.js
index.js
internal-compatibility
index.js
internal
AsyncSubject.js
BehaviorSubject.js
InnerSubscriber.js
Notification.js
Observable.js
Observer.js
Operator.js
OuterSubscriber.js
ReplaySubject.js
Rx.js
Scheduler.js
Subject.js
SubjectSubscription.js
Subscriber.js
Subscription.js
config.js
innerSubscribe.js
observable
ConnectableObservable.js
SubscribeOnObservable.js
bindCallback.js
bindNodeCallback.js
combineLatest.js
concat.js
defer.js
dom
AjaxObservable.js
WebSocketSubject.js
ajax.js
fetch.js
webSocket.js
empty.js
forkJoin.js
from.js
fromArray.js
fromEvent.js
fromEventPattern.js
fromIterable.js
fromPromise.js
generate.js
iif.js
interval.js
merge.js
never.js
of.js
onErrorResumeNext.js
pairs.js
partition.js
race.js
range.js
throwError.js
timer.js
using.js
zip.js
operators
audit.js
auditTime.js
buffer.js
bufferCount.js
bufferTime.js
bufferToggle.js
bufferWhen.js
catchError.js
combineAll.js
combineLatest.js
concat.js
concatAll.js
concatMap.js
concatMapTo.js
count.js
debounce.js
debounceTime.js
defaultIfEmpty.js
delay.js
delayWhen.js
dematerialize.js
distinct.js
distinctUntilChanged.js
distinctUntilKeyChanged.js
elementAt.js
endWith.js
every.js
exhaust.js
exhaustMap.js
expand.js
filter.js
finalize.js
find.js
findIndex.js
first.js
groupBy.js
ignoreElements.js
index.js
isEmpty.js
last.js
map.js
mapTo.js
materialize.js
max.js
merge.js
mergeAll.js
mergeMap.js
mergeMapTo.js
mergeScan.js
min.js
multicast.js
observeOn.js
onErrorResumeNext.js
pairwise.js
partition.js
pluck.js
publish.js
publishBehavior.js
publishLast.js
publishReplay.js
race.js
reduce.js
refCount.js
repeat.js
repeatWhen.js
retry.js
retryWhen.js
sample.js
sampleTime.js
scan.js
sequenceEqual.js
share.js
shareReplay.js
single.js
skip.js
skipLast.js
skipUntil.js
skipWhile.js
startWith.js
subscribeOn.js
switchAll.js
switchMap.js
switchMapTo.js
take.js
takeLast.js
takeUntil.js
takeWhile.js
tap.js
throttle.js
throttleTime.js
throwIfEmpty.js
timeInterval.js
timeout.js
timeoutWith.js
timestamp.js
toArray.js
window.js
windowCount.js
windowTime.js
windowToggle.js
windowWhen.js
withLatestFrom.js
zip.js
zipAll.js
scheduled
scheduleArray.js
scheduleIterable.js
scheduleObservable.js
schedulePromise.js
scheduled.js
scheduler
Action.js
AnimationFrameAction.js
AnimationFrameScheduler.js
AsapAction.js
AsapScheduler.js
AsyncAction.js
AsyncScheduler.js
QueueAction.js
QueueScheduler.js
VirtualTimeScheduler.js
animationFrame.js
asap.js
async.js
queue.js
symbol
iterator.js
observable.js
rxSubscriber.js
testing
ColdObservable.js
HotObservable.js
SubscriptionLog.js
SubscriptionLoggable.js
TestMessage.js
TestScheduler.js
types.js
util
ArgumentOutOfRangeError.js
EmptyError.js
Immediate.js
ObjectUnsubscribedError.js
TimeoutError.js
UnsubscriptionError.js
applyMixins.js
canReportError.js
errorObject.js
hostReportError.js
identity.js
isArray.js
isArrayLike.js
isDate.js
isFunction.js
isInteropObservable.js
isIterable.js
isNumeric.js
isObject.js
isObservable.js
isPromise.js
isScheduler.js
noop.js
not.js
pipe.js
root.js
subscribeTo.js
subscribeToArray.js
subscribeToIterable.js
subscribeToObservable.js
subscribeToPromise.js
subscribeToResult.js
toSubscriber.js
tryCatch.js
operators
index.js
path-mapping.js
testing
index.js
webSocket
index.js
_esm5
LICENSE.txt
README.md
ajax
index.js
fetch
index.js
index.js
internal-compatibility
index.js
internal
AsyncSubject.js
BehaviorSubject.js
InnerSubscriber.js
Notification.js
Observable.js
Observer.js
Operator.js
OuterSubscriber.js
ReplaySubject.js
Rx.js
Scheduler.js
Subject.js
SubjectSubscription.js
Subscriber.js
Subscription.js
config.js
innerSubscribe.js
observable
ConnectableObservable.js
SubscribeOnObservable.js
bindCallback.js
bindNodeCallback.js
combineLatest.js
concat.js
defer.js
dom
AjaxObservable.js
WebSocketSubject.js
ajax.js
fetch.js
webSocket.js
empty.js
forkJoin.js
from.js
fromArray.js
fromEvent.js
fromEventPattern.js
fromIterable.js
fromPromise.js
generate.js
iif.js
interval.js
merge.js
never.js
of.js
onErrorResumeNext.js
pairs.js
partition.js
race.js
range.js
throwError.js
timer.js
using.js
zip.js
operators
audit.js
auditTime.js
buffer.js
bufferCount.js
bufferTime.js
bufferToggle.js
bufferWhen.js
catchError.js
combineAll.js
combineLatest.js
concat.js
concatAll.js
concatMap.js
concatMapTo.js
count.js
debounce.js
debounceTime.js
defaultIfEmpty.js
delay.js
delayWhen.js
dematerialize.js
distinct.js
distinctUntilChanged.js
distinctUntilKeyChanged.js
elementAt.js
endWith.js
every.js
exhaust.js
exhaustMap.js
expand.js
filter.js
finalize.js
find.js
findIndex.js
first.js
groupBy.js
ignoreElements.js
index.js
isEmpty.js
last.js
map.js
mapTo.js
materialize.js
max.js
merge.js
mergeAll.js
mergeMap.js
mergeMapTo.js
mergeScan.js
min.js
multicast.js
observeOn.js
onErrorResumeNext.js
pairwise.js
partition.js
pluck.js
publish.js
publishBehavior.js
publishLast.js
publishReplay.js
race.js
reduce.js
refCount.js
repeat.js
repeatWhen.js
retry.js
retryWhen.js
sample.js
sampleTime.js
scan.js
sequenceEqual.js
share.js
shareReplay.js
single.js
skip.js
skipLast.js
skipUntil.js
skipWhile.js
startWith.js
subscribeOn.js
switchAll.js
switchMap.js
switchMapTo.js
take.js
takeLast.js
takeUntil.js
takeWhile.js
tap.js
throttle.js
throttleTime.js
throwIfEmpty.js
timeInterval.js
timeout.js
timeoutWith.js
timestamp.js
toArray.js
window.js
windowCount.js
windowTime.js
windowToggle.js
windowWhen.js
withLatestFrom.js
zip.js
zipAll.js
scheduled
scheduleArray.js
scheduleIterable.js
scheduleObservable.js
schedulePromise.js
scheduled.js
scheduler
Action.js
AnimationFrameAction.js
AnimationFrameScheduler.js
AsapAction.js
AsapScheduler.js
AsyncAction.js
AsyncScheduler.js
QueueAction.js
QueueScheduler.js
VirtualTimeScheduler.js
animationFrame.js
asap.js
async.js
queue.js
symbol
iterator.js
observable.js
rxSubscriber.js
testing
ColdObservable.js
HotObservable.js
SubscriptionLog.js
SubscriptionLoggable.js
TestMessage.js
TestScheduler.js
types.js
util
ArgumentOutOfRangeError.js
EmptyError.js
Immediate.js
ObjectUnsubscribedError.js
TimeoutError.js
UnsubscriptionError.js
applyMixins.js
canReportError.js
errorObject.js
hostReportError.js
identity.js
isArray.js
isArrayLike.js
isDate.js
isFunction.js
isInteropObservable.js
isIterable.js
isNumeric.js
isObject.js
isObservable.js
isPromise.js
isScheduler.js
noop.js
not.js
pipe.js
root.js
subscribeTo.js
subscribeToArray.js
subscribeToIterable.js
subscribeToObservable.js
subscribeToPromise.js
subscribeToResult.js
toSubscriber.js
tryCatch.js
operators
index.js
path-mapping.js
testing
index.js
webSocket
index.js
add
observable
bindCallback.d.ts
bindCallback.js
bindNodeCallback.d.ts
bindNodeCallback.js
combineLatest.d.ts
combineLatest.js
concat.d.ts
concat.js
defer.d.ts
defer.js
dom
ajax.d.ts
ajax.js
webSocket.d.ts
webSocket.js
empty.d.ts
empty.js
forkJoin.d.ts
forkJoin.js
from.d.ts
from.js
fromEvent.d.ts
fromEvent.js
fromEventPattern.d.ts
fromEventPattern.js
fromPromise.d.ts
fromPromise.js
generate.d.ts
generate.js
if.d.ts
if.js
interval.d.ts
interval.js
merge.d.ts
merge.js
never.d.ts
never.js
of.d.ts
of.js
onErrorResumeNext.d.ts
onErrorResumeNext.js
pairs.d.ts
pairs.js
race.d.ts
race.js
range.d.ts
range.js
throw.d.ts
throw.js
timer.d.ts
timer.js
using.d.ts
using.js
zip.d.ts
zip.js
operator
audit.d.ts
audit.js
auditTime.d.ts
auditTime.js
buffer.d.ts
buffer.js
bufferCount.d.ts
bufferCount.js
bufferTime.d.ts
bufferTime.js
bufferToggle.d.ts
bufferToggle.js
bufferWhen.d.ts
bufferWhen.js
catch.d.ts
catch.js
combineAll.d.ts
combineAll.js
combineLatest.d.ts
combineLatest.js
concat.d.ts
concat.js
concatAll.d.ts
concatAll.js
concatMap.d.ts
concatMap.js
concatMapTo.d.ts
concatMapTo.js
count.d.ts
count.js
debounce.d.ts
debounce.js
debounceTime.d.ts
debounceTime.js
defaultIfEmpty.d.ts
defaultIfEmpty.js
delay.d.ts
delay.js
delayWhen.d.ts
delayWhen.js
dematerialize.d.ts
dematerialize.js
distinct.d.ts
distinct.js
distinctUntilChanged.d.ts
distinctUntilChanged.js
distinctUntilKeyChanged.d.ts
distinctUntilKeyChanged.js
do.d.ts
do.js
elementAt.d.ts
elementAt.js
every.d.ts
every.js
exhaust.d.ts
exhaust.js
exhaustMap.d.ts
exhaustMap.js
expand.d.ts
expand.js
filter.d.ts
filter.js
finally.d.ts
finally.js
find.d.ts
find.js
findIndex.d.ts
findIndex.js
first.d.ts
first.js
groupBy.d.ts
groupBy.js
ignoreElements.d.ts
ignoreElements.js
isEmpty.d.ts
isEmpty.js
last.d.ts
last.js
let.d.ts
let.js
map.d.ts
map.js
mapTo.d.ts
mapTo.js
materialize.d.ts
materialize.js
max.d.ts
max.js
merge.d.ts
merge.js
mergeAll.d.ts
mergeAll.js
mergeMap.d.ts
mergeMap.js
mergeMapTo.d.ts
mergeMapTo.js
mergeScan.d.ts
mergeScan.js
min.d.ts
min.js
multicast.d.ts
multicast.js
observeOn.d.ts
observeOn.js
onErrorResumeNext.d.ts
onErrorResumeNext.js
pairwise.d.ts
pairwise.js
partition.d.ts
partition.js
pluck.d.ts
pluck.js
publish.d.ts
publish.js
publishBehavior.d.ts
publishBehavior.js
publishLast.d.ts
publishLast.js
publishReplay.d.ts
publishReplay.js
race.d.ts
race.js
reduce.d.ts
reduce.js
repeat.d.ts
repeat.js
repeatWhen.d.ts
repeatWhen.js
retry.d.ts
retry.js
retryWhen.d.ts
retryWhen.js
sample.d.ts
sample.js
sampleTime.d.ts
sampleTime.js
scan.d.ts
scan.js
sequenceEqual.d.ts
sequenceEqual.js
share.d.ts
share.js
shareReplay.d.ts
shareReplay.js
single.d.ts
single.js
skip.d.ts
skip.js
skipLast.d.ts
skipLast.js
skipUntil.d.ts
skipUntil.js
skipWhile.d.ts
skipWhile.js
startWith.d.ts
startWith.js
subscribeOn.d.ts
subscribeOn.js
switch.d.ts
switch.js
switchMap.d.ts
switchMap.js
switchMapTo.d.ts
switchMapTo.js
take.d.ts
take.js
takeLast.d.ts
takeLast.js
takeUntil.d.ts
takeUntil.js
takeWhile.d.ts
takeWhile.js
throttle.d.ts
throttle.js
throttleTime.d.ts
throttleTime.js
timeInterval.d.ts
timeInterval.js
timeout.d.ts
timeout.js
timeoutWith.d.ts
timeoutWith.js
timestamp.d.ts
timestamp.js
toArray.d.ts
toArray.js
toPromise.d.ts
toPromise.js
window.d.ts
window.js
windowCount.d.ts
windowCount.js
windowTime.d.ts
windowTime.js
windowToggle.d.ts
windowToggle.js
windowWhen.d.ts
windowWhen.js
withLatestFrom.d.ts
withLatestFrom.js
zip.d.ts
zip.js
zipAll.d.ts
zipAll.js
ajax
index.d.ts
index.js
package.json
bundles
rxjs.umd.js
rxjs.umd.min.js
fetch
index.d.ts
index.js
package.json
index.d.ts
index.js
interfaces.d.ts
interfaces.js
internal-compatibility
index.d.ts
index.js
package.json
internal
AsyncSubject.d.ts
AsyncSubject.js
BehaviorSubject.d.ts
BehaviorSubject.js
InnerSubscriber.d.ts
InnerSubscriber.js
Notification.d.ts
Notification.js
Observable.d.ts
Observable.js
Observer.d.ts
Observer.js
Operator.d.ts
Operator.js
OuterSubscriber.d.ts
OuterSubscriber.js
ReplaySubject.d.ts
ReplaySubject.js
Rx.d.ts
Rx.js
Scheduler.d.ts
Scheduler.js
Subject.d.ts
Subject.js
SubjectSubscription.d.ts
SubjectSubscription.js
Subscriber.d.ts
Subscriber.js
Subscription.d.ts
Subscription.js
config.d.ts
config.js
innerSubscribe.d.ts
innerSubscribe.js
observable
ConnectableObservable.d.ts
ConnectableObservable.js
SubscribeOnObservable.d.ts
SubscribeOnObservable.js
bindCallback.d.ts
bindCallback.js
bindNodeCallback.d.ts
bindNodeCallback.js
combineLatest.d.ts
combineLatest.js
concat.d.ts
concat.js
defer.d.ts
defer.js
dom
AjaxObservable.d.ts
AjaxObservable.js
WebSocketSubject.d.ts
WebSocketSubject.js
ajax.d.ts
ajax.js
fetch.d.ts
fetch.js
webSocket.d.ts
webSocket.js
empty.d.ts
empty.js
forkJoin.d.ts
forkJoin.js
from.d.ts
from.js
fromArray.d.ts
fromArray.js
fromEvent.d.ts
fromEvent.js
fromEventPattern.d.ts
fromEventPattern.js
fromIterable.d.ts
fromIterable.js
fromPromise.d.ts
fromPromise.js
generate.d.ts
generate.js
iif.d.ts
iif.js
interval.d.ts
interval.js
merge.d.ts
merge.js
never.d.ts
never.js
of.d.ts
of.js
onErrorResumeNext.d.ts
onErrorResumeNext.js
pairs.d.ts
pairs.js
partition.d.ts
partition.js
race.d.ts
race.js
range.d.ts
range.js
throwError.d.ts
throwError.js
timer.d.ts
timer.js
using.d.ts
using.js
zip.d.ts
zip.js
operators
audit.d.ts
audit.js
auditTime.d.ts
auditTime.js
buffer.d.ts
buffer.js
bufferCount.d.ts
bufferCount.js
bufferTime.d.ts
bufferTime.js
bufferToggle.d.ts
bufferToggle.js
bufferWhen.d.ts
bufferWhen.js
catchError.d.ts
catchError.js
combineAll.d.ts
combineAll.js
combineLatest.d.ts
combineLatest.js
concat.d.ts
concat.js
concatAll.d.ts
concatAll.js
concatMap.d.ts
concatMap.js
concatMapTo.d.ts
concatMapTo.js
count.d.ts
count.js
debounce.d.ts
debounce.js
debounceTime.d.ts
debounceTime.js
defaultIfEmpty.d.ts
defaultIfEmpty.js
delay.d.ts
delay.js
delayWhen.d.ts
delayWhen.js
dematerialize.d.ts
dematerialize.js
distinct.d.ts
distinct.js
distinctUntilChanged.d.ts
distinctUntilChanged.js
distinctUntilKeyChanged.d.ts
distinctUntilKeyChanged.js
elementAt.d.ts
elementAt.js
endWith.d.ts
endWith.js
every.d.ts
every.js
exhaust.d.ts
exhaust.js
exhaustMap.d.ts
exhaustMap.js
expand.d.ts
expand.js
filter.d.ts
filter.js
finalize.d.ts
finalize.js
find.d.ts
find.js
findIndex.d.ts
findIndex.js
first.d.ts
first.js
groupBy.d.ts
groupBy.js
ignoreElements.d.ts
ignoreElements.js
index.d.ts
index.js
isEmpty.d.ts
isEmpty.js
last.d.ts
last.js
map.d.ts
map.js
mapTo.d.ts
mapTo.js
materialize.d.ts
materialize.js
max.d.ts
max.js
merge.d.ts
merge.js
mergeAll.d.ts
mergeAll.js
mergeMap.d.ts
mergeMap.js
mergeMapTo.d.ts
mergeMapTo.js
mergeScan.d.ts
mergeScan.js
min.d.ts
min.js
multicast.d.ts
multicast.js
observeOn.d.ts
observeOn.js
onErrorResumeNext.d.ts
onErrorResumeNext.js
pairwise.d.ts
pairwise.js
partition.d.ts
partition.js
pluck.d.ts
pluck.js
publish.d.ts
publish.js
publishBehavior.d.ts
publishBehavior.js
publishLast.d.ts
publishLast.js
publishReplay.d.ts
publishReplay.js
race.d.ts
race.js
reduce.d.ts
reduce.js
refCount.d.ts
refCount.js
repeat.d.ts
repeat.js
repeatWhen.d.ts
repeatWhen.js
retry.d.ts
retry.js
retryWhen.d.ts
retryWhen.js
sample.d.ts
sample.js
sampleTime.d.ts
sampleTime.js
scan.d.ts
scan.js
sequenceEqual.d.ts
sequenceEqual.js
share.d.ts
share.js
shareReplay.d.ts
shareReplay.js
single.d.ts
single.js
skip.d.ts
skip.js
skipLast.d.ts
skipLast.js
skipUntil.d.ts
skipUntil.js
skipWhile.d.ts
skipWhile.js
startWith.d.ts
startWith.js
subscribeOn.d.ts
subscribeOn.js
switchAll.d.ts
switchAll.js
switchMap.d.ts
switchMap.js
switchMapTo.d.ts
switchMapTo.js
take.d.ts
take.js
takeLast.d.ts
takeLast.js
takeUntil.d.ts
takeUntil.js
takeWhile.d.ts
takeWhile.js
tap.d.ts
tap.js
throttle.d.ts
throttle.js
throttleTime.d.ts
throttleTime.js
throwIfEmpty.d.ts
throwIfEmpty.js
timeInterval.d.ts
timeInterval.js
timeout.d.ts
timeout.js
timeoutWith.d.ts
timeoutWith.js
timestamp.d.ts
timestamp.js
toArray.d.ts
toArray.js
window.d.ts
window.js
windowCount.d.ts
windowCount.js
windowTime.d.ts
windowTime.js
windowToggle.d.ts
windowToggle.js
windowWhen.d.ts
windowWhen.js
withLatestFrom.d.ts
withLatestFrom.js
zip.d.ts
zip.js
zipAll.d.ts
zipAll.js
scheduled
scheduleArray.d.ts
scheduleArray.js
scheduleIterable.d.ts
scheduleIterable.js
scheduleObservable.d.ts
scheduleObservable.js
schedulePromise.d.ts
schedulePromise.js
scheduled.d.ts
scheduled.js
scheduler
Action.d.ts
Action.js
AnimationFrameAction.d.ts
AnimationFrameAction.js
AnimationFrameScheduler.d.ts
AnimationFrameScheduler.js
AsapAction.d.ts
AsapAction.js
AsapScheduler.d.ts
AsapScheduler.js
AsyncAction.d.ts
AsyncAction.js
AsyncScheduler.d.ts
AsyncScheduler.js
QueueAction.d.ts
QueueAction.js
QueueScheduler.d.ts
QueueScheduler.js
VirtualTimeScheduler.d.ts
VirtualTimeScheduler.js
animationFrame.d.ts
animationFrame.js
asap.d.ts
asap.js
async.d.ts
async.js
queue.d.ts
queue.js
symbol
iterator.d.ts
iterator.js
observable.d.ts
observable.js
rxSubscriber.d.ts
rxSubscriber.js
testing
ColdObservable.d.ts
ColdObservable.js
HotObservable.d.ts
HotObservable.js
SubscriptionLog.d.ts
SubscriptionLog.js
SubscriptionLoggable.d.ts
SubscriptionLoggable.js
TestMessage.d.ts
TestMessage.js
TestScheduler.d.ts
TestScheduler.js
types.d.ts
types.js
util
ArgumentOutOfRangeError.d.ts
ArgumentOutOfRangeError.js
EmptyError.d.ts
EmptyError.js
Immediate.d.ts
Immediate.js
ObjectUnsubscribedError.d.ts
ObjectUnsubscribedError.js
TimeoutError.d.ts
TimeoutError.js
UnsubscriptionError.d.ts
UnsubscriptionError.js
applyMixins.d.ts
applyMixins.js
canReportError.d.ts
canReportError.js
errorObject.d.ts
errorObject.js
hostReportError.d.ts
hostReportError.js
identity.d.ts
identity.js
isArray.d.ts
isArray.js
isArrayLike.d.ts
isArrayLike.js
isDate.d.ts
isDate.js
isFunction.d.ts
isFunction.js
isInteropObservable.d.ts
isInteropObservable.js
isIterable.d.ts
isIterable.js
isNumeric.d.ts
isNumeric.js
isObject.d.ts
isObject.js
isObservable.d.ts
isObservable.js
isPromise.d.ts
isPromise.js
isScheduler.d.ts
isScheduler.js
noop.d.ts
noop.js
not.d.ts
not.js
pipe.d.ts
pipe.js
root.d.ts
root.js
subscribeTo.d.ts
subscribeTo.js
subscribeToArray.d.ts
subscribeToArray.js
subscribeToIterable.d.ts
subscribeToIterable.js
subscribeToObservable.d.ts
subscribeToObservable.js
subscribeToPromise.d.ts
subscribeToPromise.js
subscribeToResult.d.ts
subscribeToResult.js
toSubscriber.d.ts
toSubscriber.js
tryCatch.d.ts
tryCatch.js
migrations
collection.json
update-6_0_0
index.js
node_modules
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
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
scheduler
README.md
cjs
scheduler-unstable_mock.development.js
scheduler-unstable_mock.production.min.js
scheduler-unstable_post_task.development.js
scheduler-unstable_post_task.production.min.js
scheduler.development.js
scheduler.production.min.js
index.js
package.json
umd
scheduler-unstable_mock.development.js
scheduler-unstable_mock.production.min.js
scheduler.development.js
scheduler.production.min.js
scheduler.profiling.min.js
unstable_mock.js
unstable_post_task.js
semver-diff
index.d.ts
index.js
package.json
readme.md
semver
CHANGELOG.md
README.md
bin
semver.js
package.json
semver.js
serialize-error
index.d.ts
index.js
package.json
readme.md
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
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
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
node_modules
safe-buffer
README.md
index.d.ts
index.js
package.json
package.json
strip-ansi
index.d.ts
index.js
node_modules
ansi-regex
index.d.ts
index.js
package.json
readme.md
package.json
readme.md
strip-json-comments
index.js
package.json
readme.md
supertap
dist
index.d.ts
index.js
package.json
readme.md
supports-color
browser.js
index.js
package.json
readme.md
supports-preserve-symlinks-flag
.github
FUNDING.yml
CHANGELOG.md
README.md
browser.js
index.js
package.json
test
index.js
svgo
README.md
dist
svgo.browser.js
lib
css-tools.js
parser.js
path.js
stringifier.js
style.js
svgo-node.js
svgo.js
svgo
coa.js
config.js
css-class-list.js
css-select-adapter.d.ts
css-select-adapter.js
css-style-declaration.js
jsAPI.d.ts
jsAPI.js
plugins.js
tools.js
types.ts
xast.js
node_modules
commander
CHANGELOG.md
Readme.md
index.js
package-support.json
package.json
typings
index.d.ts
package.json
plugins
_applyTransforms.js
_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
mergeStyles.js
minifyStyles.js
moveElemsAttrsToGroup.js
moveGroupAttrsToElems.js
plugins.js
prefixIds.js
preset-default.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
tar-fs
.travis.yml
README.md
index.js
package.json
test
fixtures
a
hello.txt
b
a
test.txt
index.js
tar-stream
README.md
extract.js
headers.js
index.js
pack.js
package.json
sandbox.js
tcp-port-used
README.md
index.js
node_modules
debug
README.md
package.json
src
browser.js
common.js
index.js
node.js
ms
index.js
license.md
package.json
readme.md
package.json
test.js
temp-dir
index.d.ts
index.js
package.json
readme.md
term-size
index.d.ts
index.js
package.json
readme.md
terser
CHANGELOG.md
PATRONS.md
README.md
bin
package.json
dist
bundle.min.js
package.json
lib
ast.js
cli.js
compress
common.js
compressor-flags.js
drop-side-effect-free.js
evaluate.js
index.js
inference.js
inline.js
native-objects.js
reduce-vars.js
tighten-body.js
equivalent-to.js
minify.js
mozilla-ast.js
output.js
parse.js
propmangle.js
scope.js
size.js
sourcemap.js
transform.js
utils
first_in_statement.js
index.js
main.js
node_modules
commander
CHANGELOG.md
Readme.md
index.js
package.json
typings
index.d.ts
package.json
tools
domprops.js
props.html
terser.d.ts
text-encoding-utf-8
LICENSE.md
README.md
lib
encoding.js
encoding.lib.js
package.json
src
encoding.js
polyfill.js
time-zone
index.js
package.json
readme.md
timsort
LICENSE.md
README.md
build
timsort.js
timsort.min.js
index.js
package.json
src
timsort.js
to-fast-properties
index.js
package.json
readme.md
to-readable-stream
index.js
package.json
readme.md
to-regex-range
README.md
index.js
package.json
toidentifier
HISTORY.md
README.md
index.js
package.json
touch
README.md
bin
nodetouch.js
index.js
package.json
tr46
index.js
lib
mappingTable.json
package.json
ts-node
README.md
dist-raw
NODE-LICENSE.md
README.md
node-internal-constants.js
node-internal-errors.js
node-internal-modules-cjs-helpers.js
node-internal-modules-cjs-loader.js
node-internal-modules-esm-get_format.js
node-internal-modules-esm-resolve.js
node-internal-modules-package_json_reader.js
node-internal-repl-await.js
node-internalBinding-fs.js
node-nativemodule.js
node-options.js
node-primordials.js
dist
bin-cwd.d.ts
bin-cwd.js
bin-esm.d.ts
bin-esm.js
bin-script-deprecated.d.ts
bin-script-deprecated.js
bin-script.d.ts
bin-script.js
bin-transpile.d.ts
bin-transpile.js
bin.d.ts
bin.js
child
child-entrypoint.d.ts
child-entrypoint.js
child-loader.d.ts
child-loader.js
child-require.d.ts
child-require.js
spawn-child.d.ts
spawn-child.js
cjs-resolve-hooks.d.ts
cjs-resolve-hooks.js
configuration.d.ts
configuration.js
esm.d.ts
esm.js
file-extensions.d.ts
file-extensions.js
index.d.ts
index.js
module-type-classifier.d.ts
module-type-classifier.js
node-module-type-classifier.d.ts
node-module-type-classifier.js
repl.d.ts
repl.js
resolver-functions.d.ts
resolver-functions.js
transpilers
swc.d.ts
swc.js
types.d.ts
types.js
ts-compiler-types.d.ts
ts-compiler-types.js
ts-internals.d.ts
ts-internals.js
ts-transpile-module.d.ts
ts-transpile-module.js
tsconfig-schema.d.ts
tsconfig-schema.js
tsconfigs.d.ts
tsconfigs.js
util.d.ts
util.js
node10
tsconfig.json
node12
tsconfig.json
node14
tsconfig.json
node16
tsconfig.json
package.json
register
files.js
index.js
transpile-only.js
type-check.js
transpilers
swc-experimental.js
swc.js
tsconfig.schema.json
tsconfig.schemastore-schema.json
tslib
CopyrightNotice.txt
LICENSE.txt
README.md
modules
index.js
package.json
package.json
tslib.d.ts
tslib.es6.html
tslib.es6.js
tslib.html
tslib.js
tunnel-agent
README.md
index.js
package.json
tweetnacl
AUTHORS.md
CHANGELOG.md
PULL_REQUEST_TEMPLATE.md
README.md
nacl-fast.js
nacl-fast.min.js
nacl.d.ts
nacl.js
nacl.min.js
package.json
type-detect
README.md
index.js
package.json
type-detect.js
type-fest
index.d.ts
package.json
readme.md
source
async-return-type.d.ts
basic.d.ts
conditional-except.d.ts
conditional-keys.d.ts
conditional-pick.d.ts
except.d.ts
literal-union.d.ts
merge-exclusive.d.ts
merge.d.ts
mutable.d.ts
opaque.d.ts
package-json.d.ts
partial-deep.d.ts
promisable.d.ts
promise-value.d.ts
readonly-deep.d.ts
require-at-least-one.d.ts
require-exactly-one.d.ts
set-optional.d.ts
set-required.d.ts
stringified.d.ts
tsconfig-json.d.ts
union-to-intersection.d.ts
value-of.d.ts
typedarray-to-buffer
.airtap.yml
.travis.yml
README.md
index.js
package.json
test
basic.js
typescript
AUTHORS.md
CODE_OF_CONDUCT.md
CopyrightNotice.txt
LICENSE.txt
README.md
SECURITY.md
ThirdPartyNoticeText.txt
lib
README.md
cancellationToken.js
cs
diagnosticMessages.generated.json
de
diagnosticMessages.generated.json
es
diagnosticMessages.generated.json
fr
diagnosticMessages.generated.json
it
diagnosticMessages.generated.json
ja
diagnosticMessages.generated.json
ko
diagnosticMessages.generated.json
lib.d.ts
lib.dom.d.ts
lib.dom.iterable.d.ts
lib.es2015.collection.d.ts
lib.es2015.core.d.ts
lib.es2015.d.ts
lib.es2015.generator.d.ts
lib.es2015.iterable.d.ts
lib.es2015.promise.d.ts
lib.es2015.proxy.d.ts
lib.es2015.reflect.d.ts
lib.es2015.symbol.d.ts
lib.es2015.symbol.wellknown.d.ts
lib.es2016.array.include.d.ts
lib.es2016.d.ts
lib.es2016.full.d.ts
lib.es2017.d.ts
lib.es2017.full.d.ts
lib.es2017.intl.d.ts
lib.es2017.object.d.ts
lib.es2017.sharedmemory.d.ts
lib.es2017.string.d.ts
lib.es2017.typedarrays.d.ts
lib.es2018.asyncgenerator.d.ts
lib.es2018.asynciterable.d.ts
lib.es2018.d.ts
lib.es2018.full.d.ts
lib.es2018.intl.d.ts
lib.es2018.promise.d.ts
lib.es2018.regexp.d.ts
lib.es2019.array.d.ts
lib.es2019.d.ts
lib.es2019.full.d.ts
lib.es2019.object.d.ts
lib.es2019.string.d.ts
lib.es2019.symbol.d.ts
lib.es2020.bigint.d.ts
lib.es2020.d.ts
lib.es2020.date.d.ts
lib.es2020.full.d.ts
lib.es2020.intl.d.ts
lib.es2020.number.d.ts
lib.es2020.promise.d.ts
lib.es2020.sharedmemory.d.ts
lib.es2020.string.d.ts
lib.es2020.symbol.wellknown.d.ts
lib.es2021.d.ts
lib.es2021.full.d.ts
lib.es2021.intl.d.ts
lib.es2021.promise.d.ts
lib.es2021.string.d.ts
lib.es2021.weakref.d.ts
lib.es2022.array.d.ts
lib.es2022.d.ts
lib.es2022.error.d.ts
lib.es2022.full.d.ts
lib.es2022.intl.d.ts
lib.es2022.object.d.ts
lib.es2022.string.d.ts
lib.es5.d.ts
lib.es6.d.ts
lib.esnext.d.ts
lib.esnext.full.d.ts
lib.esnext.intl.d.ts
lib.esnext.promise.d.ts
lib.esnext.string.d.ts
lib.esnext.weakref.d.ts
lib.scripthost.d.ts
lib.webworker.d.ts
lib.webworker.importscripts.d.ts
lib.webworker.iterable.d.ts
pl
diagnosticMessages.generated.json
protocol.d.ts
pt-br
diagnosticMessages.generated.json
ru
diagnosticMessages.generated.json
tr
diagnosticMessages.generated.json
tsserverlibrary.d.ts
typesMap.json
typescript.d.ts
typescriptServices.d.ts
watchGuard.js
zh-cn
diagnosticMessages.generated.json
zh-tw
diagnosticMessages.generated.json
package.json
u2f-api
.travis.yml
README.md
index.d.ts
index.js
lib
google-u2f-api.js
u2f-api.js
package.json
scripts
test.sh
test.in
setup.js
tsconfig.json
u2f-api
index.ts
u3
README.md
index.js
lib
cache.js
eachCombination.js
index.js
package.json
undefsafe
.github
workflows
release.yml
.travis.yml
README.md
example.js
lib
undefsafe.js
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
unique-string
index.d.ts
index.js
package.json
readme.md
update-browserslist-db
README.md
cli.js
index.d.ts
index.js
package.json
update-notifier
check.js
index.js
node_modules
ansi-styles
index.d.ts
index.js
package.json
readme.md
chalk
index.d.ts
package.json
readme.md
source
index.js
templates.js
util.js
has-flag
index.d.ts
index.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
supports-color
browser.js
index.js
package.json
readme.md
package.json
readme.md
url-parse-lax
index.js
package.json
readme.md
usb
CHANGELOG.md
README.md
libusb
.private
README.txt
bd.cmd
bm.sh
bwince.cmd
post-rewrite.sh
pre-commit.sh
wbs.txt
wbs_wince.txt
.travis.yml
INSTALL_WIN.txt
README.md
Xcode
config.h
android
config.h
appveyor.yml
appveyor_cygwin.bat
appveyor_minGW.bat
autogen.sh
bootstrap.sh
examples
dpfp.c
dpfp_threaded.c
ezusb.c
ezusb.h
fxload.c
getopt
getopt.c
getopt.h
getopt1.c
hotplugtest.c
listdevs.c
sam3u_benchmark.c
testlibusb.c
xusb.c
libusb
core.c
descriptor.c
hotplug.c
hotplug.h
io.c
libusb.h
libusbi.h
os
darwin_usb.c
darwin_usb.h
haiku_pollfs.cpp
haiku_usb.h
haiku_usb_backend.cpp
haiku_usb_raw.cpp
haiku_usb_raw.h
linux_netlink.c
linux_udev.c
linux_usbfs.c
linux_usbfs.h
netbsd_usb.c
openbsd_usb.c
poll_posix.c
poll_posix.h
poll_windows.c
poll_windows.h
sunos_usb.c
sunos_usb.h
threads_posix.c
threads_posix.h
threads_windows.c
threads_windows.h
wince_usb.c
wince_usb.h
windows_common.h
windows_nt_common.c
windows_nt_common.h
windows_nt_shared_types.h
windows_usbdk.c
windows_usbdk.h
windows_winusb.c
windows_winusb.h
strerror.c
sync.c
version.h
version_nano.h
msvc
appveyor.bat
config.h
ddk_build.cmd
errno.h
inttypes.h
libusb_2005.sln
libusb_2010.sln
libusb_2012.sln
libusb_2013.sln
libusb_2015.sln
libusb_2017.sln
libusb_wince.sln
missing.c
missing.h
stdint.h
tests
libusb_testlib.h
stress.c
testlib.c
travis-autogen.sh
libusb_config
config.h
node_modules
node-addon-api
LICENSE.md
README.md
index.js
napi-inl.deprecated.h
napi-inl.h
napi.h
nothing.c
package-support.json
package.json
tools
README.md
check-napi.js
clang-format.js
conversion.js
eslint-format.js
package.json
src
helpers.h
node_usb.h
uv_async_queue.h
test
usb.coffee
usb.js
util-deprecate
History.md
README.md
browser.js
node.js
package.json
utility-types
CHANGELOG.md
README.md
SECURITY.md
SUPPORT.md
dist
aliases-and-guards.d.ts
aliases-and-guards.js
functional-helpers.d.ts
functional-helpers.js
index.d.ts
index.js
mapped-types.d.ts
mapped-types.js
utility-types.d.ts
utility-types.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-lib
CHANGELOG.md
README.md
package.json
v8-compile-cache.d.ts
v8-compile-cache.js
v8-compile-cache
CHANGELOG.md
README.md
package.json
v8-compile-cache.js
v8flags
README.md
config-path.js
index.js
package.json
weak-lru-cache
LRFUExpirer.js
README.md
index.d.ts
index.js
package.json
rollup.config.js
tests
benchmark.js
test.js
webidl-conversions
LICENSE.md
README.md
lib
index.js
package.json
well-known-symbols
README.md
index.js
package.json
whatwg-url
LICENSE.txt
README.md
lib
URL-impl.js
URL.js
public-api.js
url-state-machine.js
utils.js
package.json
which
CHANGELOG.md
README.md
package.json
which.js
wide-align
README.md
align.js
node_modules
emoji-regex
LICENSE-MIT.txt
README.md
es2015
index.js
text.js
index.d.ts
index.js
package.json
text.js
is-fullwidth-code-point
index.d.ts
index.js
package.json
readme.md
string-width
index.d.ts
index.js
package.json
readme.md
strip-ansi
index.d.ts
index.js
package.json
readme.md
package.json
widest-line
index.d.ts
index.js
node_modules
emoji-regex
LICENSE-MIT.txt
README.md
es2015
index.js
text.js
index.d.ts
index.js
package.json
text.js
is-fullwidth-code-point
index.d.ts
index.js
package.json
readme.md
string-width
index.d.ts
index.js
package.json
readme.md
strip-ansi
index.d.ts
index.js
package.json
readme.md
package.json
readme.md
wrap-ansi
index.js
node_modules
ansi-styles
index.d.ts
index.js
package.json
readme.md
emoji-regex
LICENSE-MIT.txt
README.md
es2015
index.js
text.js
index.d.ts
index.js
package.json
text.js
is-fullwidth-code-point
index.d.ts
index.js
package.json
readme.md
string-width
index.d.ts
index.js
package.json
readme.md
strip-ansi
index.d.ts
index.js
package.json
readme.md
package.json
readme.md
wrappy
README.md
package.json
wrappy.js
write-file-atomic
LICENSE.md
README.md
lib
index.js
package.json
xdg-basedir
index.d.ts
index.js
package.json
readme.md
xxhash-wasm
LICENSE.md
README.md
cjs
xxhash-wasm.js
esm
xxhash-wasm.js
package.json
types.d.ts
umd
xxhash-wasm.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
yaml
README.md
browser
dist
PlainValue-b8036b75.js
Schema-e94716c8.js
index.js
legacy-exports.js
package.json
parse-cst.js
resolveSeq-492ab440.js
types.js
util.js
warnings-df54cb69.js
index.js
map.js
pair.js
parse-cst.js
scalar.js
schema.js
seq.js
types.js
types
binary.js
omap.js
pairs.js
set.js
timestamp.js
util.js
dist
Document-9b4560a1.js
PlainValue-ec8e588e.js
Schema-88e323a7.js
index.js
legacy-exports.js
parse-cst.js
resolveSeq-d03cb037.js
test-events.js
types.js
util.js
warnings-1000a372.js
index.d.ts
index.js
map.js
package.json
pair.js
parse-cst.d.ts
parse-cst.js
scalar.js
schema.js
seq.js
types.d.ts
types.js
types
binary.js
omap.js
pairs.js
set.js
timestamp.js
util.d.ts
util.js
yargs-parser
CHANGELOG.md
LICENSE.txt
README.md
browser.js
build
lib
index.js
string-utils.js
tokenize-arg-string.js
yargs-parser-types.js
yargs-parser.js
package.json
yargs
README.md
build
lib
argsert.js
command.js
completion-templates.js
completion.js
middleware.js
parse-command.js
typings
common-types.js
yargs-parser-types.js
usage.js
utils
apply-extends.js
is-promise.js
levenshtein.js
maybe-async-result.js
obj-filter.js
process-argv.js
set-blocking.js
which-module.js
validation.js
yargs-factory.js
yerror.js
helpers
index.js
package.json
locales
be.json
de.json
en.json
es.json
fi.json
fr.json
hi.json
hu.json
id.json
it.json
ja.json
ko.json
nb.json
nl.json
nn.json
pirate.json
pl.json
pt.json
pt_BR.json
ru.json
th.json
tr.json
uk_UA.json
uz.json
zh_CN.json
zh_TW.json
node_modules
emoji-regex
LICENSE-MIT.txt
README.md
es2015
index.js
text.js
index.d.ts
index.js
package.json
text.js
is-fullwidth-code-point
index.d.ts
index.js
package.json
readme.md
string-width
index.d.ts
index.js
package.json
readme.md
strip-ansi
index.d.ts
index.js
package.json
readme.md
package.json
yn
index.d.ts
index.js
lenient.js
package.json
readme.md
yocto-queue
index.d.ts
index.js
package.json
readme.md
|
Inspector mode only
-----------
|
|
Dependency
Version
Streaming Decompression operations
Dependency
Resource Management
Compression
Error List
Useful constants
nested-env-vars
Welcome to debugging React
(C)
TypeScript ThirdPartyNotices
DefinitelyTyped
Unicode
WebGL
End of ThirdPartyNotices
package-lock.json
package.json
| # Source Map
[](https://travis-ci.org/mozilla/source-map)
[](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] }
```
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).
# `react-test-renderer`
This package provides an experimental React renderer that can be used to render React components to pure JavaScript objects, without depending on the DOM or a native mobile environment.
Essentially, this package makes it easy to grab a snapshot of the "DOM tree" rendered by a React DOM or React Native component without using a browser or jsdom.
Documentation:
[https://reactjs.org/docs/test-renderer.html](https://reactjs.org/docs/test-renderer.html)
Usage:
```jsx
const ReactTestRenderer = require('react-test-renderer');
const renderer = ReactTestRenderer.create(
<Link page="https://www.facebook.com/">Facebook</Link>
);
console.log(renderer.toJSON());
// { type: 'a',
// props: { href: 'https://www.facebook.com/' },
// children: [ 'Facebook' ] }
```
You can also use Jest's snapshot testing feature to automatically save a copy of the JSON tree to a file and check in your tests that it hasn't changed: https://jestjs.io/blog/2016/07/27/jest-14.html.
# js-sha256
[](https://travis-ci.org/emn178/js-sha256)
[](https://coveralls.io/r/emn178/js-sha256?branch=master)
[](https://cdnjs.com/libraries/js-sha256/)
[](https://nodei.co/npm/js-sha256/)
A simple SHA-256 / SHA-224 hash function for JavaScript supports UTF-8 encoding.
## Demo
[SHA256 Online](http://emn178.github.io/online-tools/sha256.html)
[SHA224 Online](http://emn178.github.io/online-tools/sha224.html)
## Download
[Compress](https://raw.github.com/emn178/js-sha256/master/build/sha256.min.js)
[Uncompress](https://raw.github.com/emn178/js-sha256/master/src/sha256.js)
## Installation
You can also install js-sha256 by using Bower.
bower install js-sha256
For node.js, you can use this command to install:
npm install js-sha256
## Usage
You could use like this:
```JavaScript
sha256('Message to hash');
sha224('Message to hash');
var hash = sha256.create();
hash.update('Message to hash');
hash.hex();
var hash2 = sha256.update('Message to hash');
hash2.update('Message2 to hash');
hash2.array();
// HMAC
sha256.hmac('key', 'Message to hash');
sha224.hmac('key', 'Message to hash');
var hash = sha256.hmac.create('key');
hash.update('Message to hash');
hash.hex();
var hash2 = sha256.hmac.update('key', 'Message to hash');
hash2.update('Message2 to hash');
hash2.array();
```
If you use node.js, you should require the module first:
```JavaScript
var sha256 = require('js-sha256');
```
or
```JavaScript
var sha256 = require('js-sha256').sha256;
var sha224 = require('js-sha256').sha224;
```
It supports AMD:
```JavaScript
require(['your/path/sha256.js'], function(sha256) {
// ...
});
```
or TypeScript
```TypeScript
import { sha256, sha224 } from 'js-sha256';
```
## Example
```JavaScript
sha256(''); // e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
sha256('The quick brown fox jumps over the lazy dog'); // d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592
sha256('The quick brown fox jumps over the lazy dog.'); // ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c
sha224(''); // d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f
sha224('The quick brown fox jumps over the lazy dog'); // 730e109bd7a8a32b1cb9d9a09aa2325d2430587ddbc0c38bad911525
sha224('The quick brown fox jumps over the lazy dog.'); // 619cba8e8e05826e9b8c519c0a5c68f4fb653e8a3d8aa04bb2c8cd4c
// It also supports UTF-8 encoding
sha256('ไธญๆ'); // 72726d8818f693066ceb69afa364218b692e62ea92b385782363780f47529c21
sha224('ไธญๆ'); // dfbab71afdf54388af4d55f8bd3de8c9b15e0eb916bf9125f4a959d4
// It also supports byte `Array`, `Uint8Array`, `ArrayBuffer` input
sha256([]); // e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
sha256(new Uint8Array([211, 212])); // 182889f925ae4e5cc37118ded6ed87f7bdc7cab5ec5e78faef2e50048999473f
// Different output
sha256(''); // e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
sha256.hex(''); // e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
sha256.array(''); // [227, 176, 196, 66, 152, 252, 28, 20, 154, 251, 244, 200, 153, 111, 185, 36, 39, 174, 65, 228, 100, 155, 147, 76, 164, 149, 153, 27, 120, 82, 184, 85]
sha256.digest(''); // [227, 176, 196, 66, 152, 252, 28, 20, 154, 251, 244, 200, 153, 111, 185, 36, 39, 174, 65, 228, 100, 155, 147, 76, 164, 149, 153, 27, 120, 82, 184, 85]
sha256.arrayBuffer(''); // ArrayBuffer
```
## License
The project is released under the [MIT license](http://www.opensource.org/licenses/MIT).
## Contact
The project's website is located at https://github.com/emn178/js-sha256
Author: Chen, Yi-Cyuan ([email protected])
# bl *(BufferList)*
[](https://travis-ci.com/rvagg/bl/)
**A Node.js Buffer list collector, reader and streamer thingy.**
[](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—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 & copyright
Copyright (c) 2013-2019 bl contributors (listed above).
bl is licensed under the MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE.md file for more details.
# u3 - Utility Functions
This lib contains utility functions for e3, dataflower and other projects.
## Documentation
### Installation
```bash
npm install u3
```
```bash
bower install u3
```
#### Usage
In this documentation I used the lib as follows:
```js
var u3 = require("u3"),
cache = u3.cache,
eachCombination = u3.eachCombination;
```
### Function wrappers
#### cache
The `cache(fn)` function caches the fn results, so by the next calls it will return the result of the first call.
You can use different arguments, but they won't affect the return value.
```js
var a = cache(function fn(x, y, z){
return x + y + z;
});
console.log(a(1, 2, 3)); // 6
console.log(a()); // 6
console.log(a()); // 6
```
It is possible to cache a value too.
```js
var a = cache(1 + 2 + 3);
console.log(a()); // 6
console.log(a()); // 6
console.log(a()); // 6
```
### Math
#### eachCombination
The `eachCombination(alternativesByDimension, callback)` calls the `callback(a,b,c,...)` on each combination of the `alternatives[a[],b[],c[],...]`.
```js
eachCombination([
[1, 2, 3],
["a", "b"]
], console.log);
/*
1, "a"
1, "b"
2, "a"
2, "b"
3, "a"
3, "b"
*/
```
You can use any dimension and number of alternatives. In the current example we used 2 dimensions. By the first dimension we used 3 alternatives: `[1, 2, 3]` and by the second dimension we used 2 alternatives: `["a", "b"]`.
## License
MIT - 2016 Jรกnszky Lรกszlรณ Lajos
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.
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.
# 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
```
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).
# cbor
Encode and parse data in the Concise Binary Object Representation (CBOR) data format ([RFC8949](https://www.rfc-editor.org/rfc/rfc8949.html)).
## Supported Node.js versions
This project now only supports versions of Node that the Node team is
[currently supporting](https://github.com/nodejs/Release#release-schedule).
Ava's [support
statement](https://github.com/avajs/ava/blob/main/docs/support-statement.md)
is what we will be using as well. Currently, that means Node `10`+ is
required. If you need to support an older version of Node (back to version
6), use cbor version 5.2.x, which will get nothing but security updates from
here on out.
## Installation:
```bash
$ npm install --save cbor
```
**NOTE**
If you are going to use this on the web, use [cbor-web](../cbor-web) instead.
If you need support for encoding and decoding BigDecimal fractions (tag 4) or
BigFloats (tag 5), please see [cbor-bigdecimal](../cbor-bigdecimal).
## Documentation:
See the full API [documentation](http://hildjj.github.io/node-cbor/).
For a command-line interface, see [cbor-cli](../cbor-cli).
Example:
```js
const cbor = require('cbor')
const assert = require('assert')
let encoded = cbor.encode(true) // Returns <Buffer f5>
cbor.decodeFirst(encoded, (error, obj) => {
// If there was an error, error != null
// obj is the unpacked object
assert.ok(obj === true)
})
// Use integers as keys?
const m = new Map()
m.set(1, 2)
encoded = cbor.encode(m) // <Buffer a1 01 02>
```
Allows streaming as well:
```js
const cbor = require('cbor')
const fs = require('fs')
const d = new cbor.Decoder()
d.on('data', obj => {
console.log(obj)
})
const s = fs.createReadStream('foo')
s.pipe(d)
const d2 = new cbor.Decoder({input: '00', encoding: 'hex'})
d.on('data', obj => {
console.log(obj)
})
```
There is also support for synchronous decodes:
```js
try {
console.log(cbor.decodeFirstSync('02')) // 2
console.log(cbor.decodeAllSync('0202')) // [2, 2]
} catch (e) {
// Throws on invalid input
}
```
The sync encoding and decoding are exported as a
[leveldb encoding](https://github.com/Level/levelup#custom_encodings), as
`cbor.leveldb`.
## highWaterMark
The synchronous routines for encoding and decoding will have problems with
objects that are larger than 16kB, which the default buffer size for Node
streams. There are a few ways to fix this:
1) pass in a `highWaterMark` option with the value of the largest buffer size you think you will need:
```js
cbor.encodeOne(new ArrayBuffer(40000), {highWaterMark: 65535})
```
2) use stream mode. Catch the `data`, `finish`, and `error` events. Make sure to call `end()` when you're done.
```js
const enc = new cbor.Encoder()
enc.on('data', buf => /* Send the data somewhere */ null)
enc.on('error', console.error)
enc.on('finish', () => /* Tell the consumer we are finished */ null)
enc.end(['foo', 1, false])
```
3) use `encodeAsync()`, which uses the approach from approach 2 to return a memory-inefficient promise for a Buffer.
## Supported types
The following types are supported for encoding:
* boolean
* number (including -0, NaN, and ยฑInfinity)
* string
* Array, Set (encoded as Array)
* Object (including null), Map
* undefined
* Buffer
* Date,
* RegExp
* URL
* TypedArrays, ArrayBuffer, DataView
* Map, Set
* BigInt
Decoding supports the above types, including the following CBOR tag numbers:
| Tag | Generated Type |
|-----|---------------------|
| 0 | Date |
| 1 | Date |
| 2 | BigInt |
| 3 | BigInt |
| 21 | Tagged, with toJSON |
| 22 | Tagged, with toJSON |
| 23 | Tagged, with toJSON |
| 32 | URL |
| 33 | Tagged |
| 34 | Tagged |
| 35 | RegExp |
| 64 | Uint8Array |
| 65 | Uint16Array |
| 66 | Uint32Array |
| 67 | BigUint64Array |
| 68 | Uint8ClampedArray |
| 69 | Uint16Array |
| 70 | Uint32Array |
| 71 | BigUint64Array |
| 72 | Int8Array |
| 73 | Int16Array |
| 74 | Int32Array |
| 75 | BigInt64Array |
| 77 | Int16Array |
| 78 | Int32Array |
| 79 | BigInt64Array |
| 81 | Float32Array |
| 82 | Float64Array |
| 85 | Float32Array |
| 86 | Float64Array |
| 258 | Set |
## Adding new Encoders
There are several ways to add a new encoder:
### `encodeCBOR` method
This is the easiest approach, if you can modify the class being encoded. Add an
`encodeCBOR` method to your class, which takes a single parameter of the encoder
currently being used. Your method should return `true` on success, else `false`.
Your method may call `encoder.push(buffer)` or `encoder.pushAny(any)` as needed.
For example:
```js
class Foo {
constructor() {
this.one = 1
this.two = 2
}
encodeCBOR(encoder) {
const tagged = new Tagged(64000, [this.one, this.two])
return encoder.pushAny(tagged)
}
}
```
You can also modify an existing type by monkey-patching an `encodeCBOR` function
onto its prototype, but this isn't recommended.
### `addSemanticType`
Sometimes, you want to support an existing type without modification to that
type. In this case, call `addSemanticType(type, encodeFunction)` on an existing
`Encoder` instance. The `encodeFunction` takes an encoder and an object to
encode, for example:
```js
class Bar {
constructor() {
this.three = 3
}
}
const enc = new Encoder()
enc.addSemanticType(Bar, (encoder, b) => {
encoder.pushAny(b.three)
})
```
## Adding new decoders
Most of the time, you will want to add support for decoding a new tag type. If
the Decoder class encounters a tag it doesn't support, it will generate a `Tagged`
instance that you can handle or ignore as needed. To have a specific type
generated instead, pass a `tags` option to the `Decoder`'s constructor, consisting
of an object with tag number keys and function values. The function will be
passed the decoded value associated with the tag, and should return the decoded
value. For the `Foo` example above, this might look like:
```js
const d = new Decoder({
tags: {
64000: val => {
// Check val to make sure it's an Array as expected, etc.
const foo = new Foo()
;[foo.one, foo.two] = val
return foo
},
},
})
```
You can also replace the default decoders by passing in an appropriate tag
function. For example:
```js
cbor.decodeFirstSync(input, {
tags: {
// Replace the Tag 0 (RFC3339 Date/Time string) decoder.
// See https://tc39.es/proposal-temporal/docs/ for the upcoming
// Temporal built-in, which supports nanosecond time:
0: x => Temporal.Instant.from(x),
},
})
```
Developers
----------
The tests for this package use a set of test vectors from RFC 8949 appendix A
by importing a machine readable version of them from
https://github.com/cbor/test-vectors. For these tests to work, you will need
to use the command `git submodule update --init` after cloning or pulling this
code. See https://gist.github.com/gitaarik/8735255#file-git_submodules-md
for more information.
Get a list of build steps with `npm run`. I use `npm run dev`, which rebuilds,
runs tests, and refreshes a browser window with coverage metrics every time I
save a `.js` file. If you don't want to run the fuzz tests every time, set
a `NO_GARBAGE` environment variable:
```
env NO_GARBAGE=1 npm run dev
```
[](https://github.com/hildjj/node-cbor/actions?query=workflow%3ATests)
[](https://coveralls.io/r/hildjj/node-cbor?branch=main)
LZ4 Windows binary package
====================================
#### The package contents
- `lz4.exe` : Command Line Utility, supporting gzip-like arguments
- `dll\liblz4.dll` : The DLL of LZ4 library
- `dll\liblz4.lib` : The import library of LZ4 library for Visual C++
- `example\` : The example of usage of LZ4 library
- `include\` : Header files required with LZ4 library
- `static\liblz4_static.lib` : The static LZ4 library
#### Usage of Command Line Interface
Command Line Interface (CLI) supports gzip-like arguments.
By default CLI takes an input file and compresses it to an output file:
```
Usage: lz4 [arg] [input] [output]
```
The full list of commands for CLI can be obtained with `-h` or `-H`. The ratio can
be improved with commands from `-3` to `-16` but higher levels also have slower
compression. CLI includes in-memory compression benchmark module with compression
levels starting from `-b` and ending with `-e` with iteration time of `-i` seconds.
CLI supports aggregation of parameters i.e. `-b1`, `-e18`, and `-i1` can be joined
into `-b1e18i1`.
#### The example of usage of static and dynamic LZ4 libraries with gcc/MinGW
Use `cd example` and `make` to build `fullbench-dll` and `fullbench-lib`.
`fullbench-dll` uses a dynamic LZ4 library from the `dll` directory.
`fullbench-lib` uses a static LZ4 library from the `lib` directory.
#### Using LZ4 DLL with gcc/MinGW
The header files from `include\` and the dynamic library `dll\liblz4.dll`
are required to compile a project using gcc/MinGW.
The dynamic library has to be added to linking options.
It means that if a project that uses LZ4 consists of a single `test-dll.c`
file it should be linked with `dll\liblz4.dll`. For example:
```
gcc $(CFLAGS) -Iinclude\ test-dll.c -o test-dll dll\liblz4.dll
```
The compiled executable will require LZ4 DLL which is available at `dll\liblz4.dll`.
#### The example of usage of static and dynamic LZ4 libraries with Visual C++
Open `example\fullbench-dll.sln` to compile `fullbench-dll` that uses a
dynamic LZ4 library from the `dll` directory. The solution works with Visual C++
2010 or newer. When one will open the solution with Visual C++ newer than 2010
then the solution will upgraded to the current version.
#### Using LZ4 DLL with Visual C++
The header files from `include\` and the import library `dll\liblz4.lib`
are required to compile a project using Visual C++.
1. The header files should be added to `Additional Include Directories` that can
be found in project properties `C/C++` then `General`.
2. The import library has to be added to `Additional Dependencies` that can
be found in project properties `Linker` then `Input`.
If one will provide only the name `liblz4.lib` without a full path to the library
the directory has to be added to `Linker\General\Additional Library Directories`.
The compiled executable will require LZ4 DLL which is available at `dll\liblz4.dll`.
# get-intrinsic <sup>[![Version Badge][npm-version-svg]][package-url]</sup>
[![github actions][actions-image]][actions-url]
[![coverage][codecov-image]][codecov-url]
[![dependency status][deps-svg]][deps-url]
[![dev dependency status][dev-deps-svg]][dev-deps-url]
[![License][license-image]][license-url]
[![Downloads][downloads-image]][downloads-url]
[![npm badge][npm-badge-png]][package-url]
Get and robustly cache all JS language-level intrinsics at first require time.
See the syntax described [in the JS spec](https://tc39.es/ecma262/#sec-well-known-intrinsic-objects) for reference.
## Example
```js
var GetIntrinsic = require('get-intrinsic');
var assert = require('assert');
// static methods
assert.equal(GetIntrinsic('%Math.pow%'), Math.pow);
assert.equal(Math.pow(2, 3), 8);
assert.equal(GetIntrinsic('%Math.pow%')(2, 3), 8);
delete Math.pow;
assert.equal(GetIntrinsic('%Math.pow%')(2, 3), 8);
// instance methods
var arr = [1];
assert.equal(GetIntrinsic('%Array.prototype.push%'), Array.prototype.push);
assert.deepEqual(arr, [1]);
arr.push(2);
assert.deepEqual(arr, [1, 2]);
GetIntrinsic('%Array.prototype.push%').call(arr, 3);
assert.deepEqual(arr, [1, 2, 3]);
delete Array.prototype.push;
GetIntrinsic('%Array.prototype.push%').call(arr, 4);
assert.deepEqual(arr, [1, 2, 3, 4]);
// missing features
delete JSON.parse; // to simulate a real intrinsic that is missing in the environment
assert.throws(() => GetIntrinsic('%JSON.parse%'));
assert.equal(undefined, GetIntrinsic('%JSON.parse%', true));
```
## 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/get-intrinsic
[npm-version-svg]: https://versionbadg.es/ljharb/get-intrinsic.svg
[deps-svg]: https://david-dm.org/ljharb/get-intrinsic.svg
[deps-url]: https://david-dm.org/ljharb/get-intrinsic
[dev-deps-svg]: https://david-dm.org/ljharb/get-intrinsic/dev-status.svg
[dev-deps-url]: https://david-dm.org/ljharb/get-intrinsic#info=devDependencies
[npm-badge-png]: https://nodei.co/npm/get-intrinsic.png?downloads=true&stars=true
[license-image]: https://img.shields.io/npm/l/get-intrinsic.svg
[license-url]: LICENSE
[downloads-image]: https://img.shields.io/npm/dm/get-intrinsic.svg
[downloads-url]: https://npm-stat.com/charts.html?package=get-intrinsic
[codecov-image]: https://codecov.io/gh/ljharb/get-intrinsic/branch/main/graphs/badge.svg
[codecov-url]: https://app.codecov.io/gh/ljharb/get-intrinsic/
[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/get-intrinsic
[actions-url]: https://github.com/ljharb/get-intrinsic/actions
# 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
# East Asian Width
Get [East Asian Width](http://www.unicode.org/reports/tr11/) from a character.
'F'(Fullwidth), 'H'(Halfwidth), 'W'(Wide), 'Na'(Narrow), 'A'(Ambiguous) or 'N'(Natural).
Original Code is [ๆฑใขใธใขใฎๆๅญๅน
(East Asian Width) ใฎๅคๅฎ - ไธญ้](http://d.hatena.ne.jp/takenspc/20111126#1322252878).
## Install
$ npm install eastasianwidth
## Usage
var eaw = require('eastasianwidth');
console.log(eaw.eastAsianWidth('๏ฟฆ')) // 'F'
console.log(eaw.eastAsianWidth('๏ฝก')) // 'H'
console.log(eaw.eastAsianWidth('๋')) // 'W'
console.log(eaw.eastAsianWidth('a')) // 'Na'
console.log(eaw.eastAsianWidth('โ ')) // 'A'
console.log(eaw.eastAsianWidth('ู')) // 'N'
console.log(eaw.characterLength('๏ฟฆ')) // 2
console.log(eaw.characterLength('๏ฝก')) // 1
console.log(eaw.characterLength('๋')) // 2
console.log(eaw.characterLength('a')) // 1
console.log(eaw.characterLength('โ ')) // 2
console.log(eaw.characterLength('ู')) // 1
console.log(eaw.length('ใใใใใ')) // 10
console.log(eaw.length('abcdefg')) // 7
console.log(eaw.length('๏ฟ ๏ฟฆ๏ฝก๏ฟใ
๋ยขโญaโโ ุจู')) // 19
# 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).
[](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.
# 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
# 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],
}
*/
```
# fill-range [](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [](https://www.npmjs.com/package/fill-range) [](https://npmjs.org/package/fill-range) [](https://npmjs.org/package/fill-range) [](https://travis-ci.org/jonschlinkert/fill-range)
> Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`
Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support.
## Install
Install with [npm](https://www.npmjs.com/):
```sh
$ npm install --save fill-range
```
## Usage
Expands numbers and letters, optionally using a `step` as the last argument. _(Numbers may be defined as JavaScript numbers or strings)_.
```js
const fill = require('fill-range');
// fill(from, to[, step, options]);
console.log(fill('1', '10')); //=> ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
console.log(fill('1', '10', { toRegex: true })); //=> [1-9]|10
```
**Params**
* `from`: **{String|Number}** the number or letter to start with
* `to`: **{String|Number}** the number or letter to end with
* `step`: **{String|Number|Object|Function}** Optionally pass a [step](#optionsstep) to use.
* `options`: **{Object|Function}**: See all available [options](#options)
## Examples
By default, an array of values is returned.
**Alphabetical ranges**
```js
console.log(fill('a', 'e')); //=> ['a', 'b', 'c', 'd', 'e']
console.log(fill('A', 'E')); //=> [ 'A', 'B', 'C', 'D', 'E' ]
```
**Numerical ranges**
Numbers can be defined as actual numbers or strings.
```js
console.log(fill(1, 5)); //=> [ 1, 2, 3, 4, 5 ]
console.log(fill('1', '5')); //=> [ 1, 2, 3, 4, 5 ]
```
**Negative ranges**
Numbers can be defined as actual numbers or strings.
```js
console.log(fill('-5', '-1')); //=> [ '-5', '-4', '-3', '-2', '-1' ]
console.log(fill('-5', '5')); //=> [ '-5', '-4', '-3', '-2', '-1', '0', '1', '2', '3', '4', '5' ]
```
**Steps (increments)**
```js
// numerical ranges with increments
console.log(fill('0', '25', 4)); //=> [ '0', '4', '8', '12', '16', '20', '24' ]
console.log(fill('0', '25', 5)); //=> [ '0', '5', '10', '15', '20', '25' ]
console.log(fill('0', '25', 6)); //=> [ '0', '6', '12', '18', '24' ]
// alphabetical ranges with increments
console.log(fill('a', 'z', 4)); //=> [ 'a', 'e', 'i', 'm', 'q', 'u', 'y' ]
console.log(fill('a', 'z', 5)); //=> [ 'a', 'f', 'k', 'p', 'u', 'z' ]
console.log(fill('a', 'z', 6)); //=> [ 'a', 'g', 'm', 's', 'y' ]
```
## Options
### options.step
**Type**: `number` (formatted as a string or number)
**Default**: `undefined`
**Description**: The increment to use for the range. Can be used with letters or numbers.
**Example(s)**
```js
// numbers
console.log(fill('1', '10', 2)); //=> [ '1', '3', '5', '7', '9' ]
console.log(fill('1', '10', 3)); //=> [ '1', '4', '7', '10' ]
console.log(fill('1', '10', 4)); //=> [ '1', '5', '9' ]
// letters
console.log(fill('a', 'z', 5)); //=> [ 'a', 'f', 'k', 'p', 'u', 'z' ]
console.log(fill('a', 'z', 7)); //=> [ 'a', 'h', 'o', 'v' ]
console.log(fill('a', 'z', 9)); //=> [ 'a', 'j', 's' ]
```
### options.strictRanges
**Type**: `boolean`
**Default**: `false`
**Description**: By default, `null` is returned when an invalid range is passed. Enable this option to throw a `RangeError` on invalid ranges.
**Example(s)**
The following are all invalid:
```js
fill('1.1', '2'); // decimals not supported in ranges
fill('a', '2'); // incompatible range values
fill(1, 10, 'foo'); // invalid "step" argument
```
### options.stringify
**Type**: `boolean`
**Default**: `undefined`
**Description**: Cast all returned values to strings. By default, integers are returned as numbers.
**Example(s)**
```js
console.log(fill(1, 5)); //=> [ 1, 2, 3, 4, 5 ]
console.log(fill(1, 5, { stringify: true })); //=> [ '1', '2', '3', '4', '5' ]
```
### options.toRegex
**Type**: `boolean`
**Default**: `undefined`
**Description**: Create a regex-compatible source string, instead of expanding values to an array.
**Example(s)**
```js
// alphabetical range
console.log(fill('a', 'e', { toRegex: true })); //=> '[a-e]'
// alphabetical with step
console.log(fill('a', 'z', 3, { toRegex: true })); //=> 'a|d|g|j|m|p|s|v|y'
// numerical range
console.log(fill('1', '100', { toRegex: true })); //=> '[1-9]|[1-9][0-9]|100'
// numerical range with zero padding
console.log(fill('000001', '100000', { toRegex: true }));
//=> '0{5}[1-9]|0{4}[1-9][0-9]|0{3}[1-9][0-9]{2}|0{2}[1-9][0-9]{3}|0[1-9][0-9]{4}|100000'
```
### options.transform
**Type**: `function`
**Default**: `undefined`
**Description**: Customize each value in the returned array (or [string](#optionstoRegex)). _(you can also pass this function as the last argument to `fill()`)_.
**Example(s)**
```js
// add zero padding
console.log(fill(1, 5, value => String(value).padStart(4, '0')));
//=> ['0001', '0002', '0003', '0004', '0005']
```
## About
<details>
<summary><strong>Contributing</strong></summary>
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
</details>
<details>
<summary><strong>Running Tests</strong></summary>
Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:
```sh
$ npm install && npm test
```
</details>
<details>
<summary><strong>Building docs</strong></summary>
_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
To generate the readme, run the following command:
```sh
$ npm install -g verbose/verb#dev verb-generate-readme && verb
```
</details>
### Contributors
| **Commits** | **Contributor** |
| --- | --- |
| 116 | [jonschlinkert](https://github.com/jonschlinkert) |
| 4 | [paulmillr](https://github.com/paulmillr) |
| 2 | [realityking](https://github.com/realityking) |
| 2 | [bluelovers](https://github.com/bluelovers) |
| 1 | [edorivai](https://github.com/edorivai) |
| 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) |
### Author
**Jon Schlinkert**
* [GitHub Profile](https://github.com/jonschlinkert)
* [Twitter Profile](https://twitter.com/jonschlinkert)
* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert)
Please consider supporting me on Patreon, or [start your own Patreon page](https://patreon.com/invite/bxpbvm)!
<a href="https://www.patreon.com/jonschlinkert">
<img src="https://c5.patreon.com/external/logo/[email protected]" height="50">
</a>
### License
Copyright ยฉ 2019, [Jon Schlinkert](https://github.com/jonschlinkert).
Released under the [MIT License](LICENSE).
***
_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on April 08, 2019._
# is-glob [](https://www.npmjs.com/package/is-glob) [](https://npmjs.org/package/is-glob) [](https://npmjs.org/package/is-glob) [](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._
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.
# 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"),
]);
});
```
# css-select [](https://npmjs.org/package/css-select) [](http://travis-ci.com/fb55/css-select) [](https://npmjs.org/package/css-select) [](https://coveralls.io/r/fb55/css-select)
A CSS selector compiler and engine
## What?
As a **compiler**, css-select turns CSS selectors into functions that tests if
elements match them.
As an **engine**, css-select looks through a DOM tree, searching for elements.
Elements are tested "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). To query alternative DOM structures, see [`Options`](#options)
below.
**Features:**
- ๐ฌ Full implementation of CSS3 selectors, as well as most CSS4 selectors
- ๐งช Partial implementation of jQuery/Sizzle extensions (see
[cheerio-select](https://github.com/cheeriojs/cheerio-select) for the
remaining selectors)
- ๐งโ๐ฌ High test coverage, including the full test suites from Sizzle, Qwery and
NWMatcher.
- ๐ฅผ Reliably great performance
## Why?
Most CSS engines written in JavaScript execute selectors left-to-right. That
means thet execute every component of the selector in order, from left to right
_(duh)_. As an example: For the selector `a b`, these engines 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`, for right-to-left
execution. We start by _parsing_ the selector. This turns the selector into an
array of the building blocks. 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 is where things become 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 function representing the next part of the selector. That function 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. That means elements are passed from the rightmost part of the
selector (`b` in our example) to the leftmost (~~which would be `c`~~ of course
`a`).
For traversals, such as the _descendant_ operating the space between `a` and
`b`, we walk up the DOM tree, starting from the element passed as argument.
_//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.This
is done to aid with writing css selectors, but can be unexpected when processing
arbitrary strings.
#### `CSSselect.selectAll(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: `default` export, `CSSselect.iterate(query, elems)`.
#### `CSSselect.compile(query, options)`
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.selectAll(query, elems)`. Only returns
the first match, or `null` if there was no match.
### Options
All options are optional.
- `xmlMode`: When enabled, tag names will be case-sensitive. Default: `false`.
- `rootFunc`: The last function in the stack, will be called with the last
element that's looked at.
- `adapter`: The adapter to use when interacting with the backing DOM
structure. By default it uses the `domutils` module.
- `context`: The context of the current query. Used to limit the scope of
searches. Can be matched directly using the `:scope` pseudo-selector.
- `cacheResults`: Allow css-select to cache results for some selectors,
sometimes greatly improving querying performance. Disable this if your
document can change in between queries with the same compiled selector.
Default: `true`.
#### Custom Adapters
A custom adapter must match the interface described
[here](https://github.com/fb55/css-select/blob/1aa44bdd64aaf2ebdfd7f338e2e76bed36521957/src/types.ts#L6-L96).
You may want to have a 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.
## Supported selectors
_As defined by CSS 4 and / or jQuery._
- [Selector lists](https://developer.mozilla.org/en-US/docs/Web/CSS/Selector_list)
(`,`)
- [Universal](https://developer.mozilla.org/en-US/docs/Web/CSS/Universal_selectors)
(`*`)
- [Type](https://developer.mozilla.org/en-US/docs/Web/CSS/Type_selectors)
(`<tagname>`)
- [Descendant](https://developer.mozilla.org/en-US/docs/Web/CSS/Descendant_combinator)
(` `)
- [Child](https://developer.mozilla.org/en-US/docs/Web/CSS/Child_combinator)
(`>`)
- Parent (`<`)
- [Adjacent sibling](https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_combinator)
(`+`)
- [General sibling](https://developer.mozilla.org/en-US/docs/Web/CSS/General_sibling_combinator)
(`~`)
- [Attribute](https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors)
(`[attr=foo]`), with supported comparisons:
- `[attr]` (existential)
- `=`
- `~=`
- `|=`
- `*=`
- `^=`
- `$=`
- `!=`
- `i` and `s` can be added after the comparison to make the comparison
case-insensitive or case-sensitive (eg. `[attr=foo i]`). If neither is
supplied, css-select will follow the HTML spec's
[case-sensitivity rules](https://html.spec.whatwg.org/multipage/semantics-other.html#case-sensitivity-of-selectors).
- Pseudos:
- [`:not`](https://developer.mozilla.org/en-US/docs/Web/CSS/:not)
- [`:contains`](https://api.jquery.com/contains-selector)
- `:icontains` (case-insensitive version of `:contains`)
- [`:has`](https://developer.mozilla.org/en-US/docs/Web/CSS/:has)
- [`:root`](https://developer.mozilla.org/en-US/docs/Web/CSS/:root)
- [`:empty`](https://developer.mozilla.org/en-US/docs/Web/CSS/:empty)
- [`:parent`](https://api.jquery.com/parent-selector)
- [`:first-child`](https://developer.mozilla.org/en-US/docs/Web/CSS/:first-child),
[`:last-child`](https://developer.mozilla.org/en-US/docs/Web/CSS/:last-child),
[`:first-of-type`](https://developer.mozilla.org/en-US/docs/Web/CSS/:first-of-type),
[`:last-of-type`](https://developer.mozilla.org/en-US/docs/Web/CSS/:last-of-type)
- [`:only-of-type`](https://developer.mozilla.org/en-US/docs/Web/CSS/:only-of-type),
[`:only-child`](https://developer.mozilla.org/en-US/docs/Web/CSS/:only-child)
- [`:nth-child`](https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child),
[`:nth-last-child`](https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-child),
[`:nth-of-type`](https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-of-type),
[`:nth-last-of-type`](https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-of-type),
- [`:link`](https://developer.mozilla.org/en-US/docs/Web/CSS/:link),
[`:any-link`](https://developer.mozilla.org/en-US/docs/Web/CSS/:any-link)
- [`:visited`](https://developer.mozilla.org/en-US/docs/Web/CSS/:visited),
[`:hover`](https://developer.mozilla.org/en-US/docs/Web/CSS/:hover),
[`:active`](https://developer.mozilla.org/en-US/docs/Web/CSS/:active)
(these depend on optional `Adapter` methods, so these will only match
elements if implemented in `Adapter`)
- [`:selected`](https://api.jquery.com/selected-selector),
[`:checked`](https://developer.mozilla.org/en-US/docs/Web/CSS/:checked)
- [`:enabled`](https://developer.mozilla.org/en-US/docs/Web/CSS/:enabled),
[`:disabled`](https://developer.mozilla.org/en-US/docs/Web/CSS/:disabled)
- [`:required`](https://developer.mozilla.org/en-US/docs/Web/CSS/:required),
[`:optional`](https://developer.mozilla.org/en-US/docs/Web/CSS/:optional)
- [`:header`](https://api.jquery.com/header-selector),
[`:button`](https://api.jquery.com/button-selector),
[`:input`](https://api.jquery.com/input-selector),
[`:text`](https://api.jquery.com/text-selector),
[`:checkbox`](https://api.jquery.com/checkbox-selector),
[`:file`](https://api.jquery.com/file-selector),
[`:password`](https://api.jquery.com/password-selector),
[`:reset`](https://api.jquery.com/reset-selector),
[`:radio`](https://api.jquery.com/radio-selector) etc.
- [`:is`](https://developer.mozilla.org/en-US/docs/Web/CSS/:is), plus its
legacy alias `:matches`
- [`:scope`](https://developer.mozilla.org/en-US/docs/Web/CSS/:scope)
(uses the context from the passed options)
---
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)
# 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()
```
# regenerate-unicode-properties [](https://travis-ci.org/mathiasbynens/regenerate-unicode-properties) [](https://www.npmjs.com/package/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').characters;
const Greek = require('regenerate-unicode-properties/Script_Extensions/Greek.js').characters;
```
Some properties can also refer to strings rather than single characters:
```js
const { characters, strings } = require('regenerate-unicode-properties/Property_of_Strings/Basic_Emoji.js');
```
To get the Unicode version the data was based on:
```js
const unicodeVersion = require('regenerate-unicode-properties/unicode-version.js');
```
## For maintainers
### How to publish a new release
1. On the `main` branch, bump the version number in `package.json`:
```sh
npm version patch -m 'Release v%s'
```
Instead of `patch`, use `minor` or `major` [as needed](https://semver.org/).
Note that this produces a Git commit + tag.
1. Push the release commit and tag:
```sh
git push && git push --tags
```
Our CI then automatically publishes the new release to npm.
## Author
| [](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.
# common-path-prefix
Computes the longest prefix string that is common to each path, excluding the base component. Tested with Node.js 8 and above.
## Installation
```console
npm install common-path-prefix
```
## Usage
The module has one default export, the `commonPathPrefix` function:
```js
const commonPathPrefix = require('common-path-prefix')
```
Call `commonPathPrefix()` with an array of paths (strings) and an optional separator character:
```js
const paths = ['templates/main.handlebars', 'templates/_partial.handlebars']
commonPathPrefix(paths, '/') // returns 'templates/'
```
If the separator is not provided the first `/` or `\` found in any of the paths is used. Otherwise the platform-default value is used:
```js
commonPathPrefix(['templates/main.handlebars', 'templates/_partial.handlebars']) // returns 'templates/'
commonPathPrefix(['templates\\main.handlebars', 'templates\\_partial.handlebars']) // returns 'templates\\'
```
You can provide any separator, for example:
```js
commonPathPrefix(['foo$bar', 'foo$baz'], '$') // returns 'foo$''
```
An empty string is returned if no common prefix exists:
```js
commonPathPrefix(['foo/bar', 'baz/qux']) // returns ''
commonPathPrefix(['foo/bar']) // returns ''
```
Note that the following *does* have a common prefix:
```js
commonPathPrefix(['/foo/bar', '/baz/qux']) // returns '/'
```
# 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).
# string_decoder
***Node-core v8.9.4 string_decoder for userland***
[](https://nodei.co/npm/string_decoder/)
[](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-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.
# emoji-regex [](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
| [](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.
JS-YAML - YAML 1.2 parser / writer for JavaScript
=================================================
[](https://travis-ci.org/nodeca/js-yaml)
[](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)
# reusify
[![npm version][npm-badge]][npm-url]
[![Build Status][travis-badge]][travis-url]
[![Coverage Status][coveralls-badge]][coveralls-url]
Reuse your objects and functions for maximum speed. This technique will
make any function run ~10% faster. You call your functions a
lot, and it adds up quickly in hot code paths.
```
$ node benchmarks/createNoCodeFunction.js
Total time 53133
Total iterations 100000000
Iteration/s 1882069.5236482036
$ node benchmarks/reuseNoCodeFunction.js
Total time 50617
Total iterations 100000000
Iteration/s 1975620.838848608
```
The above benchmark uses fibonacci to simulate a real high-cpu load.
The actual numbers might differ for your use case, but the difference
should not.
The benchmark was taken using Node v6.10.0.
This library was extracted from
[fastparallel](http://npm.im/fastparallel).
## Example
```js
var reusify = require('reusify')
var fib = require('reusify/benchmarks/fib')
var instance = reusify(MyObject)
// get an object from the cache,
// or creates a new one when cache is empty
var obj = instance.get()
// set the state
obj.num = 100
obj.func()
// reset the state.
// if the state contains any external object
// do not use delete operator (it is slow)
// prefer set them to null
obj.num = 0
// store an object in the cache
instance.release(obj)
function MyObject () {
// you need to define this property
// so V8 can compile MyObject into an
// hidden class
this.next = null
this.num = 0
var that = this
// this function is never reallocated,
// so it can be optimized by V8
this.func = function () {
if (null) {
// do nothing
} else {
// calculates fibonacci
fib(that.num)
}
}
}
```
The above example was intended for synchronous code, let's see async:
```js
var reusify = require('reusify')
var instance = reusify(MyObject)
for (var i = 0; i < 100; i++) {
getData(i, console.log)
}
function getData (value, cb) {
var obj = instance.get()
obj.value = value
obj.cb = cb
obj.run()
}
function MyObject () {
this.next = null
this.value = null
var that = this
this.run = function () {
asyncOperation(that.value, that.handle)
}
this.handle = function (err, result) {
that.cb(err, result)
that.value = null
that.cb = null
instance.release(that)
}
}
```
Also note how in the above examples, the code, that consumes an istance of `MyObject`,
reset the state to initial condition, just before storing it in the cache.
That's needed so that every subsequent request for an instance from the cache,
could get a clean instance.
## Why
It is faster because V8 doesn't have to collect all the functions you
create. On a short-lived benchmark, it is as fast as creating the
nested function, but on a longer time frame it creates less
pressure on the garbage collector.
## Other examples
If you want to see some complex example, checkout [middie](https://github.com/fastify/middie) and [steed](https://github.com/mcollina/steed).
## Acknowledgements
Thanks to [Trevor Norris](https://github.com/trevnorris) for
getting me down the rabbit hole of performance, and thanks to [Mathias
Buss](http://github.com/mafintosh) for suggesting me to share this
trick.
## License
MIT
[npm-badge]: https://badge.fury.io/js/reusify.svg
[npm-url]: https://badge.fury.io/js/reusify
[travis-badge]: https://api.travis-ci.org/mcollina/reusify.svg
[travis-url]: https://travis-ci.org/mcollina/reusify
[coveralls-badge]: https://coveralls.io/repos/mcollina/reusify/badge.svg?branch=master&service=github
[coveralls-url]: https://coveralls.io/github/mcollina/reusify?branch=master
# jsdiff
[](http://travis-ci.org/kpdecker/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
[](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).
# 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
[](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.
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')`
# 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",
"maintained node versions"
]
```
Or in `.browserslistrc` config:
```yaml
# Browsers that we support
defaults
not IE 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.
[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
## Docs
Read **[full docs](https://github.com/browserslist/browserslist#readme)** on GitHub.
# has-property-descriptors <sup>[![Version Badge][npm-version-svg]][package-url]</sup>
[![github actions][actions-image]][actions-url]
[![coverage][codecov-image]][codecov-url]
[![dependency status][deps-svg]][deps-url]
[![dev dependency status][dev-deps-svg]][dev-deps-url]
[![License][license-image]][license-url]
[![Downloads][downloads-image]][downloads-url]
[![npm badge][npm-badge-png]][package-url]
Does the environment have full property descriptor support? Handles IE 8's broken defineProperty/gOPD.
## Example
```js
var hasPropertyDescriptors = require('has-property-descriptors');
var assert = require('assert');
assert.equal(hasPropertyDescriptors(), true); // will be `false` in IE 6-8, and ES5 engines
// Arrays can not have their length `[[Defined]]` in some engines
assert.equal(hasPropertyDescriptors.hasArrayLengthDefineBug(), false); // will be `true` in Firefox 4-22, and node v0.6
```
## Tests
Simply clone the repo, `npm install`, and run `npm test`
[package-url]: https://npmjs.org/package/has-property-descriptors
[npm-version-svg]: https://versionbadg.es/inspect-js/has-property-descriptors.svg
[deps-svg]: https://david-dm.org/inspect-js/has-property-descriptors.svg
[deps-url]: https://david-dm.org/inspect-js/has-property-descriptors
[dev-deps-svg]: https://david-dm.org/inspect-js/has-property-descriptors/dev-status.svg
[dev-deps-url]: https://david-dm.org/inspect-js/has-property-descriptors#info=devDependencies
[npm-badge-png]: https://nodei.co/npm/has-property-descriptors.png?downloads=true&stars=true
[license-image]: https://img.shields.io/npm/l/has-property-descriptors.svg
[license-url]: LICENSE
[downloads-image]: https://img.shields.io/npm/dm/has-property-descriptors.svg
[downloads-url]: https://npm-stat.com/charts.html?package=has-property-descriptors
[codecov-image]: https://codecov.io/gh/inspect-js/has-property-descriptors/branch/main/graphs/badge.svg
[codecov-url]: https://app.codecov.io/gh/inspect-js/has-property-descriptors/
[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/has-property-descriptors
[actions-url]: https://github.com/inspect-js/has-property-descriptors/actions
# to-regex-range [](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [](https://www.npmjs.com/package/to-regex-range) [](https://npmjs.org/package/to-regex-range) [](https://npmjs.org/package/to-regex-range) [](https://travis-ci.org/micromatch/to-regex-range)
> Pass two numbers, get a regex-compatible source string for matching ranges. Validated against more than 2.78 million test assertions.
Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support.
## Install
Install with [npm](https://www.npmjs.com/):
```sh
$ npm install --save to-regex-range
```
<details>
<summary><strong>What does this do?</strong></summary>
<br>
This libary generates the `source` string to be passed to `new RegExp()` for matching a range of numbers.
**Example**
```js
const toRegexRange = require('to-regex-range');
const regex = new RegExp(toRegexRange('15', '95'));
```
A string is returned so that you can do whatever you need with it before passing it to `new RegExp()` (like adding `^` or `$` boundaries, defining flags, or combining it another string).
<br>
</details>
<details>
<summary><strong>Why use this library?</strong></summary>
<br>
### Convenience
Creating regular expressions for matching numbers gets deceptively complicated pretty fast.
For example, let's say you need a validation regex for matching part of a user-id, postal code, social security number, tax id, etc:
* regex for matching `1` => `/1/` (easy enough)
* regex for matching `1` through `5` => `/[1-5]/` (not bad...)
* regex for matching `1` or `5` => `/(1|5)/` (still easy...)
* regex for matching `1` through `50` => `/([1-9]|[1-4][0-9]|50)/` (uh-oh...)
* regex for matching `1` through `55` => `/([1-9]|[1-4][0-9]|5[0-5])/` (no prob, I can do this...)
* regex for matching `1` through `555` => `/([1-9]|[1-9][0-9]|[1-4][0-9]{2}|5[0-4][0-9]|55[0-5])/` (maybe not...)
* regex for matching `0001` through `5555` => `/(0{3}[1-9]|0{2}[1-9][0-9]|0[1-9][0-9]{2}|[1-4][0-9]{3}|5[0-4][0-9]{2}|55[0-4][0-9]|555[0-5])/` (okay, I get the point!)
The numbers are contrived, but they're also really basic. In the real world you might need to generate a regex on-the-fly for validation.
**Learn more**
If you're interested in learning more about [character classes](http://www.regular-expressions.info/charclass.html) and other regex features, I personally have always found [regular-expressions.info](http://www.regular-expressions.info/charclass.html) to be pretty useful.
### Heavily tested
As of April 07, 2019, this library runs [>1m test assertions](./test/test.js) against generated regex-ranges to provide brute-force verification that results are correct.
Tests run in ~280ms on my MacBook Pro, 2.5 GHz Intel Core i7.
### Optimized
Generated regular expressions are optimized:
* duplicate sequences and character classes are reduced using quantifiers
* smart enough to use `?` conditionals when number(s) or range(s) can be positive or negative
* uses fragment caching to avoid processing the same exact string more than once
<br>
</details>
## Usage
Add this library to your javascript application with the following line of code
```js
const toRegexRange = require('to-regex-range');
```
The main export is a function that takes two integers: the `min` value and `max` value (formatted as strings or numbers).
```js
const source = toRegexRange('15', '95');
//=> 1[5-9]|[2-8][0-9]|9[0-5]
const regex = new RegExp(`^${source}$`);
console.log(regex.test('14')); //=> false
console.log(regex.test('50')); //=> true
console.log(regex.test('94')); //=> true
console.log(regex.test('96')); //=> false
```
## Options
### options.capture
**Type**: `boolean`
**Deafault**: `undefined`
Wrap the returned value in parentheses when there is more than one regex condition. Useful when you're dynamically generating ranges.
```js
console.log(toRegexRange('-10', '10'));
//=> -[1-9]|-?10|[0-9]
console.log(toRegexRange('-10', '10', { capture: true }));
//=> (-[1-9]|-?10|[0-9])
```
### options.shorthand
**Type**: `boolean`
**Deafault**: `undefined`
Use the regex shorthand for `[0-9]`:
```js
console.log(toRegexRange('0', '999999'));
//=> [0-9]|[1-9][0-9]{1,5}
console.log(toRegexRange('0', '999999', { shorthand: true }));
//=> \d|[1-9]\d{1,5}
```
### options.relaxZeros
**Type**: `boolean`
**Default**: `true`
This option relaxes matching for leading zeros when when ranges are zero-padded.
```js
const source = toRegexRange('-0010', '0010');
const regex = new RegExp(`^${source}$`);
console.log(regex.test('-10')); //=> true
console.log(regex.test('-010')); //=> true
console.log(regex.test('-0010')); //=> true
console.log(regex.test('10')); //=> true
console.log(regex.test('010')); //=> true
console.log(regex.test('0010')); //=> true
```
When `relaxZeros` is false, matching is strict:
```js
const source = toRegexRange('-0010', '0010', { relaxZeros: false });
const regex = new RegExp(`^${source}$`);
console.log(regex.test('-10')); //=> false
console.log(regex.test('-010')); //=> false
console.log(regex.test('-0010')); //=> true
console.log(regex.test('10')); //=> false
console.log(regex.test('010')); //=> false
console.log(regex.test('0010')); //=> true
```
## Examples
| **Range** | **Result** | **Compile time** |
| --- | --- | --- |
| `toRegexRange(-10, 10)` | `-[1-9]\|-?10\|[0-9]` | _132ฮผs_ |
| `toRegexRange(-100, -10)` | `-1[0-9]\|-[2-9][0-9]\|-100` | _50ฮผs_ |
| `toRegexRange(-100, 100)` | `-[1-9]\|-?[1-9][0-9]\|-?100\|[0-9]` | _42ฮผs_ |
| `toRegexRange(001, 100)` | `0{0,2}[1-9]\|0?[1-9][0-9]\|100` | _109ฮผs_ |
| `toRegexRange(001, 555)` | `0{0,2}[1-9]\|0?[1-9][0-9]\|[1-4][0-9]{2}\|5[0-4][0-9]\|55[0-5]` | _51ฮผs_ |
| `toRegexRange(0010, 1000)` | `0{0,2}1[0-9]\|0{0,2}[2-9][0-9]\|0?[1-9][0-9]{2}\|1000` | _31ฮผs_ |
| `toRegexRange(1, 50)` | `[1-9]\|[1-4][0-9]\|50` | _24ฮผs_ |
| `toRegexRange(1, 55)` | `[1-9]\|[1-4][0-9]\|5[0-5]` | _23ฮผs_ |
| `toRegexRange(1, 555)` | `[1-9]\|[1-9][0-9]\|[1-4][0-9]{2}\|5[0-4][0-9]\|55[0-5]` | _30ฮผs_ |
| `toRegexRange(1, 5555)` | `[1-9]\|[1-9][0-9]{1,2}\|[1-4][0-9]{3}\|5[0-4][0-9]{2}\|55[0-4][0-9]\|555[0-5]` | _43ฮผs_ |
| `toRegexRange(111, 555)` | `11[1-9]\|1[2-9][0-9]\|[2-4][0-9]{2}\|5[0-4][0-9]\|55[0-5]` | _38ฮผs_ |
| `toRegexRange(29, 51)` | `29\|[34][0-9]\|5[01]` | _24ฮผs_ |
| `toRegexRange(31, 877)` | `3[1-9]\|[4-9][0-9]\|[1-7][0-9]{2}\|8[0-6][0-9]\|87[0-7]` | _32ฮผs_ |
| `toRegexRange(5, 5)` | `5` | _8ฮผs_ |
| `toRegexRange(5, 6)` | `5\|6` | _11ฮผs_ |
| `toRegexRange(1, 2)` | `1\|2` | _6ฮผs_ |
| `toRegexRange(1, 5)` | `[1-5]` | _15ฮผs_ |
| `toRegexRange(1, 10)` | `[1-9]\|10` | _22ฮผs_ |
| `toRegexRange(1, 100)` | `[1-9]\|[1-9][0-9]\|100` | _25ฮผs_ |
| `toRegexRange(1, 1000)` | `[1-9]\|[1-9][0-9]{1,2}\|1000` | _31ฮผs_ |
| `toRegexRange(1, 10000)` | `[1-9]\|[1-9][0-9]{1,3}\|10000` | _34ฮผs_ |
| `toRegexRange(1, 100000)` | `[1-9]\|[1-9][0-9]{1,4}\|100000` | _36ฮผs_ |
| `toRegexRange(1, 1000000)` | `[1-9]\|[1-9][0-9]{1,5}\|1000000` | _42ฮผs_ |
| `toRegexRange(1, 10000000)` | `[1-9]\|[1-9][0-9]{1,6}\|10000000` | _42ฮผs_ |
## Heads up!
**Order of arguments**
When the `min` is larger than the `max`, values will be flipped to create a valid range:
```js
toRegexRange('51', '29');
```
Is effectively flipped to:
```js
toRegexRange('29', '51');
//=> 29|[3-4][0-9]|5[0-1]
```
**Steps / increments**
This library does not support steps (increments). A pr to add support would be welcome.
## History
### v2.0.0 - 2017-04-21
**New features**
Adds support for zero-padding!
### v1.0.0
**Optimizations**
Repeating ranges are now grouped using quantifiers. rocessing time is roughly the same, but the generated regex is much smaller, which should result in faster matching.
## Attribution
Inspired by the python library [range-regex](https://github.com/dimka665/range-regex).
## About
<details>
<summary><strong>Contributing</strong></summary>
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
</details>
<details>
<summary><strong>Running Tests</strong></summary>
Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:
```sh
$ npm install && npm test
```
</details>
<details>
<summary><strong>Building docs</strong></summary>
_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
To generate the readme, run the following command:
```sh
$ npm install -g verbose/verb#dev verb-generate-readme && verb
```
</details>
### Related projects
You might also be interested in these projects:
* [expand-range](https://www.npmjs.com/package/expand-range): Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. Usedโฆ [more](https://github.com/jonschlinkert/expand-range) | [homepage](https://github.com/jonschlinkert/expand-range "Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. Used by micromatch.")
* [fill-range](https://www.npmjs.com/package/fill-range): Fill in a range of numbers or letters, optionally passing an increment or `step` toโฆ [more](https://github.com/jonschlinkert/fill-range) | [homepage](https://github.com/jonschlinkert/fill-range "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`")
* [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/micromatch/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.")
* [repeat-element](https://www.npmjs.com/package/repeat-element): Create an array by repeating the given value n times. | [homepage](https://github.com/jonschlinkert/repeat-element "Create an array by repeating the given value n times.")
* [repeat-string](https://www.npmjs.com/package/repeat-string): Repeat the given string n times. Fastest implementation for repeating a string. | [homepage](https://github.com/jonschlinkert/repeat-string "Repeat the given string n times. Fastest implementation for repeating a string.")
### Contributors
| **Commits** | **Contributor** |
| --- | --- |
| 63 | [jonschlinkert](https://github.com/jonschlinkert) |
| 3 | [doowb](https://github.com/doowb) |
| 2 | [realityking](https://github.com/realityking) |
### Author
**Jon Schlinkert**
* [GitHub Profile](https://github.com/jonschlinkert)
* [Twitter Profile](https://twitter.com/jonschlinkert)
* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert)
Please consider supporting me on Patreon, or [start your own Patreon page](https://patreon.com/invite/bxpbvm)!
<a href="https://www.patreon.com/jonschlinkert">
<img src="https://c5.patreon.com/external/logo/[email protected]" height="50">
</a>
### License
Copyright ยฉ 2019, [Jon Schlinkert](https://github.com/jonschlinkert).
Released under the [MIT License](LICENSE).
***
_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on April 07, 2019._
# 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
# base-x
[](https://www.npmjs.org/package/base-x)
[](https://travis-ci.org/cryptocoinjs/base-x)
[](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.
# 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.
[](https://travis-ci.org/isaacs/yallist) [](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.)
# ncp - Asynchronous recursive file & directory copying
[](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`.
# ignore-by-default
This is a package aimed at Node.js development tools. It provides a list of
directories that should probably be ignored by such tools, e.g. when watching
for file changes.
It's used by [AVA](https://www.npmjs.com/package/ava) and
[nodemon](https://www.npmjs.com/package/nodemon).
[Please contribute!](./CONTRIBUTING.md)
## Installation
```
npm install ignore-by-default
```
## Usage
The `ignore-by-default` module exports a `directories()` function, which will
return an array of directory names. These are the ones you should ignore.
```js
// ['.git', '.sass_cache', โฆ]
const ignoredDirectories = require('ignore-by-default').directories()
```
# brace-expansion
[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html),
as known from sh/bash, in JavaScript.
[](http://travis-ci.org/juliangruber/brace-expansion)
[](https://www.npmjs.org/package/brace-expansion)
[](https://greenkeeper.io/)
[](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 <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# 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
```
# dom-serializer [](https://travis-ci.com/cheeriojs/dom-serializer)
Renders a [domhandler](https://github.com/fb55/domhandler) DOM node or an array of domhandler DOM nodes to a string.
```js
import render from "dom-serializer";
// OR
const render = require("dom-serializer").default;
```
# API
## `render`
โธ **render**(`node`: Node \| Node[], `options?`: [_Options_](#Options)): _string_
Renders a DOM node or an array of DOM nodes to a string.
Can be thought of as the equivalent of the `outerHTML` of the passed node(s).
#### Parameters:
| Name | Type | Default value | Description |
| :-------- | :--------------------------------- | :------------ | :----------------------------- |
| `node` | Node \| Node[] | - | Node to be rendered. |
| `options` | [_DomSerializerOptions_](#Options) | {} | Changes serialization behavior |
**Returns:** _string_
## Options
### `decodeEntities`
โข `Optional` **decodeEntities**: _boolean_
Encode characters that are either reserved in HTML or XML, or are outside of the ASCII range.
**`default`** true
---
### `emptyAttrs`
โข `Optional` **emptyAttrs**: _boolean_
Print an empty attribute's value.
**`default`** xmlMode
**`example`** With <code>emptyAttrs: false</code>: <code><input checked></code>
**`example`** With <code>emptyAttrs: true</code>: <code><input checked=""></code>
---
### `selfClosingTags`
โข `Optional` **selfClosingTags**: _boolean_
Print self-closing tags for tags without contents.
**`default`** xmlMode
**`example`** With <code>selfClosingTags: false</code>: <code><foo></foo></code>
**`example`** With <code>selfClosingTags: true</code>: <code><foo /></code>
---
### `xmlMode`
โข `Optional` **xmlMode**: _boolean_ \| _"foreign"_
Treat the input as an XML document; enables the `emptyAttrs` and `selfClosingTags` options.
If the value is `"foreign"`, it will try to correct mixed-case attribute names.
**`default`** false
---
## Ecosystem
| Name | Description |
| ------------------------------------------------------------- | ------------------------------------------------------- |
| [htmlparser2](https://github.com/fb55/htmlparser2) | Fast & forgiving HTML/XML parser |
| [domhandler](https://github.com/fb55/domhandler) | Handler for htmlparser2 that turns documents into a DOM |
| [domutils](https://github.com/fb55/domutils) | Utilities for working with domhandler's DOM |
| [css-select](https://github.com/fb55/css-select) | CSS selector engine, compatible with domhandler's DOM |
| [cheerio](https://github.com/cheeriojs/cheerio) | The jQuery API for domhandler's DOM |
| [dom-serializer](https://github.com/cheeriojs/dom-serializer) | Serializer for domhandler's DOM |
---
LICENSE: MIT
# wrappy
Callback wrapping utility
## USAGE
```javascript
var wrappy = require("wrappy")
// var wrapper = wrappy(wrapperFunction)
// make sure a cb is called only once
// See also: http://npm.im/once for this specific use case
var once = wrappy(function (cb) {
var called = false
return function () {
if (called) return
called = true
return cb.apply(this, arguments)
}
})
function printBoo () {
console.log('boo')
}
// has some rando property
printBoo.iAmBooPrinter = true
var onlyPrintOnce = once(printBoo)
onlyPrintOnce() // prints 'boo'
onlyPrintOnce() // does nothing
// random property is retained!
assert.equal(onlyPrintOnce.iAmBooPrinter, true)
```
# readable-stream
***Node-core v8.11.1 streams for userland*** [](https://travis-ci.org/nodejs/readable-stream)
[](https://nodei.co/npm/readable-stream/)
[](https://nodei.co/npm/readable-stream/)
[](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)) <[email protected]>
- Release GPG key: 9554F04D7259F04124DE6B476D5A82AC7E37093B
* **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) <[email protected]>
- Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242
* **Rod Vagg** ([@rvagg](https://github.com/rvagg)) <[email protected]>
- Release GPG key: DD8F2338BAE7501E3DD5AC78C273792F7D83545D
* **Sam Newman** ([@sonewman](https://github.com/sonewman)) <[email protected]>
* **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) <[email protected]>
* **Domenic Denicola** ([@domenic](https://github.com/domenic)) <[email protected]>
* **Matteo Collina** ([@mcollina](https://github.com/mcollina)) <[email protected]>
- Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E
* **Irina Shestak** ([@lrlna](https://github.com/lrlna)) <[email protected]>
# 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).
anymatch [](https://travis-ci.org/micromatch/anymatch) [](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)
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`
# node-hid - Access USB HID devices from Node.js #
[](http://npmjs.com/package/node-hid)
[](https://github.com/node-hid/node-hid/actions?query=workflow%3Amacos)
[](https://github.com/node-hid/node-hid/actions?query=workflow%3Awindows)
[](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 `[email protected]`, the [hidraw](https://www.kernel.org/doc/Documentation/hid/hidraw.txt) driver is used to talk to HID devices. Before `[email protected]`, the more older but less capable [libusb](http://libusb.info/) driver was used. With `hidraw` Linux apps can now see `usage` and `usagePage` attributes of devices.
If you would still like to use the `libusb` driver, then you can do either:
During runtime, you can use `HID.setDriverType('libusb')` immediately after require()-ing `node-hid`:
```js
var HID = require('node-hid');
HID.setDriverType('libusb');
```
If you must have the libusb version and cannot use `setDriverType()`,
you can install older node-hid or build from source:
```
npm install [email protected]
```
or:
```
npm install node-hid --build-from-source --driver=libusb
```
## Compiling from source
To compile & develop locally or if `prebuild` cannot download a pre-built
binary for you, you will need the following compiler tools and libraries:
### Linux (kernel 2.6+) : (install examples shown for Debian/Ubuntu)
* Compilation tools: `apt install build-essential git`
* 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.
<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
[](https://travis-ci.org/lukechilds/keyv)
[](https://coveralls.io/github/lukechilds/keyv?branch=master)
[](https://www.npmjs.com/package/keyv)
[](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 | [](https://travis-ci.org/lukechilds/keyv-redis) [](https://coveralls.io/github/lukechilds/keyv-redis?branch=master)
MongoDB | [@keyv/mongo](https://github.com/lukechilds/keyv-mongo) | Yes | [](https://travis-ci.org/lukechilds/keyv-mongo) [](https://coveralls.io/github/lukechilds/keyv-mongo?branch=master)
SQLite | [@keyv/sqlite](https://github.com/lukechilds/keyv-sqlite) | No | [](https://travis-ci.org/lukechilds/keyv-sqlite) [](https://coveralls.io/github/lukechilds/keyv-sqlite?branch=master)
PostgreSQL | [@keyv/postgres](https://github.com/lukechilds/keyv-postgres) | No | [](https://travis-ci.org/lukechildskeyv-postgreskeyv) [](https://coveralls.io/github/lukechilds/keyv-postgres?branch=master)
MySQL | [@keyv/mysql](https://github.com/lukechilds/keyv-mysql) | No | [](https://travis-ci.org/lukechilds/keyv-mysql) [](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
# Read This!
**These files are not meant to be edited by hand.**
If you need to make modifications, the respective files should be changed within the repository's top-level `src` directory.
Running `gulp LKG` will then appropriately update the files in this directory.
# 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.
[](https://travis-ci.org/motdotla/dotenv)
[](https://ci.appveyor.com/project/motdotla/dotenv/branch/master)
[](https://www.npmjs.com/package/dotenv)
[](https://github.com/feross/standard)
[](https://coveralls.io/github/motdotla/dotenv?branch=coverall-intergration)
## Install
```bash
# with npm
npm install dotenv
# or with Yarn
yarn add dotenv
```
## 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
```
`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](https://nodejs.org/api/cli.html#cli_r_require_module) 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
```
Additionally, you can use environment variables to set configuration options. Command line arguments will precede these.
```bash
$ DOTENV_CONFIG_<OPTION>=value node -r dotenv/config your_script.js
```
```bash
$ DOTENV_CONFIG_ENCODING=latin1 node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env
```
## Config
`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 may specify a custom path if your file containing environment variables is located elsewhere.
```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.
```js
require('dotenv').config({ encoding: 'latin1' })
```
#### Debug
Default: `false`
You may turn on logging to help debug why certain keys or values are not being set as you expect.
```js
require('dotenv').config({ debug: process.env.DEBUG })
```
## 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 = Buffer.from('BASIC=basic')
const config = dotenv.parse(buf) // will return an object
console.log(typeof config, config) // object { BASIC : 'basic' }
```
### Options
#### Debug
Default: `false`
You may turn on logging to help debug why certain keys or values are not being set as you expect.
```js
const dotenv = require('dotenv')
const buf = Buffer.from('hello world')
const opt = { debug: true }
const config = dotenv.parse(buf, opt)
// expect a debug message because the buffer is not in KEY=VAL form
```
### 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: ''}`)
- inner quotes are maintained (think JSON) (`JSON={"foo": "bar"}` becomes `{JSON:"{\"foo\": \"bar\"}"`)
- whitespace is removed from both ends of unquoted values (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'}`)
- single and double quoted values are escaped (`SINGLE_QUOTE='quoted'` becomes `{SINGLE_QUOTE: "quoted"}`)
- single and double quoted values maintain whitespace from both ends (`FOO=" some value "` becomes `{FOO: ' some value '}`)
- double quoted values expand new lines (`MULTILINE="new\nline"` becomes
```
{MULTILINE: 'new
line'}
```
## 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 (let k in envConfig) {
process.env[k] = envConfig[k]
}
```
### Can I customize/write plugins for dotenv?
For `[email protected]`: 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
const dotenv = require('dotenv')
const variableExpansion = require('dotenv-expand')
const myEnv = dotenv.config()
variableExpansion(myEnv)
```
### What about variable expansion?
Try [dotenv-expand](https://github.com/motdotla/dotenv-expand)
### 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'
import errorReporter from './errorReporter'
dotenv.config()
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 or environment variables 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?
[These npm modules depend on it.](https://www.npmjs.com/browse/depended/dotenv)
Projects that expand it often use the [keyword "dotenv" on npm](https://www.npmjs.com/search?q=keywords:dotenv).
# <img src="docs_app/assets/Rx_Logo_S.png" alt="RxJS Logo" width="86" height="86"> RxJS: Reactive Extensions For JavaScript
[](https://circleci.com/gh/ReactiveX/rxjs/tree/6.x)
[](http://badge.fury.io/js/%40reactivex%2Frxjs)
[](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/
# Update Browserslist DB
<img width="120" height="120" alt="Browserslist logo by Anton Lovchikov"
src="https://browserslist.github.io/browserslist/logo.svg" align="right">
CLI tool to update `caniuse-lite` with browsers DB
from [Browserslist](https://github.com/browserslist/browserslist/) config.
Some queries like `last 2 version` or `>1%` depends on actual data
from `caniuse-lite`.
```sh
npx update-browserslist-db@latest
```
<a href="https://evilmartians.com/?utm_source=update-browserslist-db">
<img src="https://evilmartians.com/badges/sponsored-by-evil-martians.svg"
alt="Sponsored by Evil Martians" width="236" height="54">
</a>
## Docs
Read **[full docs](https://github.com/browserslist/update-db#readme)** on GitHub.
[](LICENSE)
[](https://www.npmjs.org/package/lmdb)
[](https://www.npmjs.org/package/lmdb)
[](README.md)
[](README.md)
This is an ultra-fast NodeJS and Deno interface to LMDB; probably the fastest and most efficient key-value/database interface that exists for storage and retrieval of structured JS data (objects, arrays, etc.) in a true persisted, scalable, [ACID compliant](https://en.wikipedia.org/wiki/ACID) database. It provides a simple interface for interacting with LMDB, as a key-value db, that makes it easy to fully leverage the power, crash-proof design, and efficiency of LMDB using intuitive JavaScript, and is designed to scale across multiple processes or threads. Several key features that make it idiomatic, highly performant, and easy to use LMDB efficiently:
* High-performance translation of JS values and data structures to/from binary key/value data
* Queueing asynchronous off-thread write operations with promise-based API
* Simple transaction management
* Iterable queries/cursors
* Record versioning and optimistic locking for scalability/concurrency
* Optional native off-main-thread compression with high-performance LZ4 compression <a href="https://github.com/kriszyp/db-benchmark"><img align="right" src="./assets/performance.png" width="380"/></a>
* And ridiculously fast and efficient, with integrated (de)serialization, data retrieval can be several times faster than `JSON` alone
`lmdb-js` is used in many heavy-use production applications, including as a high-performance cache for builds in [Parcel](https://parceljs.org/) and [Elasticsearch's Kibana](https://www.elastic.co/kibana/), as the storage layer for [HarperDB](https://harperdb.io/) and [Gatsby](https://www.gatsbyjs.com/)'s database, and for search and analytical engine for our [clinical medical research](https://drevidence.com).
<a href="https://www.elastic.co/kibana/"><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt4466841eed0bf232/5d082a5e97f2babb5af907ee/logo-kibana-32-color.svg" width="40" align="right"></a>
<a href="https://parceljs.org/"><img src="https://parceljs.org/avatar.633bb25a.avif" width="56" align="right"></a>
<a href="https://harperdb.io/"><img src="./assets/harperdb.png" width="55" align="right"/></a>
<a href="https://www.gatsbyjs.com/"><img src="./assets/gatsby.png" width="60" align="right"/></a>
This library is published to the NPM package `lmdb` (the 1.x versions were published to `lmdb-store`), and can be installed with:
```
npm install lmdb
```
`lmdb-js` is based on the Node-API for maximum compatility across all supported Node versions and futue Deno versions. It also includes accelerated, high-speed functions for direct V8 interaction that are compiled for, and (automatically) loaded in Node v16. The standard Node-API based functions are used in all other versions and still provide excellent performance, but for absolute maximum performance on older versions of Node, you can use `npm install --build-from-source`.
In Deno, this package could be directly used from the [deno.land `lmdb` module](https://deno.land/x/lmdb/mod.ts), but Node-API support is currently in-progress, so probably will require Deno v1.24+ (for older versions of Deno, you can use `lmdb-js` v2.2.x).
This library has minimal, tightly-controlled, and maintained dependencies to ensure stability, security, and efficiency. It supports both native ESM and CJS usage.
## Design
This library handles translation of JavaScript values, primitives, arrays, and objects, to and from the binary storage of LMDB keys and values with highly optimized native C++ code for breakneck performance. It supports multiple types of JS values for keys and values, making it easy to use idiomatic JS for storing and retrieving data in LMDB.
`lmdb-js` is designed for synchronous reads, and asynchronous writes. In idiomatic NodeJS and Deno code, I/O operations are performed asynchronously. LMDB is a memory-mapped database, reading and writing within a transaction does not use any I/O (other than the slight possibility of a page fault), and can usually be performed faster than the event queue callbacks can even execute, and it is easier to write code for instant synchronous values from reads. On the otherhand, commiting transactions does involve I/O, and vastly higher throughput can be achieved by batching operations and executing on a separate thread. Consequently, `lmdb-js` is designed for transactions to go through this asynchronous batching process and return a simple promise that resolves once data is written and flushed to disk.
With the default sync'ing configuration, LMDB has a crash-proof design; a machine can be turned off at any point, and data can not be corrupted unless the written data is actually changed or tampered. Writing data and waiting for confirmation that has been writted to the physical medium is critical for data integrity, but is well known to have latency (although not necessarily less efficient). However, by batching writes, when a database is under load, slower transactions enable more writes per transaction, and this library is able to drive LMDB to achieve the maximum levels of throughput with fully sync'ed operations, preserving both the durability/safety of the transactions and unparalled performance.
This library supports and encourages the use of conditional writes; this allows for atomic operations that are dependendent on previously read data, and most transactional types of operations can be written with an optimistic-locking based, atomic-conditional-write pattern. This allows this library to delegate writes to off-thread execution, and scale to handle concurrent execution across many processes or threads while maintaining data integrity.
This library automatically handles automatically database growth, expanding file size with a smart heuristic that minimizes file fragmentation (as you would expect from a database).
This library provides optional compression using LZ4 that works in conjunction with the asynchronous writes by performing the compression in the same thread (off the main thread) that performs the writes in a transaction. LZ4 is extremely fast, and decompression can be performed at roughly 5GB/s, so excellent storage efficiency can be achieved with almost negligible performance impact.
## Usage
An LMDB database instance is created by using `open` export from the main module:
```js
import { open } from 'lmdb'; // or require
let myDB = open({
path: 'my-db',
// any options go here, we can turn on compression like this:
compression: true,
});
await myDB.put('greeting', { someText: 'Hello, World!' });
myDB.get('greeting').someText // 'Hello, World!'
// or
myDB.transaction(() => {
myDB.put('greeting', { someText: 'Hello, World!' });
myDB.get('greeting').someText // 'Hello, World!'
});
```
(see database options below for more options)
Once you have opened a database, you can store and retrieve values using keys:
### Values
You can store a wide variety of JavaScript values and data structures in this library, including objects (with arbitrary complexity), arrays, buffers, strings, numbers, etc. in your database. Even full structural cloning (with cycles) is an optionally supported. Values are stored and retrieved according the database encoding, which can be set using the `encoding` property on the database options. By default, data is stored using MessagePack, but there are several supported encodings:
* `msgpack` (default) - All values are stored by serializing the value as MessagePack (using the [msgpackr](https://github.com/kriszyp/msgpackr) package). Values are decoded and parsed on retrieval, so `get` and `getRange` will return the object, array, or other value that you have stored. The msgpackr package is extremely fast (usually faster than native JSON), and provides the most flexibility in storing different value types. See the Shared Structures section for how to achieve maximum efficiency with this.
* `cbor` - This specifies all values use the CBOR format, which requires that the [cbor-x](https://github.com/kriszyp/cbor-x) package be installed. This package is based on [msgpackr](https://github.com/kriszyp/msgpackr) and supports all the same options.
* `json` - All values are stored by serializing the value as JSON (using JSON.stringify) and encoded with UTF-8. Values are decoded and parsed on retrieval using JSON.parse. Generally this does not perform as all as msgpack, nor support as many value types.
* `string` - All values should be strings and stored by encoding with UTF-8. Values are returned as strings from `get`.
* `binary` - Values are returned as binary arrays (`Buffer` objects in NodeJS), representing the raw binary data. Note that creating buffer objects has some overhead and while this is fast and valuable direct storage of binary data, the data encodings provides faster and more optimized process for serializing and deserializing structured data.
* `ordered-binary` - Use the same encoding as the default encoding for keys, which serializes any JS primitive value with consistent ordering. This is primarily useful in `dupSort` databases where data values are ordered, and having consistent key and value ordering is helpful.
In addition, you can use `asBinary` to directly store a buffer or Uint8Array as a value, bypassing any encoding.
### Keys
When using the various APIs, keys can be any JS primitive (string, number, boolean, symbol), an array of primitives, or a Buffer. Using the default `ordered-binary` conversion, primitives are translated to binary keys used by LMDB in such a way that consistent ordering is preserved. Numbers are ordered naturally, which come before strings, which are ordered lexically. The keys are stored with type information preserved. The `getRange`operations that return a set of entries will return entries with the original JS primitive values for the keys. If arrays are used as keys, they are ordering by first value in the array, with each subsequent element being a tie-breaker. Numbers are stored as doubles, with reversal of sign bit for proper ordering plus type information, so any JS number can be used as a key. For example, here are the order of some different keys:
```js
null // lowest possible value
Symbol.for('even symbols')
-10 // negative supported
-1.1 // decimals supported
400
3E10
'Hello'
['Hello', 'World']
'World'
'hello'
['hello', 1, 'world']
['hello', 'world']
Buffer.from([255]) // buffers can be used directly, 255 is higher than any byte produced by primitives
```
You can override the default encoding of keys, and cause keys to be returned as binary arrays (`Buffer`s in NodeJS) using the `keyEncoding: 'binary'` database option (generally slower), use `keyEncoding: 'uint32'` for keys that are strictly 32-bit unsigned integers, or provide a custom key encoder/decoder with `keyEncoder` (see custom key encoding).
Once you created have a db, the following methods are available:
### `db.get(key): any`
This will retrieve the value at the specified key. The `key` must be a JS value/primitive as described above, and the return value will be the stored data (dependent on the encoding), or `undefined` if the entry does not exist.
### `db.getEntry(key): any`
This will retrieve the the entry at the specified key. The `key` must be a JS value/primitive as described above, and the return value will be the stored entry, or `undefined` if the entry does not exist. An entry is object with a `value` property for the value in the database (as returned by `db.get`), and a `version` property for the version number of the entry in the database (if `useVersions` is enabled for the database).
### `db.put(key, value, version?: number, ifVersion?: number): Promise<boolean>`
This will store the provided value/data at the specified key. If the database is using versioning (see options below), the `version` parameter will be used to set the version number of the entry. If the `ifVersion` parameter is set, the put will only occur if the existing entry at the provided key has the version specified by `ifVersion` at the instance the commit occurs (LMDB commits are atomic by default). If the `ifVersion` parameter is not set, the put will occur regardless of the previous value.
This operation will be enqueued to be written in a batch transaction. Any other operations that occur within the current event turn (until next event after I/O by default) will also occur in the same transaction. This will return a promise for the completion of the put. The promise will resolve once the transaction has finished committing. The resolved value of the promise will be `true` if the `put` was successful, and `false` if the put did not occur due to the `ifVersion` not matching at the time of the commit. Once the promise resolves, the transaction will have been fully written to the physical storage medium (durable commit, guaranteed available in the future as far as the OS/physical storage can permit and confirm, even if there is power loss or system crash).
If `put` is called inside a transaction, the put will be executed immediately in the current transaction.
### `db.remove(key, IfVersion?: number): Promise<boolean>`
This will delete the entry at the specified key. This functions like `put`, with the same optional conditional version. This is batched along with put operations, and returns a promise indicating the success of the operation.
Again, if this is performed inside a transation, the removal will be performed in the current transaction.
### `db.remove(key, value?: any): Promise<boolean>`
If you are using a database with duplicate entries per key (with `dupSort` flag), you can specify the value to remove as the second parameter (instead of a version).
### `db.transaction(callback: Function): Promise`
This will run the provided callback in a transaction, asynchronously starting the transaction, then running the callback, then later committing the transaction. By running within a transaction, the code in the callback can perform multiple database operations atomically and isolated (fully [ACID compliant](https://en.wikipedia.org/wiki/ACID)). Any `put` or `remove` operations are immediately written to the transaction and can be immediately read afterwards (you can call `get()` or `getRange()` without awaiting for a returned promise) in the transaction.
The callback function will be queued along with other `put` and `remove` operations, and run in the same transaction as other operations that have been queued in the current event turn, and will be executed in the order they were called. `transaction` will return a promise that will resolve once its transaction has been committed. The promise will resolve to the value returned by the callback function.
For example:
```js
let products = open(...);
// decrement count if above zero
function buyShoe() {
return products.transaction(() => {
let shoe = products.get('shoe')
// this is performed atomically, so we can guarantee no other processes
// modify this entry before we write the new value
if (shoe.count > 0) {
shoe.count--
products.put('shoe', shoe)
return true // succeeded
}
return false // count is zero, no shoes to buy
})
}
```
Note that `db.transaction(() => db.put(...))` is functionally the same as calling `db.put(...)`, queuing the put for asynchronously being committed in transaction, except that `put` executes the database's write operation entirely in separate worker thread, whereas `transaction` must also synchronize the callback function in the main JS thread to execute (so it is a little bit less efficient, although still quite fast).
Also, the callback function can be an async function (or return a promise), but this is not recommended. If the function returns a promise, this will delay/defer the commit until the callback's promise is resolved. However, while waiting for the callback to finish, other code may execute operations that would end up in the current transaction and may result in a surprising order of operations, and long running transactions are generally discouraged since they extend the single write lock.
### `db.childTransaction(callback: Function): Promise`
This will run the provided callback in a transaction much like `transaction` except an explicit child transaction will be used specifically for this callback. This makes it possible for the operations to be aborted and rolled back. The callback may return the exported `ABORT` constant to abort the child transaction for this callback. Also, if the callback function throws an error (or returns a reject promise), this will also abort the child transaction. This childTransaction function is not available if caching or `useWritemap` is enabled.
The `childTransaction` function can be executed on its own (to run the child transaction inside the next queued transaction), or it can be executed inside another transaction callback, executing the child transaction within the current transaction.
### `db.committed: Promise`
This is a promise-like object that resolves when all previous writes have been committed.
### `db.flushed: Promise`
This is a promise-like object that resolves when all previous writes have been committed and fully flushed/synced to disk/storage.
### `db.putSync(key, value, versionOrOptions?: number | PutOptions): boolean`
This will set the provided value at the specified key, but will do so synchronously. If this is called inside of a transaction, the put will be performed in the current transaction. If not, a transaction will be started, the put will be executed, the transaction will be committed, and then the function will return. We do not recommend this be used for any high-frequency operations as it can be vastly slower (often blocking the main JS thread for multiple milliseconds) than the `put` operation (typically consumes a few _microseconds_ on a worker thread). The third argument may be a version number or an options object that supports `append`, `appendDup`, `noOverwrite`, `noDupData`, and `version` for corresponding LMDB put flags.
### `db.removeSync(key, valueOrIfVersion?: number): boolean`
This will delete the entry at the specified key. This functions like `putSync`, providing synchronous entry deletion, and uses the same arguments as `remove`. This returns `true` if there was an existing entry deleted, `false` if there was no matching entry.
### `db.ifVersion(key, ifVersion: number, callback): Promise<boolean>`
This executes a block of conditional writes, and conditionally execute any puts or removes that are called in the callback, using the provided condition that requires the provided key's entry to have the provided version.
### `db.ifNoExists(key, callback): Promise<boolean>`
This executes a block of conditional writes, and conditionally execute any puts or removes that are called in the callback, using the provided condition that requires the provided key's entry does not exist yet.
### `db.transactionSync(callback: Function)`
This will begin a synchronous transaction, executing the provided callback function, and then commit the transaction. The provided function can perform `get`s, `put`s, and `remove`s within the transaction, and the result will be committed. The `callback` function can return a promise to indicate an ongoing asynchronous transaction, but generally you want to minimize how long a transaction is open on the main thread, at least if you are potentially operating with multiple processes.
The callback may return the exported `ABORT` constant, or throw an error from the callback, to abort the transaction for this callback.
If this is called inside an existing transaction and child transactions are supported (no write maps or caching), this will execute as a child transaction (and can be aborted), otherwise it will simply execute as part of the existing transaction (in which case it can't be aborted).
### `db.getRange(options: RangeOptions): Iterable<{ key, value: Buffer }>`
This starts a cursor-based query of a range of data in the database, returning an iterable that also has `map`, `filter`, and `forEach` methods. The `start` and `end` indicate the starting and ending key for the range. The `reverse` flag can be used to indicate reverse traversal. The `limit` can limit the number of entries returned. The returned cursor/query is lazy, and retrieves data _as_ iteration takes place, so a large range could specified without forcing all the entries to be read and loaded in memory upfront, and one can exit out of the loop without traversing the whole range in the database. The query is iterable, we can use it directly in a for-of:
```js
for (let { key, value } of db.getRange({ start, end })) {
// for each key-value pair in the given range
}
```
Or we can use the provided iterative methods on the returned results:
```js
db.getRange({ start, end })
.filter(({ key, value }) => test(key))
.forEach(({ key, value }) => {
// for each key-value pair in the given range that matched the filter
})
```
Note that `map` and `filter` are also lazy, they will only be executed once their returned iterable is iterated or `forEach` is called on it. The `map` and `filter` functions also support async/promise-based functions, and you can create an async iterable if the callback functions execute asynchronously (return a promise).
We can also query with offset to skip a certain number of entries, and limit the number of entries to iterate through:
```js
db.getRange({ start, end, offset: 10, limit: 10 }) // skip first 10 and get next 10
```
If you want to get a true array from the range results, the `asArray` property will return the results as an array.
#### Snapshots
By default a range iterator will use a database snapshot, using a single read transaction that remains open and gives a consistent view of the database at the time it was started, for the duration of iterating through the range. However, if the iteration will take place over a long period of time, keeping a read transaction open for a long time can interfere with LMDB's free space collection and reuse and increase the database size. If you will be using a long duration iterator, you can specify `snapshot: false` flag in the range options to indicate that it snapshotting is not necessary, and it can reset and renew read transactions while iterating, to allow LMDB to collect any space that was freed during iteration.
### `db.getValues(key, options?: RangeOptions): Iterable<any>`
When using a database with duplicate entries per key (with `dupSort` flag), you can use this to retrieve all the values for a given key. This will return an iterator just like `getRange`, except each entry will be the value from the database:
```js
let db = db.openDB('my-index', {
dupSort: true,
encoding: 'ordered-binary',
});
await db.put('key1', 'value1');
await db.put('key1', 'value2');
for (let value of db.getValues('key1')) {
// iterate values 'value1', 'value2'
}
await db.remove('key', 'value1'); // only remove the second value under key1
for (let value of db.getValues('key1')) {
// just iterate value 'value1'
}
```
You can optionally provide a second argument with the same `options` that `getRange` handles. You can provide a `start` and/or `end` values, which will be define the starting value and ending value for the range of values to return for the key:
```js
for (let value of db.getValues('key1', { start: 'value1', end: 'value3'})) ...
```
Using `start`/`end` is only supported if using the `ordered-binary` encoding.
### `db.getKeys(options: RangeOptions): Iterable<any>`
This behaves like `getRange`, but only returns the keys. If this is duplicate key database, each key is only returned once (even if it has multiple values/entries).
### `RangeOptions`
Here are the options that can be provided to the range methods (all are optional):
* `start`: Starting key (will start at beginning of db, if not provided), can be any valid key type (primitive or array of primitives).
* `end`: Ending key (will finish at end of db, if not provided), can be any valid key type (primitive or array of primitives).
* `reverse`: Boolean key indicating reverse traversal through keys (does not do reverse by default).
* `limit`: Number indicating maximum number of entries to read (no limit by default).
* `offset`: Number indicating number of entries to skip before starting iteration (starts at 0 by default).
* `versions`: Boolean indicating if versions should be included in returned entries (not by default).
* `snapshot`: Boolean indicating if a database snapshot is used for iteration (true by default).
### `db.openDB(database: string|{name:string,...})`
LMDB supports multiple databases per environment (an environment corresponds to a single memory-mapped file). When you initialize an LMDB database with `open`, the database uses the default root database. However, you can use multiple databases per environment/file and instantiate a database for each one. If you are going to be opening many databases, make sure you set the `maxDbs` (it defaults to 12). For example, we can open multiple databases for a single environment:
```js
import { open } from 'lmdb';
let rootDB = open('all-my-data');
let usersDB = myDB.openDB('users');
let groupsDB = myDB.openDB('groups');
let productsDB = myDB.openDB('products');
```
Each of the opened/returned databases has the same API as the default database for the environment. Each of the databases for one environment also share the same batch queue and automated transactions with each other, so immediately writing data from two databases with the same environment will be batched together in the same commit. For example:
```js
usersDB.put('some-user', { data: userInfo });
groupsDB.put('some-group', { groupData: moreData });
```
Both these puts will be batched and committed in the same transaction in the next event turn.
Also, you can start a transaction from one database and make writes from any of the databases in that same environment (and they will be a part of the same transaction):
```js
rootDB.transaction(() => {
usersDB.put('some-user', { data: userInfo });
groupsDB.put('some-group', { groupData: moreData });
});
```
### `getLastVersion(): number`
This returns the version number of the last entry that was retrieved with `get` (assuming it was a versioned database). If you are using a database with `cache` enabled, use `getEntry` instead.
### `asBinary(buffer): Binary`
This can be used to directly store a buffer or Uint8Array as a value, bypassing any encoding. If you are using a database with an encoding that isn't `binary`, setting a value with a Uint8Array will typically be encoded with the db's encoding (for example MessagePack wraps in a header, preserving its type for `get`). However, if you want to bypass encoding, for example, if you have already encoded a value, you can use `asBinary`:
```js
let buffer = encode(myValue) // if we have already serialized a value, perhaps to compare it or check its size
db.put(key, asBinary(buffer)) // we can directly store the encoded value
```
### `close(): Promise`
This will close the current db. This closes the underlying LMDB database, and if this is the root database (opened with `open` as opposed to `db.openDB`), it will close the environment (and child databases will no longer be able to interact with the database). This is asynchronous, waiting for any outstanding transactions to finish before closing the database.
### `db.doesExist(key, valueOrVersion): boolean`
This checks if an entry exists for the given key, and optionally verifies that the version or value exists. If this is a `dupSort` enabled database, you can provide the key and value to check if that key/value entry exists. If you are using a versioned database, you can provide a version number to verify if the entry for the provided key has the specific version number. This returns true if the entry does exist.
### `db.getBinary(key): Buffer`
This will retrieve the binary data at the specified key. This is just like `get`, except it will always return the value's binary representation as a buffer, rather than decoding with the db's encoding format (if there is no entry, `undefined` will still be returned).
### `db.getBinaryFast(key): Buffer`
This will retrieve the binary data at the specified key, like `getBinary`, except it uses reusable buffers, which is faster, but means the data in the buffer is only valid until the next get operation (including cursor operations). Since this is a reusable buffer it also slightly differs from a typical buffer: the `length` property is set to the length of the value (what you typically want for normal usage), but the `byteLength` will be the size of the full allocated memory area for the buffer (usually much larger).
### `db.prefetch(ids, callback?): Promise`
With larger databases and situations where the data in the database may not be cached in memory, it may be advisable to use asynchronous methods to fetch data to avoid slow/expensive hard-page faults on the main thread. This method provides a means of asynchronously fetching data in separate thread/asynchronously to ensure data is in memory. This fetches the data for given ids and accesses all pages to ensure that any hard page faults are done asynchronously. Once completed, synchronous gets to the same entries will most likely be in memory and fast. The `prefetch` can also be run in parallel with sync `get`s (for the same entries) in situations where the main thread be busy with deserialization and other work at roughly the same rate as the prefetch page faults might occur.
### `db.getMany(ids: K[], callback?): Promise`
Asynchronously gets the values stored by the given ids and return the values in array corresponding to the array of ids. This uses `prefetch` followed by `get`s for each entry once the data is prefetched.
### `db.clearAsync(): Promise` and `db.clearSync()`
These methods remove all the entries from a database (asynchronously or synchronously, respectively).
### `db.drop(): Promise` and `db.dropSync()`
These methods remove all the entries from a database and delete that database (asynchronously or synchronously, respectively).
### `resetReadTxn(): void`
Normally, this library will automatically start a reader transaction for get and range operations, periodically reseting the read transaction on new event turns and after any write transactions are committed, to ensure it is using an up-to-date snapshot of the database. However, you can call `resetReadTxn` if you need to manually force the read transaction to reset to the latest snapshot/version of the database. In particular, this may be useful running with multiple processes where you need to immediately reset the read transaction based on a known update in another process (rather than waiting for the next event turn).
## Concurrency and Versioning
LMDB and this library are designed for high concurrency, and we recommend using multiple processes to achieve concurrency (processes are more robust than threads, and thread's advantage of shared memory is minimal with separate JavaScript workers, and you still get shared memory access with processes when using LMDB). Versioning or asynchronous transactions are the preferred method for achieving atomicity with data updates with concurrency. A version can be stored with an entry, and later the data can be updated, conditional on the version being the expected version. This provides a robust mechanism for concurrent data updates even with multiple processes are accessing the same database. To enable versioning, make sure to set the `useVersions` option when opening the database:
```js
let myDB = open('my-db', { useVersions: true });
```
You can set a version by using the `version` argument in `put` calls. You can later update data and ensure that the data will only be updated if the version matches the expected version by using the `ifVersion` argument. When retrieving entries, you can access the version number by calling `getLastVersion()`.
You can then make conditional writes, examples:
```js
myDB.put('key1', 'value1', 4, 3); // new version of 4, only if previous version was 3
```
```
myDB.ifVersion('key1', 4, () => {
myDB.put('key1', 'value2', 5); // equivalent to myDB.put('key1', 'value2', 5, 4);
myDB.put('anotherKey', 'value', 3); // we can do other puts based on the same condition above
// we can make puts in other databases (from the same database environment) based on same condition too
myDB2.put('keyInOtherDb', 'value');
});
```
Asynchronous transactions are also a robust way to handle concurrency with multiple processes and provides a more traditional and flexible mechanism for making atomic ACID-compliant transactional data changes.
## Shared Structures
Shared structures are mechanism for storing the structural information about objects stored in database in dedicated entry, outside of individual entries, for reuse across all of the data in database, for much more efficient storage and faster retrieval of data when storing objects that have the same or similar structures (note that this is only available using the default MessagePack or CBOR encoding, using the msgpackr or cbor-x package). This is highly recommended when storing structured objects with similiar object structures (including inside of array). When enabled, when data is stored, any structural information (the set of property names) is automatically generated and stored in separate entry to be reused for storing and retrieving all data for the database. To enable this feature, simply specify the key where shared structures can be stored. You can use a symbol as a metadata key, as symbols are outside of the range of the standard JS primitive values:
```js
let myDB = open('my-db', {
sharedStructuresKey: Symbol.for('structures')
})
```
Once shared structures has been enabled, you can persist JavaScript objects just as you would normally would, and this library will automatically generate, increment, and save the structural information in the provided key to improve storage efficiency and performance. You never need to directly access this key, just be aware that that entry is being used by this library.
## Compression
This library can optionally use off-thread LZ4 compression as part of the asynchronous writes to enable efficient compression with virtually no overhead to the main thread. LZ4 decompression (in `get` and `getRange` calls) is extremely fast and generally has a low impact on performance. Compression is turned off by default, but can be turned on by setting the `compression` property when opening a database. The value of compression can be `true` or an object with compression settings, including properties:
* `threshold` - Only entries that are larger than this value (in bytes) will be compressed. This defaults to 1000 (if compression is enabled)
* `dictionary` - This can be buffer to use as a shared dictionary. This is defaults to a shared dictionary that helps with compressing JSON and English words in small entries. [Zstandard](https://facebook.github.io/zstd/#small-data) provides utilities for [creating your own optimized shared dictionary](https://github.com/lz4/lz4/releases/tag/v1.8.1.2).
For example:
```js
let myDB = open('my-db', {
compression: {
threshold: 500, // compress any entry larger than 500 bytes
dictionary: fs.readFileSync('dict.txt') // use your own shared dictionary
}
})
```
Compression is recommended for large databases that may be close to or larger than available RAM, to improve caching and reduce page faults. If you enable compression for a database, you must ensure that the data is always opened with the same compression setting, so that the data will be properly decompressed.
## Caching
This library supports caching of entries from databases, and uses a [LRU/LFU (LRFU) and weak-referencing caching mechanism](https://github.com/kriszyp/weak-lru-cache) for highly optimized caching and object tracking. There are several key potential benefits to using caching, including performance, key correlation with object identity, and immediate/synchronous access to saved data. Enabling caching will cache `get`s and `put`s, which can make frequent `get`s much faster. Caching is enabled by providing a truthy value for the `cache` property on the database `options`.
The weak-referencing mechanism works in harmony with JS garbage collection to allow objects to be cached without preventing GC, and retrieved from the cache until they have actually been collected from memory, making more efficient use of memory. This also can provide a guarantee of object identity correlation with keys: as long as retrieved object is in memory, a `get` will always return the existing object, and `get` never will return two copies of the same object (for the same key). The LRFU caching mechanism is scan-resistant, tracking frequency of usage as well as recency.
Because asynchronous `put` operations immediately go in the cache (and are pinned in the cache until committed), the caching enabled, `put` values can be retrieved via `get`, immediately and synchronously after the `put` call. Without caching enabled, you need wait for the `put` promise to resolve (or use asynchronous transactions) before you can access the stored value, but the cache enables the value to be immediately without waiting for the commit to finish:
```js
db.put('hi', 'there');
db.get('hi'); // can immediately access value without having to await the promise
```
While caching can improve performance, LMDB itself is extremely fast, and for small objects with sporadic access, caching may not improve performance. Caching tends to provide the most performance benefits for larger objects that may have more significant deserialization costs. Caching does not apply to `getRange` queries. Also note that this requires Node 14.10 or higher (or Node v13.0 with `--harmony-weak-ref` flag).
If you are using caching with a database that has versions enabled, you should use the `getEntry` method to get the `value` and `version`, as `getLastVersion` will not be reliable (only returns the version when the data is accessed from the database).
### Asynchronous Transaction Ordering
Asynchronous single operations (`put` and `remove`) are executed in the order they were called, relative to each other. Likewise, asynchronous transaction callbacks (`transaction` and `childTransaction`) are also executed in order relative to other asynchronous transaction callbacks. However, by default all queued asynchronous transaction callbacks are executed _after_ all queued asynchronous single operations. But, you can enable strict ordering so that asynchronous transactions executed in order _with_ the asynchronous single operations, by setting the `strictAsyncOrder ` property to `true`.
However, strict ordering comes with a couple of caveats. First, because asynchronous single operations are executed on separate transaction threads, but asynchronous transaction callbacks must execute on the main JS thread, if there is a lot of frequent switching back and forth between single operations and callbacks, this can significantly reduce performance since it requires substantial thread switching and event queuing.
Second, if there are asynchronous operations that have been performed, and asynchronous transaction callbacks that are waiting to be called, and a synchronous transaction is executed (`transactionSync`), this must interrupt and split the current asynchronous transaction batch, so the synchronous transaction can be executed (the synchronous transaction can not block to wait for the asynchronous if there are outstanding callbacks to execute as part of that async transaction, as that would result in a deadlock). This can potentially create an exception to the general rule that all asynchronous operations that are performed in one event turn will be part of the same transaction. Of course, each single asynchronous transaction callback is still guaranteed to execute in a single atomic transaction (and calls to `transactionSync` _during_ a asynchronous transaction callback are simply executed as part of the current transaction). With the default ordering of 'after', it is possible for the async transactions to be performed in a separate transaction than the single operations if executed.
### DB Options
The open method can be used to create the main database/environment with the following signature:
`open(path, options)` or `open(options)`
Additional databases can be opened within the main database environment with:
`db.openDB(name, options)` or `db.openDB(options)`
If the `path` has an `.` in it, it is treated as a file name, otherwise it is treated as a directory name, where the data will be stored. The path can be omitted to create a temporary database, which will be created in the system temp directory and deleted on close. The `options` argument to either of the functions should be an object, and supports the following properties, all of which are optional (except `name` if not otherwise specified):
* `name` - This is the name of the database. This defaults to null (which is the root database) when opening the database environment (`open`). When an opening a database within an environment (`openDB`), this is required, if not specified in first parameter.
* `encoding` - Sets the encoding for the database values, which can be `'msgpack'`, `'json'`, `'cbor'`, `'string'`, `'ordered-binary'`or `'binary'`.
* `encoder` - Directly set the encoder to use or provide the settings for an encoder. This can be an object with settings to pass to the encoder or can be an object with `encode` and `decode` methods. It can also be an object with an `Encoder` that will be called to create the encoder instance. This allows you explicitly set the encoder with an import:
```js
import * as cbor from 'cbor-x';
let db = open({ encoder: cbor });
```
* `sharedStructuresKey` - Enables shared structures and sets the key where the shared structures will be stored.
* `compression` - This enables compression. This can be set a truthy value to enable compression with default settings, or it can be an object with compression settings.
* `cache` - Setting this to true enables caching. This can also be set to an object specifying the settings/options for the cache (see [settings for weak-lru-cache](https://github.com/kriszyp/weak-lru-cache#weaklrucacheoptions-constructor)). For long-running synchronous operations, it is recommended that you set the `clearKeptInterval` (a value of 100 is a good choice).
* `useVersions` - Set this to true if you will be setting version numbers on the entries in the database. Note that you can not change this flag once a database has entries in it (or they won't be read correctly).
* `keyEncoding` - This indicates the encoding to use for the database keys, and can be `'uint32'` for unsigned 32-bit integers, `'binary'` for raw buffers/Uint8Arrays, and the default `'ordered-binary'` allows any JS primitive as a keys.
* `keyEncoder` - Provide a custom key encoder.
* `dupSort` - Enables duplicate entries for keys. Generally this is best used for building indices where the values represent keys to other databases, and it is recommended that you use `encoding: 'ordered-binary'` with this flag. You will usually want to retrieve the values for a key with `getValues`.
* `strictAsyncOrder` - Maintain strict ordering of execution of asynchronous transaction callbacks relative to asynchronous single operations.
The following additional option properties are only available when creating the main database environment (`open`):
* `path` - This is the file path to the database environment file you will use.
* `maxDbs` - The maximum number of databases to be able to open within one root database/environment ([there is some extra overhead if this is set very high](http://www.lmdb.tech/doc/group__mdb.html#gaa2fc2f1f37cb1115e733b62cab2fcdbc)). This defaults to 12.
* `maxReaders` - The maximum number of concurrent read transactions (readers) to be able to open ([more information](http://www.lmdb.tech/doc/group__mdb.html#gae687966c24b790630be2a41573fe40e2)).
* `overlappingSync` - This enables committing transactions where LMDB waits for a transaction to be fully flushed to disk _after_ the transaction has been committed and defaults to being enabled. This option is discussed in more detail below.
* `separateFlushed` - Resolve asynchronous operations when commits are finished and visible and include a separate promise for when a commit is flushed to disk, as a `flushed` property on the commit promise. Note that you can alternately use the `flushed` property on the database.
* `pageSize` - This defines the page size of the database. This is 4,096 by default. You may want to consider setting this to 8,192 for databases larger than available memory (and moreso if you have range queries) or 4,096 for databases that can mostly cache in memory. Note that this only effects the page size of new databases (does not affect existing databases).
* `eventTurnBatching` - This is enabled by default and will ensure that all asynchronous write operations performed in the same event turn will be batched together into the same transaction. Disabling this allows lmdb-js to commit a transaction at any time, and asynchronous operations will only be guaranteed to be in the same transaction if explicitly batched together (with `transaction`, `batch`, `ifVersion`). If this is disabled (set to `false`), you can control how many writes can occur before starting a transaction with `txnStartThreshold` (allow a transaction will still be started at the next event turn if the threshold is not met). Disabling event turn batching (and using lower `txnStartThreshold` values) can facilitate a faster response time to write operations. `txnStartThreshold` defaults to 5.
* `encryptionKey` - This enables encryption, and the provided value is the key that is used for encryption. This may be a buffer or string, but must be 32 bytes/characters long. This uses the Chacha8 cipher for fast and secure on-disk encryption of data.
* `commitDelay` - This is the amount of time to wait (in milliseconds) for batching write operations before committing the writes (in a transaction). This defaults to 0. A delay of 0 means more immediate commits with less latency (uses `setImmediate`), but a longer delay (which uses `setTimeout`) can be more efficient at collecting more writes into a single transaction and reducing I/O load. Note that NodeJS timers only have an effective resolution of about 10ms, so a `commitDelay` of 1ms will generally wait about 10ms.
#### LMDB Flags
In addition, the following options map to LMDB's env flags, <a href="http://www.lmdb.tech/doc/group__mdb.html">described here</a>. None of these need to be set, the defaults can always be used and are generally recommended, but these are available for various needs and performance optimizations:
* `noSync` - Does not explicitly flush data to disk at all. This can be useful for temporary databases where durability/integrity is not necessary, and can significantly improve write performance that is I/O bound. However, we discourage this flag for data that needs integrity and durability in storage, since it can result in data loss/corruption if the computer crashes.
* `noMemInit` - This provides a small performance boost for writes, by skipping zero'ing out malloc'ed data, but can leave application data in unused portions of the database. If you do not need to worry about unauthorized access to the database files themselves, this is recommended.
* `remapChunks` - This a flag to specify if dynamic memory mapping should be used. Enabling this generally makes read operations a little bit slower, but frees up more mapped memory, making it friendlier to other applications. This is enabled by default on 32-bit operating systems (which require this to go beyond 4GB database size) if `mapSize` is not specified, otherwise it is disabled by default.
* `mapSize` - This can be used to specify the initial amount of how much virtual memory address space (in bytes) to allocate for mapping to the database files. Setting a map size will typically disable `remapChunks` by default unless the size is larger than appropriate for the OS. Different OSes have different allocation limits.
* `useWritemap` - Use writemaps, this can improve performance by reducing malloc calls and file writes, but can increase risk of a stray pointer corrupting data, and may be slower on Windows. Combined with `noSync`, normal reads/writes/transactions involve virtually zero explicit I/O calls, only modifications to memory maps that the OS persists when convenient, which may be beneficial.
* `noMetaSync` - This isn't as dangerous as `noSync`, but doesn't improve performance much either.
* `noReadAhead` - This disables read-ahead caching. Turning it off may help random read performance when the DB is larger than RAM and system RAM is full. However, this is not supported by all OSes, including Windows, and should not be used in conjunction with page sizes larger than 4,096.
* `noSubdir` - Treat `path` as a filename instead of directory (this is the default if the path appears to end with an extension and has '.' in it)
* `readOnly` - Self-descriptive.
* `mapAsync` - Not recommended, commits are already performed in a separate thread (asyncronous to JS), and this prevents accurate notification of when flushes finish.
### Overlapping Sync Options
The `overlappingSync` option enables transactions to be committed such that LMDB waits for a transaction to be fully flushed to disk _after_ the transaction has been committed. This option is enabled by default on non-Windows operating systems. This means that the expensive/slow disk flushing operations do not occur during the writer lock, and allows disk flushing to occur in parallel with future transactions, providing potentially significant performance benefits. This uses a multi-step process of updating meta pointers to ensure database integrity even if a crash occurs.
When this is enabled, there are two events of potential interest: when the transaction is committed and the data is visible (to all other threads/processes), and when the transaction is flushed and durable. The write actions return a promise for when they are committed. The database includes a `flushed` property with a promise-like object that resolves when the last commit is fully flushed/synced to disk and is durable. Alternately, the `separateFlushed` option can be enabled and for write operations, the returned promise will still resolve when the transaction is committed and the promise will also have a `flushed` property that holds a second promise that is resolved when the OS reports that the transaction writes has been fully flushed to disk and are truly durable (at least as far the hardward/OS is capable of guaranteeing this). For example:
```js
let db = open('my-db', { overlappingSync: true });
let written = db.put(key, value);
await written; // wait for it to be committed
let v = db.get(key) // this value now be retrieved from the db
await db.flushed // wait for last commit to be fully flushed to disk
```
Enabling `overlappingSync` option is generally not recommended on Windows, as Window's disk flushing operation tends to have very poor performance characteristics on larger databases (whereas Windows tends to perform well with standard transactions). This option may be enabled by default in the future, for non-Windows platforms.
#### Serialization options
If you are using the default encoding of `'msgpack'`, the [msgpackr](https://github.com/kriszyp/msgpackr) package is used for serialization and deserialization. You can provide encoder options that are passed to msgpackr or cbor, as well, by including them in the `encoder` property object. For example, these options can be potentially useful:
* `structuredClone` - This enables the structured cloning extensions that will encode object/cyclic references and additional built-in types/classes.
* `useFloat32: 4` - Encode floating point numbers in 32-bit format when possible.
You can also use the CBOR format by specifying the encoding of `'cbor'` and installing the [cbor-x](https://github.com/kriszyp/cbor-x) package, which supports the same options.
## Custom Key Encoding
Custom key encoding can be useful for defining more efficient encodings of specific keys like UUIDs. Custom key encoding can be specified by providing a `keyEncoder` object with the following methods:
* `writeKey(key, targetBuffer, startPosition)` - This should write the provided key to the target buffer and returning the end position in the buffer.
* `readKey(sourceBuffer, start, end)` - This should read the key from the provided buffer, with provided start and end position in the buffer, returning the key.
## Events
The database instance is an <a href="https://nodejs.org/dist/latest-v11.x/docs/api/events.html#events_class_eventemitter">EventEmitter</a>, allowing application to listen to database events. There is just one event right now:
`beforecommit` - This event is fired before a transaction finishes/commits. The callback function can perform additional (asynchronous) writes (`put` and `remove`) and they will be included in the transaction about to be performed as the last operation(s) before the transaction commits (this can be useful for updating a global version stamp based on all previous writes, for example). Using this event forces `eventTurnBatching` to be enabled. This can be called multiples times in a transaction, but should always be called as the last operation of a transaction.
## LevelUp
If you have an existing application built on LevelUp, the lmdb-js is designed to make it easy to transition to this package, with most of the LevelUp API implemented and supported in lmdb-js. This includes the `put`, `del`, `batch`, `status`, `isOperation`, and `getMany` functions. One key difference in APIs is that LevelUp uses asynchronous callback based `get`s, but lmdb-js is so fast that it generally returns from `get` call before an an event can even be queued, consequently lmdb-js uses synchronous `get`s. However, there is a `levelup` export that can be used to generate a new database instance with LevelUp's style of API for `get` (although it still runs synchronously):
```js
let dbLevel = levelup(db)
dbLevel.get(id, (error, value) => {
})
// or
dbLevel.get(id).then(...)
```
## Benchmarks
Benchmarking on Node 14.9, with 3.4Ghz i7-4770 Windows, a get operation, using JS numbers as a key, retrieving data from the database (random access), and decoding the data into a structured object with 10 properties (using default [MessagePack encoding](https://github.com/kriszyp/msgpackr)), can be done in about half a microsecond, or about 1,900,000/sec on a single thread. This is almost three times as fast as a single native `JSON.parse` call with the same object without any DB interaction! LMDB scales effortlessly across multiple processes or threads; over 6,000,000 operations/sec on the same 4/8 core computer by running across multiple threads (or 18,000,000 operations/sec with raw binary data). By running writes on a separate transactional thread, writing is extremely fast as well. With encoding the same objects, full encoding and writes can be performed at about 500,000 puts/second or 1,700,000 puts/second on multiple threads.
#### Build Options
A few LMDB options are available at build time, and can be specified with options with `npm install` (which can be specified in your package.json install script):
`npm install --use_robust=true`: This will enable LMDB's MDB_USE_ROBUST option, which uses robust semaphores/mutexes so that if you are using multiple processes, and one process dies in the middle of transaction, the OS will cleanup the semaphore/mutex, aborting the transaction and allowing other processes to run without hanging. There is a slight performance overhead, but this is recommended if you will be using multiple processes.
On MacOS, there is a default limit of 10 robust locked semaphores, which imposes a limit on the number of open write transactions (if you have over 10 database environments with a write transaction). If you need more concurrent write transactions, you can increase your maximum undoable semaphore count by setting kern.sysv.semmnu on your local computer. Otherwise don't use the robust mutex option. You can also try to minimize overlapping transactions and/or reduce the number of database environments (and use more databases within each environment).
`npm install --use_data_v1=true`: This will build from an older version of LMDB that uses the legacy data format version 1 (the latest LMDB uses data format version 2). For portability of the data format, this may be preferable since many libraries still use older versions of LMDB. Since this is an older version of LMDB, some features may not be available, including encryption and remapping.
#### Turbo Mode
On Node V16+, lmdb-js will automatically enable V8's turbo fast-api calls (the `--turbo-fast-api-calls` V8 flag) to accelerate `lmdb-js`'s turbo-enabled functions. If you do not want this flag enabled, set the env variable `DISABLE_TURBO_CALLS=true` for your node process, or build from source with `--enable_fast_api_calls=false`.
## Alternate Database
The lmdb-js project is developed in conjunction with [lmdbx-js](https://github.com/kriszyp/lmdbx-js), which is based on [libmdbx](https://github.com/erthink/libmdbx), a fork of LMDB. Each of these have their own advantages:
* lmdb-js/LMDB is great for general usage, has very high performance, easy to set up with automated sizing, supports encryption, and works well across all platforms.
* lmdbx-js/libmdbx has more advanced management of free space and database sizing that can offer more performance optimizations for situations that require intense free space reclamation. However, in my experience lmdb-js has better performance than lmdbx-js, and the database format is not compatible with LMDB.
## Credits
This library is built on [LMDB](https://symas.com/lmdb/) and is built from and derived from the excellent [node-lmdb](https://github.com/Venemo/node-lmdb) package.
Many thanks to [Rod Vagg](https://www.npmjs.com/~rvagg) for donating the `lmdb` package name in the NPM registry.
## License
This library is licensed under the terms of the MIT license.
Also note that LMDB: Symas (the authors of LMDB) [offers commercial support of LMDB](https://symas.com/lightning-memory-mapped-database/).
This project has no funding needs. If you feel inclined to donate, donate to one of Kris's favorite charities like [Innovations in Poverty Action](https://www.poverty-action.org/) or any of [GiveWell](https://givewell.org)'s recommended charities.
## Related Projects
* This library is built on top of [node-lmdb](https://github.com/Venemo/node-lmdb)
* This library uses msgpackr for the default serialization of data [msgpackr](https://github.com/kriszyp/msgpackr)
* cobase is built on top of this library: [cobase](https://github.com/DoctorEvidence/cobase)
<a href="https://dev.doctorevidence.com/"><img src="./assets/powers-dre.png" width="203"/></a>
USB Library for Node.JS
===============================
[](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.
# debug
[](https://travis-ci.org/debug-js/debug) [](https://coveralls.io/github/debug-js/debug?branch=master) [](https://visionmedia-community-slackin.now.sh/) [](#backers)
[](#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 <[email protected]>
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.
# y18n
[![NPM version][npm-image]][npm-url]
[![js-standard-style][standard-image]][standard-url]
[](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>__`hello ${'world'}`</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
# duplexer3 [](https://travis-ci.org/floatdrop/duplexer3) [](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 ([[email protected]](mailto:[email protected]))
# fast-glob
> It's a very fast and efficient [glob][glob_definition] library for [Node.js][node_js].
This package provides methods for traversing the file system and returning pathnames that matched a defined set of a specified pattern according to the rules used by the Unix Bash shell with some simplifications, meanwhile results are returned in **arbitrary order**. Quick, simple, effective.
## Table of Contents
<details>
<summary><strong>Details</strong></summary>
* [Highlights](#highlights)
* [Donation](#donation)
* [Old and modern mode](#old-and-modern-mode)
* [Pattern syntax](#pattern-syntax)
* [Basic syntax](#basic-syntax)
* [Advanced syntax](#advanced-syntax)
* [Installation](#installation)
* [API](#api)
* [Asynchronous](#asynchronous)
* [Synchronous](#synchronous)
* [Stream](#stream)
* [patterns](#patterns)
* [[options]](#options)
* [Helpers](#helpers)
* [generateTasks](#generatetaskspatterns-options)
* [isDynamicPattern](#isdynamicpatternpattern-options)
* [escapePath](#escapepathpattern)
* [Options](#options-3)
* [Common](#common)
* [concurrency](#concurrency)
* [cwd](#cwd)
* [deep](#deep)
* [followSymbolicLinks](#followsymboliclinks)
* [fs](#fs)
* [ignore](#ignore)
* [suppressErrors](#suppresserrors)
* [throwErrorOnBrokenSymbolicLink](#throwerroronbrokensymboliclink)
* [Output control](#output-control)
* [absolute](#absolute)
* [markDirectories](#markdirectories)
* [objectMode](#objectmode)
* [onlyDirectories](#onlydirectories)
* [onlyFiles](#onlyfiles)
* [stats](#stats)
* [unique](#unique)
* [Matching control](#matching-control)
* [braceExpansion](#braceexpansion)
* [caseSensitiveMatch](#casesensitivematch)
* [dot](#dot)
* [extglob](#extglob)
* [globstar](#globstar)
* [baseNameMatch](#basenamematch)
* [FAQ](#faq)
* [What is a static or dynamic pattern?](#what-is-a-static-or-dynamic-pattern)
* [How to write patterns on Windows?](#how-to-write-patterns-on-windows)
* [Why are parentheses match wrong?](#why-are-parentheses-match-wrong)
* [How to exclude directory from reading?](#how-to-exclude-directory-from-reading)
* [How to use UNC path?](#how-to-use-unc-path)
* [Compatible with `node-glob`?](#compatible-with-node-glob)
* [Benchmarks](#benchmarks)
* [Server](#server)
* [Nettop](#nettop)
* [Changelog](#changelog)
* [License](#license)
</details>
## Highlights
* Fast. Probably the fastest.
* Supports multiple and negative patterns.
* Synchronous, Promise and Stream API.
* Object mode. Can return more than just strings.
* Error-tolerant.
## Donation
Do you like this project? Support it by donating, creating an issue or pull request.
[][paypal_mrmlnc]
## Old and modern mode
This package works in two modes, depending on the environment in which it is used.
* **Old mode**. Node.js below 10.10 or when the [`stats`](#stats) option is *enabled*.
* **Modern mode**. Node.js 10.10+ and the [`stats`](#stats) option is *disabled*.
The modern mode is faster. Learn more about the [internal mechanism][nodelib_fs_scandir_old_and_modern_modern].
## Pattern syntax
> :warning: Always use forward-slashes in glob expressions (patterns and [`ignore`](#ignore) option). Use backslashes for escaping characters.
There is more than one form of syntax: basic and advanced. Below is a brief overview of the supported features. Also pay attention to our [FAQ](#faq).
> :book: This package uses a [`micromatch`][micromatch] as a library for pattern matching.
### Basic syntax
* An asterisk (`*`) โ matches everything except slashes (path separators), hidden files (names starting with `.`).
* A double star or globstar (`**`) โ matches zero or more directories.
* Question mark (`?`) โ matches any single character except slashes (path separators).
* Sequence (`[seq]`) โ matches any character in sequence.
> :book: A few additional words about the [basic matching behavior][picomatch_matching_behavior].
Some examples:
* `src/**/*.js` โ matches all files in the `src` directory (any level of nesting) that have the `.js` extension.
* `src/*.??` โ matches all files in the `src` directory (only first level of nesting) that have a two-character extension.
* `file-[01].js` โ matches files: `file-0.js`, `file-1.js`.
### Advanced syntax
* [Escapes characters][micromatch_backslashes] (`\\`) โ matching special characters (`$^*+?()[]`) as literals.
* [POSIX character classes][picomatch_posix_brackets] (`[[:digit:]]`).
* [Extended globs][micromatch_extglobs] (`?(pattern-list)`).
* [Bash style brace expansions][micromatch_braces] (`{}`).
* [Regexp character classes][micromatch_regex_character_classes] (`[1-5]`).
* [Regex groups][regular_expressions_brackets] (`(a|b)`).
> :book: A few additional words about the [advanced matching behavior][micromatch_extended_globbing].
Some examples:
* `src/**/*.{css,scss}` โ matches all files in the `src` directory (any level of nesting) that have the `.css` or `.scss` extension.
* `file-[[:digit:]].js` โ matches files: `file-0.js`, `file-1.js`, โฆ, `file-9.js`.
* `file-{1..3}.js` โ matches files: `file-1.js`, `file-2.js`, `file-3.js`.
* `file-(1|2)` โ matches files: `file-1.js`, `file-2.js`.
## Installation
```console
npm install fast-glob
```
## API
### Asynchronous
```js
fg(patterns, [options])
```
Returns a `Promise` with an array of matching entries.
```js
const fg = require('fast-glob');
const entries = await fg(['.editorconfig', '**/index.js'], { dot: true });
// ['.editorconfig', 'services/index.js']
```
### Synchronous
```js
fg.sync(patterns, [options])
```
Returns an array of matching entries.
```js
const fg = require('fast-glob');
const entries = fg.sync(['.editorconfig', '**/index.js'], { dot: true });
// ['.editorconfig', 'services/index.js']
```
### Stream
```js
fg.stream(patterns, [options])
```
Returns a [`ReadableStream`][node_js_stream_readable_streams] when the `data` event will be emitted with matching entry.
```js
const fg = require('fast-glob');
const stream = fg.stream(['.editorconfig', '**/index.js'], { dot: true });
for await (const entry of stream) {
// .editorconfig
// services/index.js
}
```
#### patterns
* Required: `true`
* Type: `string | string[]`
Any correct pattern(s).
> :1234: [Pattern syntax](#pattern-syntax)
>
> :warning: This package does not respect the order of patterns. First, all the negative patterns are applied, and only then the positive patterns. If you want to get a certain order of records, use sorting or split calls.
#### [options]
* Required: `false`
* Type: [`Options`](#options-3)
See [Options](#options-3) section.
### Helpers
#### `generateTasks(patterns, [options])`
Returns the internal representation of patterns ([`Task`](./src/managers/tasks.ts) is a combining patterns by base directory).
```js
fg.generateTasks('*');
[{
base: '.', // Parent directory for all patterns inside this task
dynamic: true, // Dynamic or static patterns are in this task
patterns: ['*'],
positive: ['*'],
negative: []
}]
```
##### patterns
* Required: `true`
* Type: `string | string[]`
Any correct pattern(s).
##### [options]
* Required: `false`
* Type: [`Options`](#options-3)
See [Options](#options-3) section.
#### `isDynamicPattern(pattern, [options])`
Returns `true` if the passed pattern is a dynamic pattern.
> :1234: [What is a static or dynamic pattern?](#what-is-a-static-or-dynamic-pattern)
```js
fg.isDynamicPattern('*'); // true
fg.isDynamicPattern('abc'); // false
```
##### pattern
* Required: `true`
* Type: `string`
Any correct pattern.
##### [options]
* Required: `false`
* Type: [`Options`](#options-3)
See [Options](#options-3) section.
#### `escapePath(pattern)`
Returns a path with escaped special characters (`*?|(){}[]`, `!` at the beginning of line, `@+!` before the opening parenthesis).
```js
fg.escapePath('!abc'); // \\!abc
fg.escapePath('C:/Program Files (x86)'); // C:/Program Files \\(x86\\)
```
##### pattern
* Required: `true`
* Type: `string`
Any string, for example, a path to a file.
## Options
### Common options
#### concurrency
* Type: `number`
* Default: `os.cpus().length`
Specifies the maximum number of concurrent requests from a reader to read directories.
> :book: The higher the number, the higher the performance and load on the file system. If you want to read in quiet mode, set the value to a comfortable number or `1`.
#### cwd
* Type: `string`
* Default: `process.cwd()`
The current working directory in which to search.
#### deep
* Type: `number`
* Default: `Infinity`
Specifies the maximum depth of a read directory relative to the start directory.
For example, you have the following tree:
```js
dir/
โโโ one/ // 1
โโโ two/ // 2
โโโ file.js // 3
```
```js
// With base directory
fg.sync('dir/**', { onlyFiles: false, deep: 1 }); // ['dir/one']
fg.sync('dir/**', { onlyFiles: false, deep: 2 }); // ['dir/one', 'dir/one/two']
// With cwd option
fg.sync('**', { onlyFiles: false, cwd: 'dir', deep: 1 }); // ['one']
fg.sync('**', { onlyFiles: false, cwd: 'dir', deep: 2 }); // ['one', 'one/two']
```
> :book: If you specify a pattern with some base directory, this directory will not participate in the calculation of the depth of the found directories. Think of it as a [`cwd`](#cwd) option.
#### followSymbolicLinks
* Type: `boolean`
* Default: `true`
Indicates whether to traverse descendants of symbolic link directories when expanding `**` patterns.
> :book: Note that this option does not affect the base directory of the pattern. For example, if `./a` is a symlink to directory `./b` and you specified `['./a**', './b/**']` patterns, then directory `./a` will still be read.
> :book: If the [`stats`](#stats) option is specified, the information about the symbolic link (`fs.lstat`) will be replaced with information about the entry (`fs.stat`) behind it.
#### fs
* Type: `FileSystemAdapter`
* Default: `fs.*`
Custom implementation of methods for working with the file system.
```ts
export interface FileSystemAdapter {
lstat?: typeof fs.lstat;
stat?: typeof fs.stat;
lstatSync?: typeof fs.lstatSync;
statSync?: typeof fs.statSync;
readdir?: typeof fs.readdir;
readdirSync?: typeof fs.readdirSync;
}
```
#### ignore
* Type: `string[]`
* Default: `[]`
An array of glob patterns to exclude matches. This is an alternative way to use negative patterns.
```js
dir/
โโโ package-lock.json
โโโ package.json
```
```js
fg.sync(['*.json', '!package-lock.json']); // ['package.json']
fg.sync('*.json', { ignore: ['package-lock.json'] }); // ['package.json']
```
#### suppressErrors
* Type: `boolean`
* Default: `false`
By default this package suppress only `ENOENT` errors. Set to `true` to suppress any error.
> :book: Can be useful when the directory has entries with a special level of access.
#### throwErrorOnBrokenSymbolicLink
* Type: `boolean`
* Default: `false`
Throw an error when symbolic link is broken if `true` or safely return `lstat` call if `false`.
> :book: This option has no effect on errors when reading the symbolic link directory.
### Output control
#### absolute
* Type: `boolean`
* Default: `false`
Return the absolute path for entries.
```js
fg.sync('*.js', { absolute: false }); // ['index.js']
fg.sync('*.js', { absolute: true }); // ['/home/user/index.js']
```
> :book: This option is required if you want to use negative patterns with absolute path, for example, `!${__dirname}/*.js`.
#### markDirectories
* Type: `boolean`
* Default: `false`
Mark the directory path with the final slash.
```js
fg.sync('*', { onlyFiles: false, markDirectories: false }); // ['index.js', 'controllers']
fg.sync('*', { onlyFiles: false, markDirectories: true }); // ['index.js', 'controllers/']
```
#### objectMode
* Type: `boolean`
* Default: `false`
Returns objects (instead of strings) describing entries.
```js
fg.sync('*', { objectMode: false }); // ['src/index.js']
fg.sync('*', { objectMode: true }); // [{ name: 'index.js', path: 'src/index.js', dirent: <fs.Dirent> }]
```
The object has the following fields:
* name (`string`) โ the last part of the path (basename)
* path (`string`) โ full path relative to the pattern base directory
* dirent ([`fs.Dirent`][node_js_fs_class_fs_dirent]) โ instance of `fs.Dirent`
> :book: An object is an internal representation of entry, so getting it does not affect performance.
#### onlyDirectories
* Type: `boolean`
* Default: `false`
Return only directories.
```js
fg.sync('*', { onlyDirectories: false }); // ['index.js', 'src']
fg.sync('*', { onlyDirectories: true }); // ['src']
```
> :book: If `true`, the [`onlyFiles`](#onlyfiles) option is automatically `false`.
#### onlyFiles
* Type: `boolean`
* Default: `true`
Return only files.
```js
fg.sync('*', { onlyFiles: false }); // ['index.js', 'src']
fg.sync('*', { onlyFiles: true }); // ['index.js']
```
#### stats
* Type: `boolean`
* Default: `false`
Enables an [object mode](#objectmode) with an additional field:
* stats ([`fs.Stats`][node_js_fs_class_fs_stats]) โ instance of `fs.Stats`
```js
fg.sync('*', { stats: false }); // ['src/index.js']
fg.sync('*', { stats: true }); // [{ name: 'index.js', path: 'src/index.js', dirent: <fs.Dirent>, stats: <fs.Stats> }]
```
> :book: Returns `fs.stat` instead of `fs.lstat` for symbolic links when the [`followSymbolicLinks`](#followsymboliclinks) option is specified.
>
> :warning: Unlike [object mode](#objectmode) this mode requires additional calls to the file system. On average, this mode is slower at least twice. See [old and modern mode](#old-and-modern-mode) for more details.
#### unique
* Type: `boolean`
* Default: `true`
Ensures that the returned entries are unique.
```js
fg.sync(['*.json', 'package.json'], { unique: false }); // ['package.json', 'package.json']
fg.sync(['*.json', 'package.json'], { unique: true }); // ['package.json']
```
If `true` and similar entries are found, the result is the first found.
### Matching control
#### braceExpansion
* Type: `boolean`
* Default: `true`
Enables Bash-like brace expansion.
> :1234: [Syntax description][bash_hackers_syntax_expansion_brace] or more [detailed description][micromatch_braces].
```js
dir/
โโโ abd
โโโ acd
โโโ a{b,c}d
```
```js
fg.sync('a{b,c}d', { braceExpansion: false }); // ['a{b,c}d']
fg.sync('a{b,c}d', { braceExpansion: true }); // ['abd', 'acd']
```
#### caseSensitiveMatch
* Type: `boolean`
* Default: `true`
Enables a [case-sensitive][wikipedia_case_sensitivity] mode for matching files.
```js
dir/
โโโ file.txt
โโโ File.txt
```
```js
fg.sync('file.txt', { caseSensitiveMatch: false }); // ['file.txt', 'File.txt']
fg.sync('file.txt', { caseSensitiveMatch: true }); // ['file.txt']
```
#### dot
* Type: `boolean`
* Default: `false`
Allow patterns to match entries that begin with a period (`.`).
> :book: Note that an explicit dot in a portion of the pattern will always match dot files.
```js
dir/
โโโ .editorconfig
โโโ package.json
```
```js
fg.sync('*', { dot: false }); // ['package.json']
fg.sync('*', { dot: true }); // ['.editorconfig', 'package.json']
```
#### extglob
* Type: `boolean`
* Default: `true`
Enables Bash-like `extglob` functionality.
> :1234: [Syntax description][micromatch_extglobs].
```js
dir/
โโโ README.md
โโโ package.json
```
```js
fg.sync('*.+(json|md)', { extglob: false }); // []
fg.sync('*.+(json|md)', { extglob: true }); // ['README.md', 'package.json']
```
#### globstar
* Type: `boolean`
* Default: `true`
Enables recursively repeats a pattern containing `**`. If `false`, `**` behaves exactly like `*`.
```js
dir/
โโโ a
โโโ b
```
```js
fg.sync('**', { onlyFiles: false, globstar: false }); // ['a']
fg.sync('**', { onlyFiles: false, globstar: true }); // ['a', 'a/b']
```
#### baseNameMatch
* Type: `boolean`
* Default: `false`
If set to `true`, then patterns without slashes will be matched against the basename of the path if it contains slashes.
```js
dir/
โโโ one/
โโโ file.md
```
```js
fg.sync('*.md', { baseNameMatch: false }); // []
fg.sync('*.md', { baseNameMatch: true }); // ['one/file.md']
```
## FAQ
## What is a static or dynamic pattern?
All patterns can be divided into two types:
* **static**. A pattern is considered static if it can be used to get an entry on the file system without using matching mechanisms. For example, the `file.js` pattern is a static pattern because we can just verify that it exists on the file system.
* **dynamic**. A pattern is considered dynamic if it cannot be used directly to find occurrences without using a matching mechanisms. For example, the `*` pattern is a dynamic pattern because we cannot use this pattern directly.
A pattern is considered dynamic if it contains the following characters (`โฆ` โ any characters or their absence) or options:
* The [`caseSensitiveMatch`](#casesensitivematch) option is disabled
* `\\` (the escape character)
* `*`, `?`, `!` (at the beginning of line)
* `[โฆ]`
* `(โฆ|โฆ)`
* `@(โฆ)`, `!(โฆ)`, `*(โฆ)`, `?(โฆ)`, `+(โฆ)` (respects the [`extglob`](#extglob) option)
* `{โฆ,โฆ}`, `{โฆ..โฆ}` (respects the [`braceExpansion`](#braceexpansion) option)
## How to write patterns on Windows?
Always use forward-slashes in glob expressions (patterns and [`ignore`](#ignore) option). Use backslashes for escaping characters. With the [`cwd`](#cwd) option use a convenient format.
**Bad**
```ts
[
'directory\\*',
path.join(process.cwd(), '**')
]
```
**Good**
```ts
[
'directory/*',
path.join(process.cwd(), '**').replace(/\\/g, '/')
]
```
> :book: Use the [`normalize-path`][npm_normalize_path] or the [`unixify`][npm_unixify] package to convert Windows-style path to a Unix-style path.
Read more about [matching with backslashes][micromatch_backslashes].
## Why are parentheses match wrong?
```js
dir/
โโโ (special-*file).txt
```
```js
fg.sync(['(special-*file).txt']) // []
```
Refers to Bash. You need to escape special characters:
```js
fg.sync(['\\(special-*file\\).txt']) // ['(special-*file).txt']
```
Read more about [matching special characters as literals][picomatch_matching_special_characters_as_literals].
## How to exclude directory from reading?
You can use a negative pattern like this: `!**/node_modules` or `!**/node_modules/**`. Also you can use [`ignore`](#ignore) option. Just look at the example below.
```js
first/
โโโ file.md
โโโ second/
โโโ file.txt
```
If you don't want to read the `second` directory, you must write the following pattern: `!**/second` or `!**/second/**`.
```js
fg.sync(['**/*.md', '!**/second']); // ['first/file.md']
fg.sync(['**/*.md'], { ignore: ['**/second/**'] }); // ['first/file.md']
```
> :warning: When you write `!**/second/**/*` it means that the directory will be **read**, but all the entries will not be included in the results.
You have to understand that if you write the pattern to exclude directories, then the directory will not be read under any circumstances.
## How to use UNC path?
You cannot use [Uniform Naming Convention (UNC)][unc_path] paths as patterns (due to syntax), but you can use them as [`cwd`](#cwd) directory.
```ts
fg.sync('*', { cwd: '\\\\?\\C:\\Python27' /* or //?/C:/Python27 */ });
fg.sync('Python27/*', { cwd: '\\\\?\\C:\\' /* or //?/C:/ */ });
```
## Compatible with `node-glob`?
| node-glob | fast-glob |
| :----------: | :-------: |
| `cwd` | [`cwd`](#cwd) |
| `root` | โ |
| `dot` | [`dot`](#dot) |
| `nomount` | โ |
| `mark` | [`markDirectories`](#markdirectories) |
| `nosort` | โ |
| `nounique` | [`unique`](#unique) |
| `nobrace` | [`braceExpansion`](#braceexpansion) |
| `noglobstar` | [`globstar`](#globstar) |
| `noext` | [`extglob`](#extglob) |
| `nocase` | [`caseSensitiveMatch`](#casesensitivematch) |
| `matchBase` | [`baseNameMatch`](#basenamematch) |
| `nodir` | [`onlyFiles`](#onlyfiles) |
| `ignore` | [`ignore`](#ignore) |
| `follow` | [`followSymbolicLinks`](#followsymboliclinks) |
| `realpath` | โ |
| `absolute` | [`absolute`](#absolute) |
## Benchmarks
### Server
Link: [Vultr Bare Metal][vultr_pricing_baremetal]
* Processor: E3-1270v6 (8 CPU)
* RAM: 32GB
* Disk: SSD ([Intel DC S3520 SSDSC2BB240G7][intel_ssd])
You can see results [here][github_gist_benchmark_server] for latest release.
### Nettop
Link: [Zotac bi323][zotac_bi323]
* Processor: Intel N3150 (4 CPU)
* RAM: 8GB
* Disk: SSD ([Silicon Power SP060GBSS3S55S25][silicon_power_ssd])
You can see results [here][github_gist_benchmark_nettop] for latest release.
## Changelog
See the [Releases section of our GitHub project][github_releases] for changelog for each release version.
## License
This software is released under the terms of the MIT license.
[bash_hackers_syntax_expansion_brace]: https://wiki.bash-hackers.org/syntax/expansion/brace
[github_gist_benchmark_nettop]: https://gist.github.com/mrmlnc/f06246b197f53c356895fa35355a367c#file-fg-benchmark-nettop-product-txt
[github_gist_benchmark_server]: https://gist.github.com/mrmlnc/f06246b197f53c356895fa35355a367c#file-fg-benchmark-server-product-txt
[github_releases]: https://github.com/mrmlnc/fast-glob/releases
[glob_definition]: https://en.wikipedia.org/wiki/Glob_(programming)
[glob_linux_man]: http://man7.org/linux/man-pages/man3/glob.3.html
[intel_ssd]: https://ark.intel.com/content/www/us/en/ark/products/93012/intel-ssd-dc-s3520-series-240gb-2-5in-sata-6gb-s-3d1-mlc.html
[micromatch_backslashes]: https://github.com/micromatch/micromatch#backslashes
[micromatch_braces]: https://github.com/micromatch/braces
[micromatch_extended_globbing]: https://github.com/micromatch/micromatch#extended-globbing
[micromatch_extglobs]: https://github.com/micromatch/micromatch#extglobs
[micromatch_regex_character_classes]: https://github.com/micromatch/micromatch#regex-character-classes
[micromatch]: https://github.com/micromatch/micromatch
[node_js_fs_class_fs_dirent]: https://nodejs.org/api/fs.html#fs_class_fs_dirent
[node_js_fs_class_fs_stats]: https://nodejs.org/api/fs.html#fs_class_fs_stats
[node_js_stream_readable_streams]: https://nodejs.org/api/stream.html#stream_readable_streams
[node_js]: https://nodejs.org/en
[nodelib_fs_scandir_old_and_modern_modern]: https://github.com/nodelib/nodelib/blob/master/packages/fs/fs.scandir/README.md#old-and-modern-mode
[npm_normalize_path]: https://www.npmjs.com/package/normalize-path
[npm_unixify]: https://www.npmjs.com/package/unixify
[paypal_mrmlnc]:https://paypal.me/mrmlnc
[picomatch_matching_behavior]: https://github.com/micromatch/picomatch#matching-behavior-vs-bash
[picomatch_matching_special_characters_as_literals]: https://github.com/micromatch/picomatch#matching-special-characters-as-literals
[picomatch_posix_brackets]: https://github.com/micromatch/picomatch#posix-brackets
[regular_expressions_brackets]: https://www.regular-expressions.info/brackets.html
[silicon_power_ssd]: https://www.silicon-power.com/web/product-1
[unc_path]: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-dtyp/62e862f4-2a51-452e-8eeb-dc4ff5ee33cc
[vultr_pricing_baremetal]: https://www.vultr.com/pricing/baremetal
[wikipedia_case_sensitivity]: https://en.wikipedia.org/wiki/Case_sensitivity
[zotac_bi323]: https://www.zotac.com/ee/product/mini_pcs/zbox-bi323
agent-base
==========
### Turn a function into an [`http.Agent`][http.Agent] instance
[](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 <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[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
# `react-dom`
This package serves as the entry point to the DOM and server renderers for React. It is intended to be paired with the generic React package, which is shipped as `react` to npm.
## Installation
```sh
npm install react react-dom
```
## Usage
### In the browser
```js
import { createRoot } from 'react-dom/client';
function App() {
return <div>Hello World</div>;
}
const root = createRoot(document.getElementById('root'));
root.render(<App />);
```
### On the server
```js
import { renderToPipeableStream } from 'react-dom/server';
function App() {
return <div>Hello World</div>;
}
function handleRequest(res) {
// ... in your server handler ...
const stream = renderToPipeableStream(<App />, {
onShellReady() {
res.statusCode = 200;
res.setHeader('Content-type', 'text/html');
stream.pipe(res);
},
// ...
});
}
```
## API
### `react-dom`
See https://reactjs.org/docs/react-dom.html
### `react-dom/client`
See https://reactjs.org/docs/react-dom-client.html
### `react-dom/server`
See https://reactjs.org/docs/react-dom-server.html
# node-is-arrayish [](https://travis-ci.org/Qix-/node-is-arrayish) [](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).
# Tools
## clang-format
The clang-format checking tools is designed to check changed lines of code compared to given git-refs.
## Migration Script
The migration tool is designed to reduce repetitive work in the migration process. However, the script is not aiming to convert every thing for you. There are usually some small fixes and major reconstruction required.
### How To Use
To run the conversion script, first make sure you have the latest `node-addon-api` in your `node_modules` directory.
```
npm install node-addon-api
```
Then run the script passing your project directory
```
node ./node_modules/node-addon-api/tools/conversion.js ./
```
After finish, recompile and debug things that are missed by the script.
### Quick Fixes
Here is the list of things that can be fixed easily.
1. Change your methods' return value to void if it doesn't return value to JavaScript.
2. Use `.` to access attribute or to invoke member function in Napi::Object instead of `->`.
3. `Napi::New(env, value);` to `Napi::[Type]::New(env, value);
### Major Reconstructions
The implementation of `Napi::ObjectWrap` is significantly different from NAN's. `Napi::ObjectWrap` takes a pointer to the wrapped object and creates a reference to the wrapped object inside ObjectWrap constructor. `Napi::ObjectWrap` also associates wrapped object's instance methods to Javascript module instead of static methods like NAN.
So if you use Nan::ObjectWrap in your module, you will need to execute the following steps.
1. Convert your [ClassName]::New function to a constructor function that takes a `Napi::CallbackInfo`. Declare it as
```
[ClassName](const Napi::CallbackInfo& info);
```
and define it as
```
[ClassName]::[ClassName](const Napi::CallbackInfo& info) : Napi::ObjectWrap<[ClassName]>(info){
...
}
```
This way, the `Napi::ObjectWrap` constructor will be invoked after the object has been instantiated and `Napi::ObjectWrap` can use the `this` pointer to create a reference to the wrapped object.
2. Move your original constructor code into the new constructor. Delete your original constructor.
3. In your class initialization function, associate native methods in the following way.
```
Napi::FunctionReference constructor;
void [ClassName]::Init(Napi::Env env, Napi::Object exports, Napi::Object module) {
Napi::HandleScope scope(env);
Napi::Function ctor = DefineClass(env, "Canvas", {
InstanceMethod<&[ClassName]::Func1>("Func1"),
InstanceMethod<&[ClassName]::Func2>("Func2"),
InstanceAccessor<&[ClassName]::ValueGetter>("Value"),
StaticMethod<&[ClassName]::StaticMethod>("MethodName"),
InstanceValue("Value", Napi::[Type]::New(env, value)),
});
constructor = Napi::Persistent(ctor);
constructor .SuppressDestruct();
exports.Set("[ClassName]", ctor);
}
```
4. In function where you need to Unwrap the ObjectWrap in NAN like `[ClassName]* native = Nan::ObjectWrap::Unwrap<[ClassName]>(info.This());`, use `this` pointer directly as the unwrapped object as each ObjectWrap instance is associated with a unique object instance.
If you still find issues after following this guide, please leave us an issue describing your problem and we will try to resolve it.
# node-gyp-build
> Build tool and bindings loader for [`node-gyp`][node-gyp] that supports prebuilds.
```
npm install node-gyp-build
```
[](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
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.
[](https://travis-ci.org/isaacs/rimraf) [](https://david-dm.org/isaacs/rimraf) [](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).
# chunkd
> Get a chunk of an array based on the total number of chunks and current index
## Install
```sh
yarn add [--dev] chunkd
```
## Example
```js
const chunkd = require("chunkd")
chunkd([1, 2, 3, 4], 0, 3) // [1, 2]
chunkd([1, 2, 3, 4], 1, 3) // [3]
chunkd([1, 2, 3, 4], 2, 3) // [4]
```
# 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)`
util-deprecate
==============
### The Node.js `util.deprecate()` function with browser support
In Node.js, this module simply re-exports the `util.deprecate()` function.
In the web browser (i.e. via browserify), a browser-specific implementation
of the `util.deprecate()` function is used.
## API
A `deprecate()` function is the only thing exposed by this module.
``` javascript
// setup:
exports.foo = deprecate(foo, 'foo() is deprecated, use bar() instead');
// users see:
foo();
// foo() is deprecated, use bar() instead
foo();
foo();
```
## License
(The MIT License)
Copyright (c) 2014 Nathan Rajlich <[email protected]>
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
# is-number [](https://www.npmjs.com/package/is-number) [](https://npmjs.org/package/is-number) [](https://npmjs.org/package/is-number) [](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._
#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
# 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.
# Chokidar [](https://github.com/paulmillr/chokidar) [](https://github.com/paulmillr/chokidar)
> Minimal and efficient cross-platform file watching library
[](https://www.npmjs.com/package/chokidar)
## Why?
Node.js `fs.watch`:
* Doesn't report filenames on MacOS.
* Doesn't report events at all when using editors like Sublime on MacOS.
* Often reports events twice.
* Emits most changes as `rename`.
* Does not provide an easy way to recursively watch file trees.
* Does not support recursive watching on Linux.
Node.js `fs.watchFile`:
* Almost as bad at event handling.
* Also does not provide any recursive watching.
* Results in high CPU utilization.
Chokidar resolves these problems.
Initially made for **[Brunch](https://brunch.io/)** (an ultra-swift web app build tool), it is now used in
[Microsoft's Visual Studio Code](https://github.com/microsoft/vscode),
[gulp](https://github.com/gulpjs/gulp/),
[karma](https://karma-runner.github.io/),
[PM2](https://github.com/Unitech/PM2),
[browserify](http://browserify.org/),
[webpack](https://webpack.github.io/),
[BrowserSync](https://www.browsersync.io/),
and [many others](https://www.npmjs.com/browse/depended/chokidar).
It has proven itself in production environments.
Version 3 is out! Check out our blog post about it: [Chokidar 3: How to save 32TB of traffic every week](https://paulmillr.com/posts/chokidar-3-save-32tb-of-traffic/)
## How?
Chokidar does still rely on the Node.js core `fs` module, but when using
`fs.watch` and `fs.watchFile` for watching, it normalizes the events it
receives, often checking for truth by getting file stats and/or dir contents.
On MacOS, chokidar by default uses a native extension exposing the Darwin
`FSEvents` API. This provides very efficient recursive watching compared with
implementations like `kqueue` available on most \*nix platforms. Chokidar still
does have to do some work to normalize the events received that way as well.
On most other platforms, the `fs.watch`-based implementation is the default, which
avoids polling and keeps CPU usage down. Be advised that chokidar will initiate
watchers recursively for everything within scope of the paths that have been
specified, so be judicious about not wasting system resources by watching much
more than needed.
## Getting started
Install with npm:
```sh
npm install chokidar
```
Then `require` and use it in your code:
```javascript
const chokidar = require('chokidar');
// One-liner for current directory
chokidar.watch('.').on('all', (event, path) => {
console.log(event, path);
});
```
## API
```javascript
// Example of a more typical implementation structure
// Initialize watcher.
const watcher = chokidar.watch('file, dir, glob, or array', {
ignored: /(^|[\/\\])\../, // ignore dotfiles
persistent: true
});
// Something to use when events are received.
const log = console.log.bind(console);
// Add event listeners.
watcher
.on('add', path => log(`File ${path} has been added`))
.on('change', path => log(`File ${path} has been changed`))
.on('unlink', path => log(`File ${path} has been removed`));
// More possible events.
watcher
.on('addDir', path => log(`Directory ${path} has been added`))
.on('unlinkDir', path => log(`Directory ${path} has been removed`))
.on('error', error => log(`Watcher error: ${error}`))
.on('ready', () => log('Initial scan complete. Ready for changes'))
.on('raw', (event, path, details) => { // internal
log('Raw event info:', event, path, details);
});
// 'add', 'addDir' and 'change' events also receive stat() results as second
// argument when available: https://nodejs.org/api/fs.html#fs_class_fs_stats
watcher.on('change', (path, stats) => {
if (stats) console.log(`File ${path} changed size to ${stats.size}`);
});
// Watch new files.
watcher.add('new-file');
watcher.add(['new-file-2', 'new-file-3', '**/other-file*']);
// Get list of actual paths being watched on the filesystem
var watchedPaths = watcher.getWatched();
// Un-watch some files.
await watcher.unwatch('new-file*');
// Stop watching.
// The method is async!
watcher.close().then(() => console.log('closed'));
// Full list of options. See below for descriptions.
// Do not use this example!
chokidar.watch('file', {
persistent: true,
ignored: '*.txt',
ignoreInitial: false,
followSymlinks: true,
cwd: '.',
disableGlobbing: false,
usePolling: false,
interval: 100,
binaryInterval: 300,
alwaysStat: false,
depth: 99,
awaitWriteFinish: {
stabilityThreshold: 2000,
pollInterval: 100
},
ignorePermissionErrors: false,
atomic: true // or a custom 'atomicity delay', in milliseconds (default 100)
});
```
`chokidar.watch(paths, [options])`
* `paths` (string or array of strings). Paths to files, dirs to be watched
recursively, or glob patterns.
- Note: globs must not contain windows separators (`\`),
because that's how they work by the standard โ
you'll need to replace them with forward slashes (`/`).
- Note 2: for additional glob documentation, check out low-level
library: [picomatch](https://github.com/micromatch/picomatch).
* `options` (object) Options object as defined below:
#### Persistence
* `persistent` (default: `true`). Indicates whether the process
should continue to run as long as files are being watched. If set to
`false` when using `fsevents` to watch, no more events will be emitted
after `ready`, even if the process continues to run.
#### Path filtering
* `ignored` ([anymatch](https://github.com/es128/anymatch)-compatible definition)
Defines files/paths to be ignored. The whole relative or absolute path is
tested, not just filename. If a function with two arguments is provided, it
gets called twice per path - once with a single argument (the path), second
time with two arguments (the path and the
[`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats)
object of that path).
* `ignoreInitial` (default: `false`). If set to `false` then `add`/`addDir` events are also emitted for matching paths while
instantiating the watching as chokidar discovers these file paths (before the `ready` event).
* `followSymlinks` (default: `true`). When `false`, only the
symlinks themselves will be watched for changes instead of following
the link references and bubbling events through the link's path.
* `cwd` (no default). The base directory from which watch `paths` are to be
derived. Paths emitted with events will be relative to this.
* `disableGlobbing` (default: `false`). If set to `true` then the strings passed to `.watch()` and `.add()` are treated as
literal path names, even if they look like globs.
#### Performance
* `usePolling` (default: `false`).
Whether to use fs.watchFile (backed by polling), or fs.watch. If polling
leads to high CPU utilization, consider setting this to `false`. It is
typically necessary to **set this to `true` to successfully watch files over
a network**, and it may be necessary to successfully watch files in other
non-standard situations. Setting to `true` explicitly on MacOS overrides the
`useFsEvents` default. You may also set the CHOKIDAR_USEPOLLING env variable
to true (1) or false (0) in order to override this option.
* _Polling-specific settings_ (effective when `usePolling: true`)
* `interval` (default: `100`). Interval of file system polling, in milliseconds. You may also
set the CHOKIDAR_INTERVAL env variable to override this option.
* `binaryInterval` (default: `300`). Interval of file system
polling for binary files.
([see list of binary extensions](https://github.com/sindresorhus/binary-extensions/blob/master/binary-extensions.json))
* `useFsEvents` (default: `true` on MacOS). Whether to use the
`fsevents` watching interface if available. When set to `true` explicitly
and `fsevents` is available this supercedes the `usePolling` setting. When
set to `false` on MacOS, `usePolling: true` becomes the default.
* `alwaysStat` (default: `false`). If relying upon the
[`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats)
object that may get passed with `add`, `addDir`, and `change` events, set
this to `true` to ensure it is provided even in cases where it wasn't
already available from the underlying watch events.
* `depth` (default: `undefined`). If set, limits how many levels of
subdirectories will be traversed.
* `awaitWriteFinish` (default: `false`).
By default, the `add` event will fire when a file first appears on disk, before
the entire file has been written. Furthermore, in some cases some `change`
events will be emitted while the file is being written. In some cases,
especially when watching for large files there will be a need to wait for the
write operation to finish before responding to a file creation or modification.
Setting `awaitWriteFinish` to `true` (or a truthy value) will poll file size,
holding its `add` and `change` events until the size does not change for a
configurable amount of time. The appropriate duration setting is heavily
dependent on the OS and hardware. For accurate detection this parameter should
be relatively high, making file watching much less responsive.
Use with caution.
* *`options.awaitWriteFinish` can be set to an object in order to adjust
timing params:*
* `awaitWriteFinish.stabilityThreshold` (default: 2000). Amount of time in
milliseconds for a file size to remain constant before emitting its event.
* `awaitWriteFinish.pollInterval` (default: 100). File size polling interval, in milliseconds.
#### Errors
* `ignorePermissionErrors` (default: `false`). Indicates whether to watch files
that don't have read permissions if possible. If watching fails due to `EPERM`
or `EACCES` with this set to `true`, the errors will be suppressed silently.
* `atomic` (default: `true` if `useFsEvents` and `usePolling` are `false`).
Automatically filters out artifacts that occur when using editors that use
"atomic writes" instead of writing directly to the source file. If a file is
re-added within 100 ms of being deleted, Chokidar emits a `change` event
rather than `unlink` then `add`. If the default of 100 ms does not work well
for you, you can override it by setting `atomic` to a custom value, in
milliseconds.
### Methods & Events
`chokidar.watch()` produces an instance of `FSWatcher`. Methods of `FSWatcher`:
* `.add(path / paths)`: Add files, directories, or glob patterns for tracking.
Takes an array of strings or just one string.
* `.on(event, callback)`: Listen for an FS event.
Available events: `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `ready`,
`raw`, `error`.
Additionally `all` is available which gets emitted with the underlying event
name and path for every event other than `ready`, `raw`, and `error`. `raw` is internal, use it carefully.
* `.unwatch(path / paths)`: Stop watching files, directories, or glob patterns.
Takes an array of strings or just one string.
* `.close()`: **async** Removes all listeners from watched files. Asynchronous, returns Promise. Use with `await` to ensure bugs don't happen.
* `.getWatched()`: Returns an object representing all the paths on the file
system being watched by this `FSWatcher` instance. The object's keys are all the
directories (using absolute paths unless the `cwd` option was used), and the
values are arrays of the names of the items contained in each directory.
## CLI
If you need a CLI interface for your file watching, check out
[chokidar-cli](https://github.com/open-cli-tools/chokidar-cli), allowing you to
execute a command on each change, or get a stdio stream of change events.
## Install Troubleshooting
* `npm WARN optional dep failed, continuing [email protected]`
* This message is normal part of how `npm` handles optional dependencies and is
not indicative of a problem. Even if accompanied by other related error messages,
Chokidar should function properly.
* `TypeError: fsevents is not a constructor`
* Update chokidar by doing `rm -rf node_modules package-lock.json yarn.lock && npm install`, or update your dependency that uses chokidar.
* Chokidar is producing `ENOSP` error on Linux, like this:
* `bash: cannot set terminal process group (-1): Inappropriate ioctl for device bash: no job control in this shell`
`Error: watch /home/ ENOSPC`
* This means Chokidar ran out of file handles and you'll need to increase their count by executing the following command in Terminal:
`echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p`
## Changelog
For more detailed changelog, see [`full_changelog.md`](.github/full_changelog.md).
- **v3.5 (Jan 6, 2021):** Support for ARM Macs with Apple Silicon. Fixes for deleted symlinks.
- **v3.4 (Apr 26, 2020):** Support for directory-based symlinks. Fixes for macos file replacement.
- **v3.3 (Nov 2, 2019):** `FSWatcher#close()` method became async. That fixes IO race conditions related to close method.
- **v3.2 (Oct 1, 2019):** Improve Linux RAM usage by 50%. Race condition fixes. Windows glob fixes. Improve stability by using tight range of dependency versions.
- **v3.1 (Sep 16, 2019):** dotfiles are no longer filtered out by default. Use `ignored` option if needed. Improve initial Linux scan time by 50%.
- **v3 (Apr 30, 2019):** massive CPU & RAM consumption improvements; reduces deps / package size by a factor of 17x and bumps Node.js requirement to v8.16 and higher.
- **v2 (Dec 29, 2017):** Globs are now posix-style-only; without windows support. Tons of bugfixes.
- **v1 (Apr 7, 2015):** Glob support, symlink support, tons of bugfixes. Node 0.8+ is supported
- **v0.1 (Apr 20, 2012):** Initial release, extracted from [Brunch](https://github.com/brunch/brunch/blob/9847a065aea300da99bd0753f90354cde9de1261/src/helpers.coffee#L66)
## Also
Why was chokidar named this way? What's the meaning behind it?
>Chowkidar is a transliteration of a Hindi word meaning 'watchman, gatekeeper', เคเฅเคเฅเคฆเคพเคฐ. This ultimately comes from Sanskrit _ เคเคคเฅเคทเฅเค_ (crossway, quadrangle, consisting-of-four).
## License
MIT (c) Paul Miller (<https://paulmillr.com>), see [LICENSE](LICENSE) file.
# debug
[](https://travis-ci.org/visionmedia/debug) [](https://coveralls.io/github/visionmedia/debug?branch=master) [](https://visionmedia-community-slackin.now.sh/) [](#backers)
[](#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 <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# debug
[](https://travis-ci.org/visionmedia/debug) [](https://coveralls.io/github/visionmedia/debug?branch=master) [](https://visionmedia-community-slackin.now.sh/) [](#backers)
[](#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 <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# define-properties <sup>[![Version Badge][npm-version-svg]][package-url]</sup>
[![github actions][actions-image]][actions-url]
[![coverage][codecov-image]][codecov-url]
[![dependency status][deps-svg]][deps-url]
[![dev dependency status][dev-deps-svg]][dev-deps-url]
[![License][license-image]][license-url]
[![Downloads][downloads-image]][downloads-url]
[![npm badge][npm-badge-png]][package-url]
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]: https://versionbadg.es/ljharb/define-properties.svg
[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
[npm-badge-png]: https://nodei.co/npm/define-properties.png?downloads=true&stars=true
[license-image]: https://img.shields.io/npm/l/define-properties.svg
[license-url]: LICENSE
[downloads-image]: https://img.shields.io/npm/dm/define-properties.svg
[downloads-url]: https://npm-stat.com/charts.html?package=define-properties
[codecov-image]: https://codecov.io/gh/ljharb/define-properties/branch/main/graphs/badge.svg
[codecov-url]: https://app.codecov.io/gh/ljharb/define-properties/
[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/define-properties
[actions-url]: https://github.com/ljharb/define-properties/actions
# Ozone - Javascript Class Framework
[](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
[](https://www.npmjs.com/package/csso)
[](https://travis-ci.org/css/csso)
[](https://coveralls.io/github/css/csso?branch=master)
[](https://www.npmjs.com/package/csso)
[](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.
[](https://www.yandex.com/)
[](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.
tunnel-agent
============
HTTP proxy tunneling agent. Formerly part of mikeal/request, now a standalone module.
# fsevents [](https://nodei.co/npm/fsevents/)
Native access to MacOS FSEvents in [Node.js](https://nodejs.org/)
The FSEvents API in MacOS allows applications to register for notifications of
changes to a given directory tree. It is a very fast and lightweight alternative
to kqueue.
This is a low-level library. For a cross-platform file watching module that
uses fsevents, check out [Chokidar](https://github.com/paulmillr/chokidar).
## Installation
Supports only **Node.js v8.16 and higher**.
```sh
npm install fsevents
```
## Usage
```js
const fsevents = require('fsevents');
const stop = fsevents.watch(__dirname, (path, flags, id) => {
const info = fsevents.getInfo(path, flags, id);
}); // To start observation
stop(); // To end observation
```
The callback passed as the second parameter to `.watch` get's called whenever the operating system detects a
a change in the file system. It takes three arguments:
###### `fsevents.watch(dirname: string, (path: string, flags: number, id: string) => void): () => Promise<undefined>`
* `path: string` - the item in the filesystem that have been changed
* `flags: number` - a numeric value describing what the change was
* `id: string` - an unique-id identifying this specific event
Returns closer callback which when called returns a Promise resolving when the watcher process has been shut down.
###### `fsevents.getInfo(path: string, flags: number, id: string): FsEventInfo`
The `getInfo` function takes the `path`, `flags` and `id` arguments and converts those parameters into a structure
that is easier to digest to determine what the change was.
The `FsEventsInfo` has the following shape:
```js
/**
* @typedef {'created'|'modified'|'deleted'|'moved'|'root-changed'|'cloned'|'unknown'} FsEventsEvent
* @typedef {'file'|'directory'|'symlink'} FsEventsType
*/
{
"event": "created", // {FsEventsEvent}
"path": "file.txt",
"type": "file", // {FsEventsType}
"changes": {
"inode": true, // Had iNode Meta-Information changed
"finder": false, // Had Finder Meta-Data changed
"access": false, // Had access permissions changed
"xattrs": false // Had xAttributes changed
},
"flags": 0x100000000
}
```
## Changelog
- v2.3 supports Apple Silicon ARM CPUs
- v2 supports node 8.16+ and reduces package size massively
- v1.2.8 supports node 6+
- v1.2.7 supports node 4+
## Troubleshooting
- I'm getting `EBADPLATFORM` `Unsupported platform for fsevents` error.
- It's fine, nothing is broken. fsevents is macos-only. Other platforms are skipped. If you want to hide this warning, report a bug to NPM bugtracker asking them to hide ebadplatform warnings by default.
## License
The MIT License Copyright (C) 2010-2020 by Philipp Dunkel, Ben Noordhuis, Elan Shankar, Paul Miller โ see LICENSE file.
Visit our [GitHub page](https://github.com/fsevents/fsevents) and [NPM Page](https://npmjs.org/package/fsevents)
# readdirp [](https://github.com/paulmillr/readdirp)
Recursive version of [fs.readdir](https://nodejs.org/api/fs.html#fs_fs_readdir_path_options_callback). Exposes a **stream API** and a **promise API**.
```sh
npm install readdirp
```
```javascript
const readdirp = require('readdirp');
// Use streams to achieve small RAM & CPU footprint.
// 1) Streams example with for-await.
for await (const entry of readdirp('.')) {
const {path} = entry;
console.log(`${JSON.stringify({path})}`);
}
// 2) Streams example, non for-await.
// Print out all JS files along with their size within the current folder & subfolders.
readdirp('.', {fileFilter: '*.js', alwaysStat: true})
.on('data', (entry) => {
const {path, stats: {size}} = entry;
console.log(`${JSON.stringify({path, size})}`);
})
// Optionally call stream.destroy() in `warn()` in order to abort and cause 'close' to be emitted
.on('warn', error => console.error('non-fatal error', error))
.on('error', error => console.error('fatal error', error))
.on('end', () => console.log('done'));
// 3) Promise example. More RAM and CPU than streams / for-await.
const files = await readdirp.promise('.');
console.log(files.map(file => file.path));
// Other options.
readdirp('test', {
fileFilter: '*.js',
directoryFilter: ['!.git', '!*modules']
// directoryFilter: (di) => di.basename.length === 9
type: 'files_directories',
depth: 1
});
```
For more examples, check out `examples` directory.
## API
`const stream = readdirp(root[, options])` โ **Stream API**
- Reads given root recursively and returns a `stream` of [entry infos](#entryinfo)
- Optionally can be used like `for await (const entry of stream)` with node.js 10+ (`asyncIterator`).
- `on('data', (entry) => {})` [entry info](#entryinfo) for every file / dir.
- `on('warn', (error) => {})` non-fatal `Error` that prevents a file / dir from being processed. Example: inaccessible to the user.
- `on('error', (error) => {})` fatal `Error` which also ends the stream. Example: illegal options where passed.
- `on('end')` โ we are done. Called when all entries were found and no more will be emitted.
- `on('close')` โ stream is destroyed via `stream.destroy()`.
Could be useful if you want to manually abort even on a non fatal error.
At that point the stream is no longer `readable` and no more entries, warning or errors are emitted
- To learn more about streams, consult the very detailed [nodejs streams documentation](https://nodejs.org/api/stream.html)
or the [stream-handbook](https://github.com/substack/stream-handbook)
`const entries = await readdirp.promise(root[, options])` โ **Promise API**. Returns a list of [entry infos](#entryinfo).
First argument is awalys `root`, path in which to start reading and recursing into subdirectories.
### options
- `fileFilter: ["*.js"]`: filter to include or exclude files. A `Function`, Glob string or Array of glob strings.
- **Function**: a function that takes an entry info as a parameter and returns true to include or false to exclude the entry
- **Glob string**: a string (e.g., `*.js`) which is matched using [picomatch](https://github.com/micromatch/picomatch), so go there for more
information. Globstars (`**`) are not supported since specifying a recursive pattern for an already recursive function doesn't make sense. Negated globs (as explained in the minimatch documentation) are allowed, e.g., `!*.txt` matches everything but text files.
- **Array of glob strings**: either need to be all inclusive or all exclusive (negated) patterns otherwise an error is thrown.
`['*.json', '*.js']` includes all JavaScript and Json files.
`['!.git', '!node_modules']` includes all directories except the '.git' and 'node_modules'.
- Directories that do not pass a filter will not be recursed into.
- `directoryFilter: ['!.git']`: filter to include/exclude directories found and to recurse into. Directories that do not pass a filter will not be recursed into.
- `depth: 5`: depth at which to stop recursing even if more subdirectories are found
- `type: 'files'`: determines if data events on the stream should be emitted for `'files'` (default), `'directories'`, `'files_directories'`, or `'all'`. Setting to `'all'` will also include entries for other types of file descriptors like character devices, unix sockets and named pipes.
- `alwaysStat: false`: always return `stats` property for every file. Default is `false`, readdirp will return `Dirent` entries. Setting it to `true` can double readdir execution time - use it only when you need file `size`, `mtime` etc. Cannot be enabled on node <10.10.0.
- `lstat: false`: include symlink entries in the stream along with files. When `true`, `fs.lstat` would be used instead of `fs.stat`
### `EntryInfo`
Has the following properties:
- `path: 'assets/javascripts/react.js'`: path to the file/directory (relative to given root)
- `fullPath: '/Users/dev/projects/app/assets/javascripts/react.js'`: full path to the file/directory found
- `basename: 'react.js'`: name of the file/directory
- `dirent: fs.Dirent`: built-in [dir entry object](https://nodejs.org/api/fs.html#fs_class_fs_dirent) - only with `alwaysStat: false`
- `stats: fs.Stats`: built in [stat object](https://nodejs.org/api/fs.html#fs_class_fs_stats) - only with `alwaysStat: true`
## Changelog
- 3.5 (Oct 13, 2020) disallows recursive directory-based symlinks.
Before, it could have entered infinite loop.
- 3.4 (Mar 19, 2020) adds support for directory-based symlinks.
- 3.3 (Dec 6, 2019) stabilizes RAM consumption and enables perf management with `highWaterMark` option. Fixes race conditions related to `for-await` looping.
- 3.2 (Oct 14, 2019) improves performance by 250% and makes streams implementation more idiomatic.
- 3.1 (Jul 7, 2019) brings `bigint` support to `stat` output on Windows. This is backwards-incompatible for some cases. Be careful. It you use it incorrectly, you'll see "TypeError: Cannot mix BigInt and other types, use explicit conversions".
- 3.0 brings huge performance improvements and stream backpressure support.
- Upgrading 2.x to 3.x:
- Signature changed from `readdirp(options)` to `readdirp(root, options)`
- Replaced callback API with promise API.
- Renamed `entryType` option to `type`
- Renamed `entryType: 'both'` to `'files_directories'`
- `EntryInfo`
- Renamed `stat` to `stats`
- Emitted only when `alwaysStat: true`
- `dirent` is emitted instead of `stats` by default with `alwaysStat: false`
- Renamed `name` to `basename`
- Removed `parentDir` and `fullParentDir` properties
- Supported node.js versions:
- 3.x: node 8+
- 2.x: node 0.6+
## License
Copyright (c) 2012-2019 Thorsten Lorenz, Paul Miller (<https://paulmillr.com>)
MIT License, see [LICENSE](LICENSE) file.
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()
```

### 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.
# v8-compile-cache
[](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
# Glob
Match files using the patterns the shell uses, like stars and stuff.
[](https://travis-ci.org/isaacs/node-glob/) [](https://ci.appveyor.com/project/isaacs/node-glob) [](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.

## 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
```

# NEAR CLI (command line interface)
[](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.
# is-extglob [](https://www.npmjs.com/package/is-extglob) [](https://npmjs.org/package/is-extglob) [](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._
# Node-TimSort: Fast Sorting for Node.js
[](https://travis-ci.org/mziccard/node-timsort)
[](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`.
[](https://travis-ci.org/samccone/chrome-trace-event)
chrome-trace-event: A node library for creating trace event logs of program
execution according to [Google's Trace Event
format](https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU).
These logs can then be visualized with
[trace-viewer](https://github.com/google/trace-viewer) or chrome devtools to grok one's programs.
# Install
npm install chrome-trace-event
# Usage
```javascript
const Trace = require("chrome-trace-event").Tracer;
const trace = new Trace({
noStream: true
});
trace.pipe(fs.createWriteStream(outPath));
trace.flush();
```
# Links
* https://github.com/google/trace-viewer/wiki
* https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU
# License
MIT. See LICENSE.txt.
# 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.
# expand-template
> Expand placeholders in a template string.
[](https://www.npmjs.com/package/expand-template)

[](https://travis-ci.org/ralphtheninja/expand-template)
[](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).
# napi-build-utils
[](https://www.npmjs.com/package/napi-build-utils)

[](https://travis-ci.org/inspiredware/napi-build-utils)
[](http://standardjs.com/)
[](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.
# path-parse [](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)
# 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.
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.
# Source Map Support
[](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).
# Node.js ABI
[](https://travis-ci.org/lgeiger/node-abi) [](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
# emoji-regex [](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
| [](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.
# pbkdf2
[](https://www.npmjs.org/package/pbkdf2)
[](https://travis-ci.org/crypto-browserify/pbkdf2)
[](https://david-dm.org/crypto-browserify/pbkdf2#info=dependencies)
[](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).
# readable-stream
***Node.js core streams for userland*** [](https://travis-ci.com/nodejs/readable-stream)
[](https://nodei.co/npm/readable-stream/)
[](https://nodei.co/npm/readable-stream/)
[](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)) <[email protected]>
- Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242
* **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) <[email protected]>
* **Matteo Collina** ([@mcollina](https://github.com/mcollina)) <[email protected]>
- Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E
* **Irina Shestak** ([@lrlna](https://github.com/lrlna)) <[email protected]>
* **Yoshua Wyuts** ([@yoshuawuyts](https://github.com/yoshuawuyts)) <[email protected]>
[sauce]: https://saucelabs.com
# make-error
[](https://npmjs.org/package/make-error) [](https://travis-ci.org/JsCommunity/make-error) [](https://packagephobia.now.sh/result?p=make-error) [](https://github.com/JsCommunity/make-error/commits/master)
> Make your own error types!
## Features
- Compatible Node & browsers
- `instanceof` support
- `error.name` & `error.stack` support
- compatible with [CSP](https://en.wikipedia.org/wiki/Content_Security_Policy) (i.e. no `eval()`)
## Installation
### Node & [Browserify](http://browserify.org/)/[Webpack](https://webpack.js.org/)
Installation of the [npm package](https://npmjs.org/package/make-error):
```
> npm install --save make-error
```
Then require the package:
```javascript
var makeError = require("make-error");
```
### Browser
You can directly use the build provided at [unpkg.com](https://unpkg.com):
```html
<script src="https://unpkg.com/make-error@1/dist/make-error.js"></script>
```
## Usage
### Basic named error
```javascript
var CustomError = makeError("CustomError");
// Parameters are forwarded to the super class (here Error).
throw new CustomError("a message");
```
### Advanced error class
```javascript
function CustomError(customValue) {
CustomError.super.call(this, "custom error message");
this.customValue = customValue;
}
makeError(CustomError);
// Feel free to extend the prototype.
CustomError.prototype.myMethod = function CustomError$myMethod() {
console.log("CustomError.myMethod (%s, %s)", this.code, this.message);
};
//-----
try {
throw new CustomError(42);
} catch (error) {
error.myMethod();
}
```
### Specialized error
```javascript
var SpecializedError = makeError("SpecializedError", CustomError);
throw new SpecializedError(42);
```
### Inheritance
> Best for ES2015+.
```javascript
import { BaseError } from "make-error";
class CustomError extends BaseError {
constructor() {
super("custom error message");
}
}
```
## Related
- [make-error-cause](https://www.npmjs.com/package/make-error-cause): Make your own error types, with a cause!
## Contributions
Contributions are _very_ welcomed, either on the documentation or on
the code.
You may:
- report any [issue](https://github.com/JsCommunity/make-error/issues)
you've encountered;
- fork and create a pull request.
## License
ISC ยฉ [Julien Fontanet](http://julien.isonoe.net)
# postcss-value-parser
[](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:[email protected])
[![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
# cacheable-request
> Wrap native HTTP requests with RFC compliant cache support
[](https://travis-ci.org/lukechilds/cacheable-request)
[](https://coveralls.io/github/lukechilds/cacheable-request?branch=master)
[](https://www.npmjs.com/package/cacheable-request)
[](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
# AbortController polyfill for abortable fetch()
[](https://badge.fury.io/js/abortcontroller-polyfill)
Minimal stubs so that the AbortController DOM API for terminating ```fetch()``` requests can be used
in browsers that doesn't yet implement it. This "polyfill" doesn't actually close the connection
when the request is aborted, but it will call ```.catch()``` with ```err.name == 'AbortError'```
instead of ```.then()```.
```js
const controller = new AbortController();
const signal = controller.signal;
fetch('/some/url', {signal})
.then(res => res.json())
.then(data => {
// do something with "data"
}).catch(err => {
if (err.name == 'AbortError') {
return;
}
});
// controller.abort(); // can be called at any time
```
You can read about the [AbortController](https://dom.spec.whatwg.org/#aborting-ongoing-activities) API in the DOM specification.
# How to use
```shell
$ npm install --save abortcontroller-polyfill
```
If you're using webpack or similar, you then import it early in your client entrypoint .js file using
```js
import 'abortcontroller-polyfill/dist/polyfill-patch-fetch'
// or:
require('abortcontroller-polyfill/dist/polyfill-patch-fetch')
```
## Using it on browsers without fetch
If you need to support browsers where fetch is not available at all (for example
Internet Explorer 11), you first need to install a fetch polyfill and then
import the ```abortcontroller-polyfill``` afterwards.
The [unfetch](https://www.npmjs.com/package/unfetch) npm package offers a minimal ```fetch()```
implementation (though it does not offer for example a ```Request``` class). If you need a polyfill that
implements the full Fetch specification, use the
[whatwg-fetch](https://www.npmjs.com/package/whatwg-fetch) npm package instead. Typically you will
also need to load a polyfill that implements ES6 promises, for example
[promise-polyfill](https://www.npmjs.com/package/promise-polyfill), and of course you need to avoid
ES6 arrow functions and template literals.
Example projects showing abortable fetch setup so that it works even in Internet Explorer 11, using
both unfetch and GitHub fetch, is available
[here](https://github.com/mo/abortcontroller-polyfill-examples).
## Using it along with 'create-react-app'
create-react-app enforces the no-undef eslint rule at compile time so if your
version of eslint does not list ```AbortController``` etc as a known global for
the ```browser``` environment, then you might run into an compile error like:
```
'AbortController' is not defined no-undef
```
This can be worked around by (temporarily, details [here](https://github.com/mo/abortcontroller-polyfill/issues/10)) adding a declaration like:
```js
const AbortController = window.AbortController;
```
## Using the AbortController/AbortSignal without patching fetch
If you just want to polyfill AbortController/AbortSignal without patching fetch
you can use:
```js
import 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only'
```
# Using it on Node.js
You can either import it as a [ponyfill](https://ponyfill.com/) without modifying globals:
```js
const { AbortController, abortableFetch } = require('abortcontroller-polyfill/dist/cjs-ponyfill');
const { fetch } = abortableFetch(require('node-fetch'));
// or
// import { AbortController, abortableFetch } from 'abortcontroller-polyfill/dist/cjs-ponyfill';
// import _fetch from 'node-fetch';
// const { fetch } = abortableFetch(_fetch);
```
or if you're lazy
```js
global.fetch = require('node-fetch');
require('abortcontroller-polyfill/dist/polyfill-patch-fetch');
```
If you also need a ```Request``` class with support for aborting you can do:
```js
const { AbortController, abortableFetch } = require('abortcontroller-polyfill/dist/cjs-ponyfill');
const _nodeFetch = require('node-fetch');
const { fetch, Request } = abortableFetch({fetch: _nodeFetch, Request: _nodeFetch.Request});
const controller = new AbortController();
const signal = controller.signal;
controller.abort();
fetch(Request("http://api.github.com", {signal}))
.then(r => r.json())
.then(j => console.log(j))
.catch(err => {
if (err.name === 'AbortError') {
console.log('aborted');
}
})
```
See also Node.js examples [here](https://github.com/mo/abortcontroller-polyfill-examples/tree/master/node)
# Using it on Internet Explorer 11 (MSIE11)
The ```abortcontroller-polyfill``` works on Internet Explorer 11. However, to use it you must first
install separate polyfills for promises and for ```fetch()```. For the promise polyfill, you can
use the ```promise-polyfill``` package from npm, and for ```fetch()``` you can use either the ```whatwg-fetch``` npm package (complete fetch implementation) or the ```unfetch``` npm package (not a complete polyfill but it's only 500 bytes large and covers a lot of the basic use cases).
If you choose ```unfetch```, the imports should be done in this order for example:
```js
import 'promise-polyfill/src/polyfill';
import 'unfetch/polyfill';
import 'abortcontroller-polyfill';
```
See example code [here](https://github.com/mo/abortcontroller-polyfill-examples/tree/master/create-react-app-msie11).
# Using it on Internet Explorer 8 (MSIE8)
The ```abortcontroller-polyfill``` works on Internet Explorer 8. However, since ```github-fetch```
only supports IE 10+ you need to use the ```fetch-ie8``` npm package instead and also note that IE 8 only
implements ES 3 so you need to use the ```es5-shim``` package (or similar). Finally, just like with
IE 11 you also need to polyfill promises. One caveat is that CORS requests will not work out of the box on IE 8.
Here is a basic example of [abortable fetch running in IE 8](https://github.com/mo/abortcontroller-polyfill-examples/tree/master/plain-javascript-fetch-ie8).
# Contributors
* [Martin Olsson](https://github.com/mo)
* [Jimmy Wรคrting](https://github.com/jimmywarting)
* [silverwind](https://github.com/silverwind)
* [Rasmus Jacobsen](https://github.com/rmja)
* [Joรฃo Vieira](https://github.com/joaovieira)
* [Cyril Auburtin](https://github.com/caub)
* [Leonardo Apiwan](https://github.com/homer0)
* [Jake Champion](https://github.com/JakeChampion)
* [Sai Srinivasan](https://github.com/SairamSrinivasan)
* [Ambar Lee](https://github.com/ambar)
# License
MIT
# string_decoder
***Node-core v8.9.4 string_decoder for userland***
[](https://nodei.co/npm/string_decoder/)
[](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.
# convert-source-map [](http://travis-ci.org/thlorenz/convert-source-map)
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.
# 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
# <img src="docs_app/assets/Rx_Logo_S.png" alt="RxJS Logo" width="86" height="86"> RxJS: Reactive Extensions For JavaScript
[](https://circleci.com/gh/ReactiveX/rxjs/tree/6.x)
[](http://badge.fury.io/js/%40reactivex%2Frxjs)
[](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/
# 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)
# 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))
```
### 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 [](https://www.npmjs.com/package/electron-to-chromium) [](https://travis-ci.org/Kilian/electron-to-chromium) [](https://www.npmjs.com/package/electron-to-chromium) [](https://codecov.io/gh/Kilian/electron-to-chromium)[](https://app.fossa.io/projects/git%2Bgithub.com%2FKilian%2Felectron-to-chromium?ref=badge_shield)
This repository provides a mapping of Electron versions to the Chromium version that it uses.
This package is used in [Browserslist](https://github.com/ai/browserslist), so you can use e.g. `electron >= 1.4` in [Autoprefixer](https://github.com/postcss/autoprefixer), [Stylelint](https://github.com/stylelint/stylelint), [babel-preset-env](https://github.com/babel/babel-preset-env) and [eslint-plugin-compat](https://github.com/amilajack/eslint-plugin-compat).
**Supported by:**
<a href="https://m.do.co/c/bb22ea58e765">
<img src="https://opensource.nyc3.cdn.digitaloceanspaces.com/attribution/assets/SVG/DO_Logo_horizontal_blue.svg" width="201px">
</a>
## Install
Install using `npm install electron-to-chromium`.
## Usage
To include Electron-to-Chromium, require it:
```js
var e2c = require('electron-to-chromium');
```
### Properties
The Electron-to-Chromium object has 4 properties to use:
#### `versions`
An object of key-value pairs with a _major_ Electron version as the key, and the corresponding major Chromium version as the value.
```js
var versions = e2c.versions;
console.log(versions['1.4']);
// returns "53"
```
#### `fullVersions`
An object of key-value pairs with a Electron version as the key, and the corresponding full Chromium version as the value.
```js
var versions = e2c.fullVersions;
console.log(versions['1.4.11']);
// returns "53.0.2785.143"
```
#### `chromiumVersions`
An object of key-value pairs with a _major_ Chromium version as the key, and the corresponding major Electron version as the value.
```js
var versions = e2c.chromiumVersions;
console.log(versions['54']);
// returns "1.4"
```
#### `fullChromiumVersions`
An object of key-value pairs with a Chromium version as the key, and an array of the corresponding major Electron versions as the value.
```js
var versions = e2c.fullChromiumVersions;
console.log(versions['54.0.2840.101']);
// returns ["1.5.1", "1.5.0"]
```
### Functions
#### `electronToChromium(query)`
Arguments:
* Query: string or number, required. A major or full Electron version.
A function that returns the corresponding Chromium version for a given Electron function. Returns a string.
If you provide it with a major Electron version, it will return a major Chromium version:
```js
var chromeVersion = e2c.electronToChromium('1.4');
// chromeVersion is "53"
```
If you provide it with a full Electron version, it will return the full Chromium version.
```js
var chromeVersion = e2c.electronToChromium('1.4.11');
// chromeVersion is "53.0.2785.143"
```
If a query does not match a Chromium version, it will return `undefined`.
```js
var chromeVersion = e2c.electronToChromium('9000');
// chromeVersion is undefined
```
#### `chromiumToElectron(query)`
Arguments:
* Query: string or number, required. A major or full Chromium version.
Returns a string with the corresponding Electron version for a given Chromium query.
If you provide it with a major Chromium version, it will return a major Electron version:
```js
var electronVersion = e2c.chromiumToElectron('54');
// electronVersion is "1.4"
```
If you provide it with a full Chrome version, it will return an array of full Electron versions.
```js
var electronVersions = e2c.chromiumToElectron('56.0.2924.87');
// electronVersions is ["1.6.3", "1.6.2", "1.6.1", "1.6.0"]
```
If a query does not match an Electron version, it will return `undefined`.
```js
var electronVersion = e2c.chromiumToElectron('10');
// electronVersion is undefined
```
#### `electronToBrowserList(query)` **DEPRECATED**
Arguments:
* Query: string or number, required. A major Electron version.
_**Deprecated**: Browserlist already includes electron-to-chromium._
A function that returns a [Browserslist](https://github.com/ai/browserslist) query that matches the given major Electron version. Returns a string.
If you provide it with a major Electron version, it will return a Browserlist query string that matches the Chromium capabilities:
```js
var query = e2c.electronToBrowserList('1.4');
// query is "Chrome >= 53"
```
If a query does not match a Chromium version, it will return `undefined`.
```js
var query = e2c.electronToBrowserList('9000');
// query is undefined
```
### Importing just versions, fullVersions, chromiumVersions and fullChromiumVersions
All lists can be imported on their own, if file size is a concern.
#### `versions`
```js
var versions = require('electron-to-chromium/versions');
```
#### `fullVersions`
```js
var fullVersions = require('electron-to-chromium/full-versions');
```
#### `chromiumVersions`
```js
var chromiumVersions = require('electron-to-chromium/chromium-versions');
```
#### `fullChromiumVersions`
```js
var fullChromiumVersions = require('electron-to-chromium/full-chromium-versions');
```
## Updating
This package will be updated with each new Electron release.
To update the list, run `npm run build.js`. Requires internet access as it downloads from the canonical list of Electron versions.
To verify correct behaviour, run `npm test`.
## License
[](https://app.fossa.io/projects/git%2Bgithub.com%2FKilian%2Felectron-to-chromium?ref=badge_large)
# ci-parallel-vars
> Get CI environment variables for parallelizing builds
## Install
```
yarn add ci-parallel-vars
```
## Usage
```js
const ciParallelVars = require('ci-parallel-vars');
console.log(ciParallelVars); // { index: 3, total: 10 } || null
```
## Supports
> If you want to add support for another pair, please open a pull request and
> add them to `index.js` and to this list.
- [Knapsack] / [TravisCI] / [GitLab] - `CI_NODE_INDEX`/`CI_NODE_TOTAL`
- [CircleCI] - `CIRCLE_NODE_INDEX`/`CIRCLE_NODE_TOTAL`
- [Bitbucket Pipelines] - `BITBUCKET_PARALLEL_STEP`/`BITBUCKET_PARALLEL_STEP_COUNT`
- [Buildkite] - `BUILDKITE_PARALLEL_JOB`/`BUILDKITE_PARALLEL_JOB_COUNT`
- [Semaphore] - `SEMAPHORE_CURRENT_JOB`/`SEMAPHORE_JOB_COUNT`
One of these pairs must both be defined as numbers or `ci-parallel-vars` will
be `null`.
[Knapsack]: http://docs.knapsackpro.com/ruby/knapsack#info-about-env-variables
[TravisCI]: https://docs.travis-ci.com/user/speeding-up-the-build/#Parallelizing-RSpec%2C-Cucumber-and-Minitest-on-multiple-VMs
[GitLab]: https://docs.gitlab.com/ee/ci/yaml/#parallel
[CircleCI]: https://circleci.com/docs/1.0/parallel-manual-setup/#using-environment-variables
[Bitbucket Pipelines]: https://confluence.atlassian.com/bitbucket/parallel-steps-946606807.html
[Buildkite]: https://buildkite.com/docs/builds/parallel-builds
[Semaphore]: https://semaphoreci.com/docs/available-environment-variables.html#variables-exported-in-builds-and-deploys
## HIDAPI library for Windows, Linux, FreeBSD and macOS
| CI instance | Status |
|----------------------|--------|
| `macOS master` | [](https://travis-ci.org/libusb/hidapi) |
| `Windows master` | [](https://ci.appveyor.com/project/Youw/hidapi/branch/master) |
| `Linux/BSD, last build (branch/PR)` | [](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
```
# TypeScript
[](https://github.com/microsoft/TypeScript/actions?query=workflow%3ACI)
[](https://dev.azure.com/typescript/TypeScript/_build?definitionId=7)
[](https://www.npmjs.com/package/typescript)
[](https://www.npmjs.com/package/typescript)
[TypeScript](https://www.typescriptlang.org/) is a language for application-scale JavaScript. TypeScript adds optional types to JavaScript that support tools for large-scale JavaScript applications for any browser, for any host, on any OS. TypeScript compiles to readable, standards-based JavaScript. Try it out at the [playground](https://www.typescriptlang.org/play/), and stay up to date via [our blog](https://blogs.msdn.microsoft.com/typescript) and [Twitter account](https://twitter.com/typescript).
Find others who are using TypeScript at [our community page](https://www.typescriptlang.org/community/).
## Installing
For the latest stable version:
```bash
npm install -g typescript
```
For our nightly builds:
```bash
npm install -g typescript@next
```
## Contribute
There are many ways to [contribute](https://github.com/microsoft/TypeScript/blob/main/CONTRIBUTING.md) to TypeScript.
* [Submit bugs](https://github.com/microsoft/TypeScript/issues) and help us verify fixes as they are checked in.
* Review the [source code changes](https://github.com/microsoft/TypeScript/pulls).
* Engage with other TypeScript users and developers on [StackOverflow](https://stackoverflow.com/questions/tagged/typescript).
* Help each other in the [TypeScript Community Discord](https://discord.gg/typescript).
* Join the [#typescript](https://twitter.com/search?q=%23TypeScript) discussion on Twitter.
* [Contribute bug fixes](https://github.com/microsoft/TypeScript/blob/main/CONTRIBUTING.md).
* Read the archived language specification ([docx](https://github.com/microsoft/TypeScript/blob/main/doc/TypeScript%20Language%20Specification%20-%20ARCHIVED.docx?raw=true),
[pdf](https://github.com/microsoft/TypeScript/blob/main/doc/TypeScript%20Language%20Specification%20-%20ARCHIVED.pdf?raw=true), [md](https://github.com/microsoft/TypeScript/blob/main/doc/spec-ARCHIVED.md)).
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see
the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [[email protected]](mailto:[email protected])
with any additional questions or comments.
## Documentation
* [TypeScript in 5 minutes](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html)
* [Programming handbook](https://www.typescriptlang.org/docs/handbook/intro.html)
* [Homepage](https://www.typescriptlang.org/)
## Building
In order to build the TypeScript compiler, ensure that you have [Git](https://git-scm.com/downloads) and [Node.js](https://nodejs.org/) installed.
Clone a copy of the repo:
```bash
git clone https://github.com/microsoft/TypeScript.git
```
Change to the TypeScript directory:
```bash
cd TypeScript
```
Install [Gulp](https://gulpjs.com/) tools and dev dependencies:
```bash
npm install -g gulp
npm ci
```
Use one of the following to build and test:
```
gulp local # Build the compiler into built/local.
gulp clean # Delete the built compiler.
gulp LKG # Replace the last known good with the built one.
# Bootstrapping step to be executed when the built compiler reaches a stable state.
gulp tests # Build the test infrastructure using the built compiler.
gulp runtests # Run tests using the built compiler and test infrastructure.
# You can override the specific suite runner used or specify a test for this command.
# Use --tests=<testPath> for a specific test and/or --runner=<runnerName> for a specific suite.
# Valid runners include conformance, compiler, fourslash, project, user, and docker
# The user and docker runners are extended test suite runners - the user runner
# works on disk in the tests/cases/user directory, while the docker runner works in containers.
# You'll need to have the docker executable in your system path for the docker runner to work.
gulp runtests-parallel # Like runtests, but split across multiple threads. Uses a number of threads equal to the system
# core count by default. Use --workers=<number> to adjust this.
gulp baseline-accept # This replaces the baseline test results with the results obtained from gulp runtests.
gulp lint # Runs eslint on the TypeScript source.
gulp help # List the above commands.
```
## Usage
```bash
node built/local/tsc.js hello.ts
```
## Roadmap
For details on our planned features and future direction please refer to our [roadmap](https://github.com/microsoft/TypeScript/wiki/Roadmap).
### esutils [](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.
# 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 3.9.2 or later
npm install tslib
# TypeScript 3.8.4 or earlier
npm install tslib@^1
# TypeScript 2.3.2 or earlier
npm install [email protected]
```
## yarn
```sh
# TypeScript 3.9.2 or later
yarn add tslib
# TypeScript 3.8.4 or earlier
yarn add tslib@^1
# TypeScript 2.3.2 or earlier
yarn add [email protected]
```
## bower
```sh
# TypeScript 3.9.2 or later
bower install tslib
# TypeScript 3.8.4 or earlier
bower install tslib@^1
# TypeScript 2.3.2 or earlier
bower install [email protected]
```
## JSPM
```sh
# TypeScript 3.9.2 or later
jspm install tslib
# TypeScript 3.8.4 or earlier
jspm install tslib@^1
# TypeScript 2.3.2 or earlier
jspm install [email protected]
```
# Usage
Set the `importHelpers` compiler option on the command line:
```
tsc --importHelpers file.ts
```
or in your tsconfig.json:
```json
{
"compilerOptions": {
"importHelpers": true
}
}
```
#### For bower and JSPM users
You will need to add a `paths` mapping for `tslib`, e.g. For Bower users:
```json
{
"compilerOptions": {
"module": "amd",
"importHelpers": true,
"baseUrl": "./",
"paths": {
"tslib" : ["bower_components/tslib/tslib.d.ts"]
}
}
}
```
For JSPM users:
```json
{
"compilerOptions": {
"module": "system",
"importHelpers": true,
"baseUrl": "./",
"paths": {
"tslib" : ["jspm_packages/npm/[email protected]/tslib.d.ts"]
}
}
}
```
## Deployment
- Choose your new version number
- Set it in `package.json` and `bower.json`
- Create a tag: `git tag [version]`
- Push the tag: `git push --tags`
- Create a [release in GitHub](https://github.com/microsoft/tslib/releases)
- Run the [publish to npm](https://github.com/microsoft/tslib/actions?query=workflow%3A%22Publish+to+NPM%22) workflow
Done.
# 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/)
# 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)
```
# babel-plugin-polyfill-regenerator
## Install
Using npm:
```sh
npm install --save-dev babel-plugin-polyfill-regenerator
```
or using yarn:
```sh
yarn add babel-plugin-polyfill-regenerator --dev
```
## Usage
Add this plugin to your Babel configuration:
```json
{
"plugins": [["polyfill-regenerator", { "method": "usage-global" }]]
}
```
This package supports the `usage-pure`, `usage-global`, and `entry-global` methods.
When `entry-global` is used, it replaces imports to `regenerator-runtime`.
# unicode-canonical-property-names-ecmascript [](https://travis-ci.org/mathiasbynens/unicode-canonical-property-names-ecmascript) [](https://www.npmjs.com/package/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
```
## For maintainers
### How to publish a new release
1. On the `main` branch, bump the version number in `package.json`:
```sh
npm version patch -m 'Release v%s'
```
Instead of `patch`, use `minor` or `major` [as needed](https://semver.org/).
Note that this produces a Git commit + tag.
1. Push the release commit and tag:
```sh
git push && git push --tags
```
Our CI then automatically publishes the new release to npm.
## Author
| [](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.
# <img src="./logo.png" alt="bn.js" width="160" height="160" />
> BigNum in pure javascript
[](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
# regexpu-core [](https://github.com/mathiasbynens/regexpu-core/actions?query=workflow%3Arun-checks) [](https://www.npmjs.com/package/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:
#### Stable regular expression features
These options can be set to `false` or `'transform'`. When using `'transform'`, the corresponding features are compiled to older syntax that can run in older browsers. When using `false` (the default), they are not compiled and they can be relied upon to compile more modern features.
- `unicodeFlag` - The `u` flag, enabling support for Unicode code point escapes in the form `\u{...}`.
```js
rewritePattern('\\u{ab}', '', {
unicodeFlag: 'transform'
});
// โ '\\u{ab}'
rewritePattern('\\u{ab}', 'u', {
unicodeFlag: 'transform'
});
// โ '\\xAB'
```
- `dotAllFlag` - The [`s` (`dotAll`) flag](https://github.com/mathiasbynens/es-regexp-dotall-flag).
```js
rewritePattern('.', '', {
dotAllFlag: 'transform'
});
// โ '[\\0-\\t\\x0B\\f\\x0E-\\u2027\\u202A-\\uFFFF]'
rewritePattern('.', 's', {
dotAllFlag: 'transform'
});
// โ '[\\0-\\uFFFF]'
rewritePattern('.', 'su', {
dotAllFlag: 'transform'
});
// โ '(?:[\\0-\\uD7FF\\uE000-\\uFFFF]|[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF])'
```
- `unicodePropertyEscapes` - [Unicode property escapes](property-escapes.md).
By default they are compiled to Unicode code point escapes of the form `\u{...}`. If the `unicodeFlag` option is set to `'transform'` they often result in larger output, although there are cases (such as `\p{Lu}`) where it actually _decreases_ the output size.
```js
rewritePattern('\\p{Script_Extensions=Anatolian_Hieroglyphs}', 'u', {
unicodePropertyEscapes: 'transform'
});
// โ '[\\u{14400}-\\u{14646}]'
rewritePattern('\\p{Script_Extensions=Anatolian_Hieroglyphs}', 'u', {
unicodeFlag: 'transform',
unicodePropertyEscapes: 'transform'
});
// โ '(?:\\uD811[\\uDC00-\\uDE46])'
```
- `namedGroups` - [Named capture groups](https://github.com/tc39/proposal-regexp-named-groups).
```js
rewritePattern('(?<name>.)\\k<name>', '', {
namedGroups: 'transform'
});
// โ '(.)\1'
```
#### Experimental regular expression features
These options can be set to `false`, `'parse'` and `'transform'`. When using `'transform'`, the corresponding features are compiled to older syntax that can run in older browsers. When using `'parse'`, they are parsed and left as-is in the output pattern. When using `false` (the default), they result in a syntax error if used.
Once these features become stable (when the proposals are accepted as part of ECMAScript), they will be parsed by default and thus `'parse'` will behave like `false`.
- `unicodeSetsFlag` - [The `v` (`unicodeSets`) flag](https://github.com/tc39/proposal-regexp-set-notation)
```js
rewritePattern('[\\p{Emoji}&&\\p{ASCII}]', 'u', {
unicodeSetsFlag: 'transform'
});
// โ '[#\*0-9]'
```
By default, patterns with the `v` flag are transformed to patterns with the `u` flag. If you want to downlevel them more you can set the `unicodeFlag: 'transform'` option.
```js
rewritePattern('[^[a-h]&&[f-z]]', 'v', {
unicodeSetsFlag: 'transform'
});
// โ '[^f-h]' (to be used with /u)
```
```js
rewritePattern('[^[a-h]&&[f-z]]', 'v', {
unicodeSetsFlag: 'transform',
unicodeFlag: 'transform'
});
// โ '(?:(?![f-h])[\s\S])' (to be used without /u)
```
#### Miscellaneous options
- `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>', '', {
onNamedGroup(name, index) {
console.log(name, index);
// โ 'name', 1
}
});
```
### Caveats
- [Lookbehind assertions](https://github.com/tc39/proposal-regexp-lookbehind) cannot be transformed to older syntax.
- When using `namedGroups: 'transform'`, _regexpu-core_ only takes care of the _syntax_: you will still need a runtime wrapper around the regular expression to populate the `.groups` property of `RegExp.prototype.match()`'s result. If you are using _regexpu-core_ via Babel, it's handled automatically.
## For maintainers
### How to publish a new release
1. On the `main` branch, bump the version number in `package.json`:
```sh
npm version patch -m 'Release v%s'
```
Instead of `patch`, use `minor` or `major` [as needed](https://semver.org/).
Note that this produces a Git commit + tag.
1. Push the release commit and tag:
```sh
git push && git push --tags
```
Our CI then automatically publishes the new release to npm.
1. Once the release has been published to npm, update [`regexpu`](https://github.com/mathiasbynens/regexpu) to make use of it, and [cut a new release of `regexpu` as well](https://github.com/mathiasbynens/regexpu#how-to-publish-a-new-release).
## Author
| [](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.
# 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/
# node-gyp-build
> Build tool and bindings loader for [`node-gyp`][node-gyp] that supports prebuilds.
```
npm install node-gyp-build
```
[](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
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)
[](https://nodei.co/npm/node-addon-api/) [](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:









## **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
#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
# loose-envify
[](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
```
cipher-base
===
[](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.
near-blank-project
==================
This [React] app was initialized with [create-near-app]
Quick Start
===========
To run this project locally:
1. Prerequisites: Make sure you've installed [Node.js] โฅ 12
2. Install dependencies: `npm install`
3. Run the local development server: `npm run dev` (see `package.json` for a
full list of `scripts` you can run with `npm`)
Now you'll have a local development environment backed by the NEAR TestNet!
Go ahead and play with the app and the code. As you make code changes, the app will automatically reload.
Exploring The Code
==================
1. The "backend" code lives in the `/contract` folder. See the README there for
more info.
2. The frontend code lives in the `/frontend` folder. `/frontend/index.html` is a great
place to start exploring. Note that it loads in `/frontend/assets/js/index.js`, where you
can learn how the frontend connects to the NEAR blockchain.
3. Tests: there are different kinds of tests for the frontend and the smart
contract. See `contract/README` for info about how it's tested. The frontend
code gets tested with [jest]. You can run both of these at once with `npm
run test`.
Deploy
======
Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `npm run dev`, your smart contract gets deployed to the live NEAR TestNet with a throwaway account. When you're ready to make it permanent, here's how.
Step 0: Install near-cli (optional)
-------------------------------------
[near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `npm install`, but for best ergonomics you may want to install it globally:
npm install --global near-cli
Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx`
Ensure that it's installed with `near --version` (or `npx near --version`)
Step 1: Create an account for the contract
------------------------------------------
Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `near-blank-project.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `near-blank-project.your-name.testnet`:
1. Authorize NEAR CLI, following the commands it gives you:
near login
2. Create a subaccount (replace `YOUR-NAME` below with your actual account name):
near create-account near-blank-project.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet
Step 2: set contract name in code
---------------------------------
Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above.
const CONTRACT_NAME = process.env.CONTRACT_NAME || 'near-blank-project.YOUR-NAME.testnet'
Step 3: deploy!
---------------
One command:
npm run deploy
As you can see in `package.json`, this does two things:
1. builds & deploys smart contract to NEAR TestNet
2. builds & deploys frontend code to GitHub using [gh-pages]. This will only work if the project already has a repository set up on GitHub. Feel free to modify the `deploy` script in `package.json` to deploy elsewhere.
Troubleshooting
===============
On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details.
[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
# normalize-path [](https://www.npmjs.com/package/normalize-path) [](https://npmjs.org/package/normalize-path) [](https://npmjs.org/package/normalize-path) [](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._
# `react-shallow-renderer`
[](https://github.com/NMinhNguyen/react-shallow-renderer/blob/master/LICENSE)
[](https://www.npmjs.com/package/react-shallow-renderer)
[](https://circleci.com/gh/NMinhNguyen/react-shallow-renderer/tree/master)
When writing unit tests for React, shallow rendering can be helpful. Shallow rendering lets you render a component "one level deep" and assert facts about what its render method returns, without worrying about the behavior of child components, which are not instantiated or rendered. This does not require a DOM.
## Installation
```sh
# npm
npm install react-shallow-renderer --save-dev
# Yarn
yarn add react-shallow-renderer --dev
```
## Usage
For example, if you have the following component:
```jsx
function MyComponent() {
return (
<div>
<span className="heading">Title</span>
<Subcomponent foo="bar" />
</div>
);
}
```
Then you can assert:
```jsx
import ShallowRenderer from 'react-shallow-renderer';
// in your test:
const renderer = new ShallowRenderer();
renderer.render(<MyComponent />);
const result = renderer.getRenderOutput();
expect(result.type).toBe('div');
expect(result.props.children).toEqual([
<span className="heading">Title</span>,
<Subcomponent foo="bar" />,
]);
```
Shallow testing currently has some limitations, namely not supporting refs.
> Note:
>
> We also recommend checking out Enzyme's [Shallow Rendering API](https://airbnb.io/enzyme/docs/api/shallow.html). It provides a nicer higher-level API over the same functionality.
## Reference
### `shallowRenderer.render()`
You can think of the shallowRenderer as a "place" to render the component you're testing, and from which you can extract the component's output.
`shallowRenderer.render()` is similar to [`ReactDOM.render()`](https://reactjs.org/docs/react-dom.html#render) but it doesn't require DOM and only renders a single level deep. This means you can test components isolated from how their children are implemented.
### `shallowRenderer.getRenderOutput()`
After `shallowRenderer.render()` has been called, you can use `shallowRenderer.getRenderOutput()` to get the shallowly rendered output.
You can then begin to assert facts about the output.
# Polyfill for `Object.setPrototypeOf`
[](https://npmjs.org/package/setprototypeof)
[](https://npmjs.org/package/setprototypeof)
[](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'
```
Overview [](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).
# libusb
[](https://travis-ci.org/libusb/libusb)
[](https://ci.appveyor.com/project/LudovicRousseau/libusb)
[](https://scan.coverity.com/projects/libusb-libusb)
libusb is a library for USB device access from Linux, macOS,
Windows, OpenBSD/NetBSD and Haiku userspace.
It is written in C (Haiku backend in C++) and licensed under the GNU
Lesser General Public License version 2.1 or, at your option, any later
version (see [COPYING](COPYING)).
libusb is abstracted internally in such a way that it can hopefully
be ported to other operating systems. Please see the [PORTING](PORTING)
file for more information.
libusb homepage:
http://libusb.info/
Developers will wish to consult the API documentation:
http://api.libusb.info
Use the mailing list for questions, comments, etc:
http://mailing-list.libusb.info
- Hans de Goede <[email protected]>
- Xiaofan Chen <[email protected]>
- Ludovic Rousseau <[email protected]>
- Nathan Hjelm <[email protected]>
- Chris Dickens <[email protected]>
(Please use the mailing list rather than mailing developers directly)
# 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.
[](https://travis-ci.org/motdotla/dotenv-expand)
[](https://www.npmjs.com/package/dotenv-expand)
[](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.
# 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**
<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
[](https://www.npmjs.com/package/css-tree)
[](https://travis-ci.org/csstree/csstree)
[](https://coveralls.io/github/csstree/csstree?branch=master)
[](https://www.npmjs.com/package/css-tree)
[](https://twitter.com/csstree)
CSSTree is a tool set for CSS: [fast](https://github.com/postcss/benchmark) detailed parser (CSS โ AST), walker (AST traversal), generator (AST โ CSS) and lexer (validation and matching) based on specs and browser implementations. The main goal is to be efficient and W3C specs compliant, with focus on CSS analyzing and source-to-source transforming tasks.
> NOTE: The library isn't in final shape and needs further improvements (e.g. AST format and API are subjects to change in next major versions). However it's stable enough and used by projects 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.
## Documentation
- [AST format](docs/ast.md)
- [Parsing CSS โ AST](docs/parsing.md)
- [parse(source[, options])](docs/parsing.md#parsesource-options)
- [Serialization AST โ CSS](docs/generate.md)
- [generate(ast[, options])](docs/generate.md#generateast-options)
- [AST traversal](docs/traversal.md)
- [walk(ast, options)](docs/traversal.md#walkast-options)
- [find(ast, fn)](docs/traversal.md#findast-fn)
- [findLast(ast, fn)](docs/traversal.md#findlastast-fn)
- [findAll(ast, fn)](docs/traversal.md#findallast-fn)
- [Utils for AST](docs/utils.md)
- [property(name)](docs/utils.md#propertyname)
- [keyword(name)](docs/utils.md#keywordname)
- [clone(ast)](docs/utils.md#cloneast)
- [fromPlainObject(object)](docs/utils.md#fromplainobjectobject)
- [toPlainObject(ast)](docs/utils.md#toplainobjectast)
- [Value Definition Syntax](docs/definition-syntax.md)
- [parse(source)](docs/definition-syntax.md#parsesource)
- [walk(node, options, context)](docs/definition-syntax.md#walknode-options-context)
- [generate(node, options)](docs/definition-syntax.md#generatenode-options)
- [AST format](docs/definition-syntax.md#ast-format)
## 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' });
// match 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

## License
MIT
[](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)
# `react`
React is a JavaScript library for creating user interfaces.
The `react` package contains only the functionality necessary to define React components. It is typically used together with a React renderer like `react-dom` for the web, or `react-native` for the native environments.
**Note:** by default, React will be in development mode. The development version includes extra warnings about common mistakes, whereas the production version includes extra performance optimizations and strips all error messages. Don't forget to use the [production build](https://reactjs.org/docs/optimizing-performance.html#use-the-production-build) when deploying your application.
## Usage
```js
import { useState } from 'react';
import { createRoot } from 'react-dom/client';
function Counter() {
const [count, setCount] = useState(0);
return (
<>
<h1>{count}</h1>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</>
);
}
const root = createRoot(document.getElementById('root'));
root.render(<App />);
```
## Documentation
See https://reactjs.org/
## API
See https://reactjs.org/docs/react-api.html
# braces [](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [](https://www.npmjs.com/package/braces) [](https://npmjs.org/package/braces) [](https://npmjs.org/package/braces) [](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._
# `create-require`
[![npm version][npm-version-src]][npm-version-href]
[![npm downloads][npm-downloads-src]][npm-downloads-href]
[![Github Actions][github-actions-src]][github-actions-href]
[![Codecov][codecov-src]][codecov-href]
Polyfill for Node.js [`module.createRequire`](https://nodejs.org/api/modules.html#modules_module_createrequire_filename) (<= v12.2.0)
## Install
```sh
yarn add create-require
npm install create-require
```
## Usage
```ts
function createRequire (filename: string | URL): NodeRequire;
```
```js
const createRequire = require('create-require')
const myRequire = createRequire('path/to/test.js')
const myModule = myRequire('./test-sibling-module')
```
## License
[MIT](./LICENSE)
<!-- Badges -->
[npm-version-src]: https://img.shields.io/npm/v/create-require?style=flat-square
[npm-version-href]: https://npmjs.com/package/create-require
[npm-downloads-src]: https://img.shields.io/npm/dm/create-require?style=flat-square
[npm-downloads-href]: https://npmjs.com/package/create-require
[github-actions-src]: https://img.shields.io/github/workflow/status/nuxt-contrib/create-require/test/master?style=flat-square
[github-actions-href]: https://github.com/nuxt-contrib/create-require/actions?query=workflow%3Atest
[codecov-src]: https://img.shields.io/codecov/c/gh/nuxt-contrib/create-require/master?style=flat-square
[codecov-href]: https://codecov.io/gh/nuxt-contrib/create-require
<table><thead>
<tr>
<th>Linux</th>
<th>OS X</th>
<th>Windows</th>
<th>Coverage</th>
<th>Downloads</th>
</tr>
</thead><tbody><tr>
<td colspan="2" align="center">
<a href="https://travis-ci.org/kaelzhang/node-ignore">
<img
src="https://travis-ci.org/kaelzhang/node-ignore.svg?branch=master"
alt="Build Status" /></a>
</td>
<td align="center">
<a href="https://ci.appveyor.com/project/kaelzhang/node-ignore">
<img
src="https://ci.appveyor.com/api/projects/status/github/kaelzhang/node-ignore?branch=master&svg=true"
alt="Windows Build Status" /></a>
</td>
<td align="center">
<a href="https://codecov.io/gh/kaelzhang/node-ignore">
<img
src="https://codecov.io/gh/kaelzhang/node-ignore/branch/master/graph/badge.svg"
alt="Coverage Status" /></a>
</td>
<td align="center">
<a href="https://www.npmjs.org/package/ignore">
<img
src="http://img.shields.io/npm/dm/ignore.svg"
alt="npm module downloads per month" /></a>
</td>
</tr></tbody></table>
# ignore
`ignore` is a manager, filter and parser which implemented in pure JavaScript according to the [.gitignore spec 2.22.1](http://git-scm.com/docs/gitignore).
`ignore` is used by eslint, gitbook and [many others](https://www.npmjs.com/browse/depended/ignore).
Pay **ATTENTION** that [`minimatch`](https://www.npmjs.org/package/minimatch) (which used by `fstream-ignore`) does not follow the gitignore spec.
To filter filenames according to a .gitignore file, I recommend this npm package, `ignore`.
To parse an `.npmignore` file, you should use `minimatch`, because an `.npmignore` file is parsed by npm using `minimatch` and it does not work in the .gitignore way.
### Tested on
`ignore` is fully tested, and has more than **five hundreds** of unit tests.
- Linux + Node: `0.8` - `7.x`
- Windows + Node: `0.10` - `7.x`, node < `0.10` is not tested due to the lack of support of appveyor.
Actually, `ignore` does not rely on any versions of node specially.
Since `4.0.0`, ignore will no longer support `node < 6` by default, to use in node < 6, `require('ignore/legacy')`. For details, see [CHANGELOG](https://github.com/kaelzhang/node-ignore/blob/master/CHANGELOG.md).
## Table Of Main Contents
- [Usage](#usage)
- [`Pathname` Conventions](#pathname-conventions)
- See Also:
- [`glob-gitignore`](https://www.npmjs.com/package/glob-gitignore) matches files using patterns and filters them according to gitignore rules.
- [Upgrade Guide](#upgrade-guide)
## Install
```sh
npm i ignore
```
## Usage
```js
import ignore from 'ignore'
const ig = ignore().add(['.abc/*', '!.abc/d/'])
```
### Filter the given paths
```js
const paths = [
'.abc/a.js', // filtered out
'.abc/d/e.js' // included
]
ig.filter(paths) // ['.abc/d/e.js']
ig.ignores('.abc/a.js') // true
```
### As the filter function
```js
paths.filter(ig.createFilter()); // ['.abc/d/e.js']
```
### Win32 paths will be handled
```js
ig.filter(['.abc\\a.js', '.abc\\d\\e.js'])
// if the code above runs on windows, the result will be
// ['.abc\\d\\e.js']
```
## Why another ignore?
- `ignore` is a standalone module, and is much simpler so that it could easy work with other programs, unlike [isaacs](https://npmjs.org/~isaacs)'s [fstream-ignore](https://npmjs.org/package/fstream-ignore) which must work with the modules of the fstream family.
- `ignore` only contains utility methods to filter paths according to the specified ignore rules, so
- `ignore` never try to find out ignore rules by traversing directories or fetching from git configurations.
- `ignore` don't cares about sub-modules of git projects.
- Exactly according to [gitignore man page](http://git-scm.com/docs/gitignore), fixes some known matching issues of fstream-ignore, such as:
- '`/*.js`' should only match '`a.js`', but not '`abc/a.js`'.
- '`**/foo`' should match '`foo`' anywhere.
- Prevent re-including a file if a parent directory of that file is excluded.
- Handle trailing whitespaces:
- `'a '`(one space) should not match `'a '`(two spaces).
- `'a \ '` matches `'a '`
- All test cases are verified with the result of `git check-ignore`.
# Methods
## .add(pattern: string | Ignore): this
## .add(patterns: Array<string | Ignore>): this
- **pattern** `String | Ignore` An ignore pattern string, or the `Ignore` instance
- **patterns** `Array<String | Ignore>` Array of ignore patterns.
Adds a rule or several rules to the current manager.
Returns `this`
Notice that a line starting with `'#'`(hash) is treated as a comment. Put a backslash (`'\'`) in front of the first hash for patterns that begin with a hash, if you want to ignore a file with a hash at the beginning of the filename.
```js
ignore().add('#abc').ignores('#abc') // false
ignore().add('\#abc').ignores('#abc') // true
```
`pattern` could either be a line of ignore pattern or a string of multiple ignore patterns, which means we could just `ignore().add()` the content of a ignore file:
```js
ignore()
.add(fs.readFileSync(filenameOfGitignore).toString())
.filter(filenames)
```
`pattern` could also be an `ignore` instance, so that we could easily inherit the rules of another `Ignore` instance.
## <strike>.addIgnoreFile(path)</strike>
REMOVED in `3.x` for now.
To upgrade `[email protected]` up to `3.x`, use
```js
import fs from 'fs'
if (fs.existsSync(filename)) {
ignore().add(fs.readFileSync(filename).toString())
}
```
instead.
## .filter(paths: Array<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, an error will be thrown
ig.ignores('./abc')
// WRONG, for it will never happen, and an error will be thrown
// If the gitignore rule locates at the root directory,
// `'/abc'` should be changed to `'abc'`.
// ```
// path.relative('/', '/abc') -> 'abc'
// ```
ig.ignores('/abc')
// WRONG, that it is an absolute path on Windows, an error will be thrown
ig.ignores('C:\\abc')
// Right
ig.ignores('abc')
// Right
ig.ignores(path.join('./abc')) // path.join('./abc') -> 'abc'
```
In other words, each `Pathname` here should be a relative path to the directory of the gitignore rules.
Suppose the dir structure is:
```
/path/to/your/repo
|-- a
| |-- a.js
|
|-- .b
|
|-- .c
|-- .DS_store
```
Then the `paths` might be like this:
```js
[
'a/a.js'
'.b',
'.c/.DS_store'
]
```
#### 2. filenames and dirnames
`node-ignore` does NO `fs.stat` during path matching, so for the example below:
```js
// First, we add a ignore pattern to ignore a directory
ig.add('config/')
// `ig` does NOT know if 'config', in the real world,
// is a normal file, directory or something.
ig.ignores('config')
// `ig` treats `config` as a file, so it returns `false`
ig.ignores('config/')
// returns `true`
```
Specially for people who develop some library based on `node-ignore`, it is important to understand that.
Usually, you could use [`glob`](http://npmjs.org/package/glob) with `option.mark = true` to fetch the structure of the current directory:
```js
import glob from 'glob'
glob('**', {
// Adds a / character to directory matches.
mark: true
}, (err, files) => {
if (err) {
return console.error(err)
}
let filtered = ignore().add(patterns).filter(files)
console.log(filtered)
})
```
## .ignores(pathname: Pathname): boolean
> new in 3.2.0
Returns `Boolean` whether `pathname` should be ignored.
```js
ig.ignores('.abc/a.js') // true
```
## .createFilter()
Creates a filter function which could filter an array of paths with `Array.prototype.filter`.
Returns `function(path)` the filter function.
## .test(pathname: Pathname) since 5.0.0
Returns `TestResult`
```ts
interface TestResult {
ignored: boolean
// true if the `pathname` is finally unignored by some negative pattern
unignored: boolean
}
```
- `{ignored: true, unignored: false}`: the `pathname` is ignored
- `{ignored: false, unignored: true}`: the `pathname` is unignored
- `{ignored: false, unignored: false}`: the `pathname` is never matched by any ignore rules.
## static `ignore.isPathValid(pathname): boolean` since 5.0.0
Check whether the `pathname` is an valid `path.relative()`d path according to the [convention](#1-pathname-should-be-a-pathrelatived-pathname).
This method is **NOT** used to check if an ignore pattern is valid.
```js
ignore.isPathValid('./foo') // false
```
## ignore(options)
### `options.ignorecase` since 4.0.0
Similar as the `core.ignorecase` option of [git-config](https://git-scm.com/docs/git-config), `node-ignore` will be case insensitive if `options.ignorecase` is set to `true` (the default value), otherwise case sensitive.
```js
const ig = ignore({
ignorecase: false
})
ig.add('*.png')
ig.ignores('*.PNG') // false
```
### `options.ignoreCase?: boolean` since 5.2.0
Which is alternative to `options.ignoreCase`
### `options.allowRelativePaths?: boolean` since 5.2.0
This option brings backward compatibility with projects which based on `[email protected]`. If `options.allowRelativePaths` is `true`, `ignore` will not check whether the given path to be tested is [`path.relative()`d](#pathname-conventions).
However, passing a relative path, such as `'./foo'` or `'../foo'`, to test if it is ignored or not is not a good practise, which might lead to unexpected behavior
```js
ignore({
allowRelativePaths: true
}).ignores('../foo/bar.js') // And it will not throw
```
****
# Upgrade Guide
## Upgrade 4.x -> 5.x
Since `5.0.0`, if an invalid `Pathname` passed into `ig.ignores()`, an error will be thrown, unless `options.allowRelative = true` is passed to the `Ignore` factory.
While `ignore < 5.0.0` did not make sure what the return value was, as well as
```ts
.ignores(pathname: Pathname): boolean
.filter(pathnames: Array<Pathname>): Array<Pathname>
.createFilter(): (pathname: Pathname) => boolean
.test(pathname: Pathname): {ignored: boolean, unignored: boolean}
```
See the convention [here](#1-pathname-should-be-a-pathrelatived-pathname) for details.
If there are invalid pathnames, the conversion and filtration should be done by users.
```js
import {isPathValid} from 'ignore' // introduced in 5.0.0
const paths = [
// invalid
//////////////////
'',
false,
'../foo',
'.',
//////////////////
// valid
'foo'
]
.filter(isValidPath)
ig.filter(paths)
```
## Upgrade 3.x -> 4.x
Since `4.0.0`, `ignore` will no longer support node < 6, to use `ignore` in node < 6:
```js
var ignore = require('ignore/legacy')
```
## Upgrade 2.x -> 3.x
- All `options` of 2.x are unnecessary and removed, so just remove them.
- `ignore()` instance is no longer an [`EventEmitter`](nodejs.org/api/events.html), and all events are unnecessary and removed.
- `.addIgnoreFile()` is removed, see the [.addIgnoreFile](#addignorefilepath) section for details.
****
# Collaborators
- [@whitecolor](https://github.com/whitecolor) *Alex*
- [@SamyPesse](https://github.com/SamyPesse) *Samy Pessรฉ*
- [@azproduction](https://github.com/azproduction) *Mikhail Davydov*
- [@TrySound](https://github.com/TrySound) *Bogdan Chadkin*
- [@JanMattner](https://github.com/JanMattner) *Jan Mattner*
- [@ntwb](https://github.com/ntwb) *Stephen Edgar*
- [@kasperisager](https://github.com/kasperisager) *Kasper Isager*
- [@sandersn](https://github.com/sandersn) *Nathan Shively-Sanders*
# fastq
![ci][ci-url]
[![npm version][npm-badge]][npm-url]
[![Dependency Status][david-badge]][david-url]
Fast, in memory work queue.
Benchmarks (1 million tasks):
* setImmediate: 812ms
* fastq: 854ms
* async.queue: 1298ms
* neoAsync.queue: 1249ms
Obtained on node 12.16.1, on a dedicated server.
If you need zero-overhead series function call, check out
[fastseries](http://npm.im/fastseries). For zero-overhead parallel
function call, check out [fastparallel](http://npm.im/fastparallel).
[](https://github.com/feross/standard)
* <a href="#install">Installation</a>
* <a href="#usage">Usage</a>
* <a href="#api">API</a>
* <a href="#license">Licence & copyright</a>
## Install
`npm i fastq --save`
## Usage (callback API)
```js
'use strict'
const queue = require('fastq')(worker, 1)
queue.push(42, function (err, result) {
if (err) { throw err }
console.log('the result is', result)
})
function worker (arg, cb) {
cb(null, arg * 2)
}
```
## Usage (promise API)
```js
const queue = require('fastq').promise(worker, 1)
async function worker (arg) {
return arg * 2
}
async function run () {
const result = await queue.push(42)
console.log('the result is', result)
}
run()
```
### Setting "this"
```js
'use strict'
const that = { hello: 'world' }
const queue = require('fastq')(that, worker, 1)
queue.push(42, function (err, result) {
if (err) { throw err }
console.log(this)
console.log('the result is', result)
})
function worker (arg, cb) {
console.log(this)
cb(null, arg * 2)
}
```
### Using with TypeScript (callback API)
```ts
'use strict'
import * as fastq from "fastq";
import type { queue, done } from "fastq";
type Task = {
id: number
}
const q: queue<Task> = fastq(worker, 1)
q.push({ id: 42})
function worker (arg: Task, cb: done) {
console.log(arg.id)
cb(null)
}
```
### Using with TypeScript (promise API)
```ts
'use strict'
import * as fastq from "fastq";
import type { queueAsPromised } from "fastq";
type Task = {
id: number
}
const q: queueAsPromised<Task> = fastq.promise(asyncWorker, 1)
q.push({ id: 42}).catch((err) => console.error(err))
async function asyncWorker (arg: Task): Promise<void> {
// No need for a try-catch block, fastq handles errors automatically
console.log(arg.id)
}
```
## API
* <a href="#fastqueue"><code>fastqueue()</code></a>
* <a href="#push"><code>queue#<b>push()</b></code></a>
* <a href="#unshift"><code>queue#<b>unshift()</b></code></a>
* <a href="#pause"><code>queue#<b>pause()</b></code></a>
* <a href="#resume"><code>queue#<b>resume()</b></code></a>
* <a href="#idle"><code>queue#<b>idle()</b></code></a>
* <a href="#length"><code>queue#<b>length()</b></code></a>
* <a href="#getQueue"><code>queue#<b>getQueue()</b></code></a>
* <a href="#kill"><code>queue#<b>kill()</b></code></a>
* <a href="#killAndDrain"><code>queue#<b>killAndDrain()</b></code></a>
* <a href="#error"><code>queue#<b>error()</b></code></a>
* <a href="#concurrency"><code>queue#<b>concurrency</b></code></a>
* <a href="#drain"><code>queue#<b>drain</b></code></a>
* <a href="#empty"><code>queue#<b>empty</b></code></a>
* <a href="#saturated"><code>queue#<b>saturated</b></code></a>
* <a href="#promise"><code>fastqueue.promise()</code></a>
-------------------------------------------------------
<a name="fastqueue"></a>
### fastqueue([that], worker, concurrency)
Creates a new queue.
Arguments:
* `that`, optional context of the `worker` function.
* `worker`, worker function, it would be called with `that` as `this`,
if that is specified.
* `concurrency`, number of concurrent tasks that could be executed in
parallel.
-------------------------------------------------------
<a name="push"></a>
### queue.push(task, done)
Add a task at the end of the queue. `done(err, result)` will be called
when the task was processed.
-------------------------------------------------------
<a name="unshift"></a>
### queue.unshift(task, done)
Add a task at the beginning of the queue. `done(err, result)` will be called
when the task was processed.
-------------------------------------------------------
<a name="pause"></a>
### queue.pause()
Pause the processing of tasks. Currently worked tasks are not
stopped.
-------------------------------------------------------
<a name="resume"></a>
### queue.resume()
Resume the processing of tasks.
-------------------------------------------------------
<a name="idle"></a>
### queue.idle()
Returns `false` if there are tasks being processed or waiting to be processed.
`true` otherwise.
-------------------------------------------------------
<a name="length"></a>
### queue.length()
Returns the number of tasks waiting to be processed (in the queue).
-------------------------------------------------------
<a name="getQueue"></a>
### queue.getQueue()
Returns all the tasks be processed (in the queue). Returns empty array when there are no tasks
-------------------------------------------------------
<a name="kill"></a>
### queue.kill()
Removes all tasks waiting to be processed, and reset `drain` to an empty
function.
-------------------------------------------------------
<a name="killAndDrain"></a>
### queue.killAndDrain()
Same than `kill` but the `drain` function will be called before reset to empty.
-------------------------------------------------------
<a name="error"></a>
### queue.error(handler)
Set a global error handler. `handler(err, task)` will be called
when any of the tasks return an error.
-------------------------------------------------------
<a name="concurrency"></a>
### queue.concurrency
Property that returns the number of concurrent tasks that could be executed in
parallel. It can be altered at runtime.
-------------------------------------------------------
<a name="drain"></a>
### queue.drain
Function that will be called when the last
item from the queue has been processed by a worker.
It can be altered at runtime.
-------------------------------------------------------
<a name="empty"></a>
### queue.empty
Function that will be called when the last
item from the queue has been assigned to a worker.
It can be altered at runtime.
-------------------------------------------------------
<a name="saturated"></a>
### queue.saturated
Function that will be called when the queue hits the concurrency
limit.
It can be altered at runtime.
-------------------------------------------------------
<a name="promise"></a>
### fastqueue.promise([that], worker(arg), concurrency)
Creates a new queue with `Promise` apis. It also offers all the methods
and properties of the object returned by [`fastqueue`](#fastqueue) with the modified
[`push`](#pushPromise) and [`unshift`](#unshiftPromise) methods.
Node v10+ is required to use the promisified version.
Arguments:
* `that`, optional context of the `worker` function.
* `worker`, worker function, it would be called with `that` as `this`,
if that is specified. It MUST return a `Promise`.
* `concurrency`, number of concurrent tasks that could be executed in
parallel.
<a name="pushPromise"></a>
#### queue.push(task) => Promise
Add a task at the end of the queue. The returned `Promise` will be fulfilled (rejected)
when the task is completed successfully (unsuccessfully).
This promise could be ignored as it will not lead to a `'unhandledRejection'`.
<a name="unshiftPromise"></a>
#### queue.unshift(task) => Promise
Add a task at the beginning of the queue. The returned `Promise` will be fulfilled (rejected)
when the task is completed successfully (unsuccessfully).
This promise could be ignored as it will not lead to a `'unhandledRejection'`.
<a name="drained"></a>
#### queue.drained() => Promise
Wait for the queue to be drained. The returned `Promise` will be resolved when all tasks in the queue have been processed by a worker.
This promise could be ignored as it will not lead to a `'unhandledRejection'`.
## License
ISC
[ci-url]: https://github.com/mcollina/fastq/workflows/ci/badge.svg
[npm-badge]: https://badge.fury.io/js/fastq.svg
[npm-url]: https://badge.fury.io/js/fastq
[david-badge]: https://david-dm.org/mcollina/fastq.svg
[david-url]: https://david-dm.org/mcollina/fastq
# 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"]
});
```
# 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.
# JSON5 โ JSON for Humans
[][Build Status]
[][Coverage
Status]
The JSON5 Data Interchange Format (JSON5) is a superset of [JSON] that aims to
alleviate some of the limitations of JSON by expanding its syntax to include
some productions from [ECMAScript 5.1].
This JavaScript library is the official reference implementation for JSON5
parsing and serialization libraries.
[Build Status]: https://travis-ci.com/json5/json5
[Coverage Status]: https://coveralls.io/github/json5/json5
[JSON]: https://tools.ietf.org/html/rfc7159
[ECMAScript 5.1]: https://www.ecma-international.org/ecma-262/5.1/
## Summary of Features
The following ECMAScript 5.1 features, which are not supported in JSON, have
been extended to JSON5.
### Objects
- Object keys may be an ECMAScript 5.1 _[IdentifierName]_.
- Objects may have a single trailing comma.
### Arrays
- Arrays may have a single trailing comma.
### Strings
- Strings may be single quoted.
- Strings may span multiple lines by escaping new line characters.
- Strings may include character escapes.
### Numbers
- Numbers may be hexadecimal.
- Numbers may have a leading or trailing decimal point.
- Numbers may be [IEEE 754] positive infinity, negative infinity, and NaN.
- Numbers may begin with an explicit plus sign.
### Comments
- Single and multi-line comments are allowed.
### White Space
- Additional white space characters are allowed.
[IdentifierName]: https://www.ecma-international.org/ecma-262/5.1/#sec-7.6
[IEEE 754]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
## Short Example
```js
{
// comments
unquoted: 'and you can quote me on that',
singleQuotes: 'I can use "double quotes" here',
lineBreaks: "Look, Mom! \
No \\n's!",
hexadecimal: 0xdecaf,
leadingDecimalPoint: .8675309, andTrailing: 8675309.,
positiveSign: +1,
trailingComma: 'in objects', andIn: ['arrays',],
"backwardsCompatible": "with JSON",
}
```
## Specification
For a detailed explanation of the JSON5 format, please read the [official
specification](https://json5.github.io/json5-spec/).
## Installation
### Node.js
```sh
npm install json5
```
```js
const JSON5 = require('json5')
```
### Browsers
```html
<script src="https://unpkg.com/json5@^2.0.0/dist/index.min.js"></script>
```
This will create a global `JSON5` variable.
## API
The JSON5 API is compatible with the [JSON API].
[JSON API]:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON
### JSON5.parse()
Parses a JSON5 string, constructing the JavaScript value or object described by
the string. An optional reviver function can be provided to perform a
transformation on the resulting object before it is returned.
#### Syntax
JSON5.parse(text[, reviver])
#### Parameters
- `text`: The string to parse as JSON5.
- `reviver`: If a function, this prescribes how the value originally produced by
parsing is transformed, before being returned.
#### Return value
The object corresponding to the given JSON5 text.
### JSON5.stringify()
Converts a JavaScript value to a JSON5 string, optionally replacing values if a
replacer function is specified, or optionally including only the specified
properties if a replacer array is specified.
#### Syntax
JSON5.stringify(value[, replacer[, space]])
JSON5.stringify(value[, options])
#### Parameters
- `value`: The value to convert to a JSON5 string.
- `replacer`: A function that alters the behavior of the stringification
process, or an array of String and Number objects that serve as a whitelist
for selecting/filtering the properties of the value object to be included in
the JSON5 string. If this value is null or not provided, all properties of the
object are included in the resulting JSON5 string.
- `space`: A String or Number object that's used to insert white space into the
output JSON5 string for readability purposes. If this is a Number, it
indicates the number of space characters to use as white space; this number is
capped at 10 (if it is greater, the value is just 10). Values less than 1
indicate that no space should be used. If this is a String, the string (or the
first 10 characters of the string, if it's longer than that) is used as white
space. If this parameter is not provided (or is null), no white space is used.
If white space is used, trailing commas will be used in objects and arrays.
- `options`: An object with the following properties:
- `replacer`: Same as the `replacer` parameter.
- `space`: Same as the `space` parameter.
- `quote`: A String representing the quote character to use when serializing
strings.
#### Return value
A JSON5 string representing the value.
### Node.js `require()` JSON5 files
When using Node.js, you can `require()` JSON5 files by adding the following
statement.
```js
require('json5/lib/register')
```
Then you can load a JSON5 file with a Node.js `require()` statement. For
example:
```js
const config = require('./config.json5')
```
## CLI
Since JSON is more widely used than JSON5, this package includes a CLI for
converting JSON5 to JSON and for validating the syntax of JSON5 documents.
### Installation
```sh
npm install --global json5
```
### Usage
```sh
json5 [options] <file>
```
If `<file>` is not provided, then STDIN is used.
#### Options:
- `-s`, `--space`: The number of spaces to indent or `t` for tabs
- `-o`, `--out-file [file]`: Output to the specified file, otherwise STDOUT
- `-v`, `--validate`: Validate JSON5 but do not output JSON
- `-V`, `--version`: Output the version number
- `-h`, `--help`: Output usage information
## Contributing
### Development
```sh
git clone https://github.com/json5/json5
cd json5
npm install
```
When contributing code, please write relevant tests and run `npm test` and `npm
run lint` before submitting pull requests. Please use an editor that supports
[EditorConfig](http://editorconfig.org/).
### Issues
To report bugs or request features regarding the JSON5 data format, please
submit an issue to the [official specification
repository](https://github.com/json5/json5-spec).
To report bugs or request features regarding the JavaScript implementation of
JSON5, please submit an issue to this repository.
## License
MIT. See [LICENSE.md](./LICENSE.md) for details.
## Credits
[Assem Kishore](https://github.com/aseemk) founded this project.
[Michael Bolin](http://bolinfest.com/) independently arrived at and published
some of these same ideas with awesome explanations and detail. Recommended
reading: [Suggested Improvements to JSON](http://bolinfest.com/essays/json.html)
[Douglas Crockford](http://www.crockford.com/) of course designed and built
JSON, but his state machine diagrams on the [JSON website](http://json.org/), as
cheesy as it may sound, gave us motivation and confidence that building a new
parser to implement these ideas was within reach! The original
implementation of JSON5 was also modeled directly off of Dougโs open-source
[json_parse.js] parser. Weโre grateful for that clean and well-documented
code.
[json_parse.js]:
https://github.com/douglascrockford/JSON-js/blob/03157639c7a7cddd2e9f032537f346f1a87c0f6d/json_parse.js
[Max Nanasy](https://github.com/MaxNanasy) has been an early and prolific
supporter, contributing multiple patches and ideas.
[Andrew Eisenberg](https://github.com/aeisenberg) contributed the original
`stringify` method.
[Jordan Tucker](https://github.com/jordanbtucker) has aligned JSON5 more closely
with ES5, wrote the official JSON5 specification, completely rewrote the
codebase from the ground up, and is actively maintaining this project.
# json-buffer
JSON functions that can convert buffers!
[](http://travis-ci.org/dominictarr/json-buffer)
[](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');
```
file-uri-to-path
================
### Convert a `file:` URI to a file path
[](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 <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
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)
[](https://nodei.co/npm/node-addon-api/) [](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:









## **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
# 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
# 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
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.
# emoji-regex [](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
| [](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.
# babel-plugin-polyfill-corejs2
## Install
Using npm:
```sh
npm install --save-dev babel-plugin-polyfill-corejs2
```
or using yarn:
```sh
yarn add babel-plugin-polyfill-corejs2 --dev
```
## Usage
Add this plugin to your Babel configuration:
```json
{
"plugins": [["polyfill-corejs2", { "method": "usage-global" }]]
}
```
This package supports the `usage-pure`, `usage-global`, and `entry-global` methods.
When `entry-global` is used, it replaces imports to `core-js`.
# is-error
<!--
[![build status][build-png]][build]
[![Coverage Status][cover-png]][cover]
[![Davis Dependency status][dep-png]][dep]
-->
<!-- [![NPM][npm-png]][npm] -->
Detect whether a value is an error
## Example
```js
var isError = require("is-error");
console.log(isError(new Error('hi'))) // true
console.log(isError({ message: 'hi' })) // false
```
## Docs
### `var bool = isError(maybeErr)`
```hs
is-error := (maybeErr: Any) => Boolean
```
`isError` returns a boolean. it will detect whether the argument
is an error or not.
## Installation
`npm install is-error`
## Tests
`npm test`
## Contributors
- Raynos
## MIT Licensed
[build-png]: https://secure.travis-ci.org/Raynos/is-error.png
[build]: https://travis-ci.org/Raynos/is-error
[cover-png]: https://coveralls.io/repos/Raynos/is-error/badge.png
[cover]: https://coveralls.io/r/Raynos/is-error
[dep-png]: https://david-dm.org/Raynos/is-error.png
[dep]: https://david-dm.org/Raynos/is-error
[npm-png]: https://nodei.co/npm/is-error.png?stars&downloads
[npm]: https://nodei.co/npm/is-error
# 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");
```
# capability.js - javascript environment capability detection
[](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
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**.
# near-api-js
[](https://travis-ci.com/near/near-api-js)
[](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.
# BIP39
[](https://travis-ci.org/bitcoinjs/bip39)
[](https://www.npmjs.org/package/bip39)
[](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'
```
# Fast Diff [](https://travis-ci.org/jhchen/fast-diff)
This is a simplified import of the excellent [diff-match-patch](https://code.google.com/p/google-diff-match-patch/) library by [Neil Fraser](https://neil.fraser.name/) into the Node.js environment. The match and patch parts are removed, as well as all the extra diff options. What remains is incredibly fast diffing between two strings.
The diff function is an implementation of ["An O(ND) Difference Algorithm and its Variations" (Myers, 1986)](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.4.6927&rep=rep1&type=pdf) with the suggested divide and conquer strategy along with several [optimizations](http://neil.fraser.name/news/2007/10/09/) Neil added.
```js
var diff = require('fast-diff');
var good = 'Good dog';
var bad = 'Bad dog';
var result = diff(good, bad);
// [[-1, "Goo"], [1, "Ba"], [0, "d dog"]]
// Respect suggested edit location (cursor position), added in v1.1
diff('aaa', 'aaaa', 1)
// [[0, "a"], [1, "a"], [0, "aa"]]
// For convenience
diff.INSERT === 1;
diff.EQUAL === 0;
diff.DELETE === -1;
```
# emoji-regex [](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
| [](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.
# 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.
[](https://www.npmjs.com/package/prebuild-install)

[](https://github.com/prebuild/prebuild-install/actions/workflows/test.yml)
[](https://david-dm.org/prebuild/prebuild-install)
[](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

The default scopes should be fine.
### Custom binaries
The end user can override binary download location through environment variables in their .npmrc file.
The variable needs to meet the mask `% your package name %_binary_host` or `% your package name %_binary_host_mirror`. For example:
```
leveldown_binary_host=http://overriden-host.com/overriden-path
```
Note that the package version subpath and file name will still be appended.
So if you are installing `[email protected]` the resulting url will be:
```
http://overriden-host.com/overriden-path/v1.2.3/leveldown-v1.2.3-node-v57-win32-x64.tar.gz
```
#### Local prebuilds
If you want to use prebuilds from your local filesystem, you can use the `% your package name %_local_prebuilds` .npmrc variable to set a path to the folder containing prebuilds. For example:
```
leveldown_local_prebuilds=/path/to/prebuilds
```
This option will look directly in that folder for bundles created with `prebuild`, for example:
```
/path/to/prebuilds/leveldown-v1.2.3-node-v57-win32-x64.tar.gz
```
Non-absolute paths resolve relative to the directory of the package invoking prebuild-install, e.g. for nested dependencies.
### Cache
All prebuilt binaries are cached to minimize traffic. So first `prebuild-install` picks binaries from the cache and if no binary could be found, it will be downloaded. Depending on the environment, the cache folder is determined in the following order:
- `${npm_config_cache}/_prebuilds`
- `${APP_DATA}/npm-cache/_prebuilds`
- `${HOME}/.npm/_prebuilds`
## License
MIT
# <img src="docs_app/assets/Rx_Logo_S.png" alt="RxJS Logo" width="86" height="86"> RxJS: Reactive Extensions For JavaScript
[](https://circleci.com/gh/ReactiveX/rxjs/tree/6.x)
[](http://badge.fury.io/js/%40reactivex%2Frxjs)
[](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/
# lodash.debounce v4.0.8
The [lodash](https://lodash.com/) method `_.debounce` exported as a [Node.js](https://nodejs.org/) module.
## Installation
Using npm:
```bash
$ {sudo -H} npm i -g npm
$ npm i --save lodash.debounce
```
In Node.js:
```js
var debounce = require('lodash.debounce');
```
See the [documentation](https://lodash.com/docs#debounce) or [package source](https://github.com/lodash/lodash/blob/4.0.8-npm-packages/lodash.debounce) for more details.
write-file-atomic
-----------------
This is an extension for node's `fs.writeFile` that makes its operation
atomic and allows you set ownership (uid/gid of the file).
### `writeFileAtomic(filename, data, [options], [callback])`
#### Description:
Atomically and asynchronously writes data to a file, replacing the file if it already
exists. data can be a string or a buffer.
#### Options:
* filename **String**
* data **String** | **Buffer**
* options **Object** | **String**
* chown **Object** default, uid & gid of existing file, if any
* uid **Number**
* gid **Number**
* encoding **String** | **Null** default = 'utf8'
* fsync **Boolean** default = true
* mode **Number** default, from existing file, if any
* tmpfileCreated **Function** called when the tmpfile is created
* callback **Function**
#### Usage:
```js
var writeFileAtomic = require('write-file-atomic')
writeFileAtomic(filename, data, [options], [callback])
```
The file is initially named `filename + "." + murmurhex(__filename, process.pid, ++invocations)`.
Note that `require('worker_threads').threadId` is used in addition to `process.pid` if running inside of a worker thread.
If writeFile completes successfully then, if passed the **chown** option it will change
the ownership of the file. Finally it renames the file back to the filename you specified. If
it encounters errors at any of these steps it will attempt to unlink the temporary file and then
pass the error back to the caller.
If multiple writes are concurrently issued to the same file, the write operations are put into a queue and serialized in the order they were called, using Promises. Writes to different files are still executed in parallel.
If provided, the **chown** option requires both **uid** and **gid** properties or else
you'll get an error. If **chown** is not specified it will default to using
the owner of the previous file. To prevent chown from being ran you can
also pass `false`, in which case the file will be created with the current user's credentials.
If **mode** is not specified, it will default to using the permissions from
an existing file, if any. Expicitly setting this to `false` remove this default, resulting
in a file created with the system default permissions.
If options is a String, it's assumed to be the **encoding** option. The **encoding** option is ignored if **data** is a buffer. It defaults to 'utf8'.
If the **fsync** option is **false**, writeFile will skip the final fsync call.
If the **tmpfileCreated** option is specified it will be called with the name of the tmpfile when created.
Example:
```javascript
writeFileAtomic('message.txt', 'Hello Node', {chown:{uid:100,gid:50}}, function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
```
This function also supports async/await:
```javascript
(async () => {
try {
await writeFileAtomic('message.txt', 'Hello Node', {chown:{uid:100,gid:50}});
console.log('It\'s saved!');
} catch (err) {
console.error(err);
process.exit(1);
}
})();
```
### `writeFileAtomicSync(filename, data, [options])`
#### Description:
The synchronous version of **writeFileAtomic**.
#### Usage:
```js
var writeFileAtomicSync = require('write-file-atomic').sync
writeFileAtomicSync(filename, data, [options])
```
# 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
# defer-to-connect
> The safe way to handle the `connect` socket event
[](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
# 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()
```
# js-string-escape
[](https://travis-ci.org/joliss/js-string-escape)
Escape any string to be a valid JavaScript string literal between double
quotes or single quotes.
## Installation
```
npm install js-string-escape
```
## Example
If you need to generate JavaScript output, this library will help you safely
put arbitrary data in JavaScript strings:
```js
jsStringEscape = require('js-string-escape')
console.log('"' + jsStringEscape('Quotes (\", \'), newlines (\n), etc.') + '"')
// => "Quotes (\", \'), newlines (\n), etc."
```
In other words, given any string `s`, the following invariants hold:
```js
eval('"' + jsStringEscape(s) + '"') === s
eval("'" + jsStringEscape(s) + "'") === s
```
These `eval` expressions are safe with untrusted strings `s`.
Non-strings will be cast to strings.
## Compliance
This library has been checked against [ECMAScript
5.1](http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4) and tested
against all Unicode code points.
Note that the returned string is not necessarily valid JSON, since JSON
disallows control characters, and `\'` is illegal in JSON.
# 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.
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')`
# Can I cache this? [](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

## 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).
# `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
```
# `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
```
# parse-passwd [](https://www.npmjs.com/package/parse-passwd) [](https://npmjs.org/package/parse-passwd) [](https://travis-ci.org/doowb/parse-passwd) [](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._
[](https://travis-ci.org/toddbluhm/env-cmd)
[](https://coveralls.io/github/toddbluhm/env-cmd?branch=master)
[](https://www.npmjs.com/package/env-cmd)
[](https://www.npmjs.com/package/env-cmd)
[](https://www.npmjs.com/package/env-cmd)
[](https://github.com/toddbluhm/ts-standard)
[](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
# emoji-regex [](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
| [](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.
A JSON with color names and its values. Based on http://dev.w3.org/csswg/css-color/#named-colors.
[](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>
# v8-compile-cache-lib
> Fork of [`v8-compile-cache`](https://www.npmjs.com/package/v8-compile-cache) exposed as an API for programmatic usage in other libraries and tools.
---
[](https://github.com/cspotcode/v8-compile-cache-lib/actions?query=workflow%3A%22Continuous+Integration%22)
`v8-compile-cache-lib` attaches a `require` hook to use [V8's code cache](https://v8project.blogspot.com/2015/07/code-caching.html) to speed up instantiation time. The "code cache" is the work of parsing and compiling done by V8.
The ability to tap into V8 to produce/consume this cache was introduced in [Node v5.7.0](https://nodejs.org/en/blog/release/v5.7.0/).
## Usage
1. Add the dependency:
```sh
$ npm install --save v8-compile-cache-lib
```
2. Then, in your entry module add:
```js
require('v8-compile-cache-lib').install();
```
**`.install()` in Node <5.7.0 is a noop โ but you need at least Node 4.0.0 to support the ES2015 syntax used by `v8-compile-cache-lib`.**
## Options
Set the environment variable `DISABLE_V8_COMPILE_CACHE=1` to disable the cache.
Cache directory is defined by environment variable `V8_COMPILE_CACHE_CACHE_DIR` or defaults to `<os.tmpdir()>/v8-compile-cache-<V8_VERSION>`.
## Internals
Cache files are suffixed `.BLOB` and `.MAP` corresponding to the entry module that required `v8-compile-cache-lib`. The cache is _entry module specific_ because it is faster to load the entire code cache into memory at once, than it is to read it from disk on a file-by-file basis.
## Benchmarks
See https://github.com/cspotcode/v8-compile-cache-lib/tree/master/bench.
**Load Times:**
| Module | Without Cache | With Cache |
| ---------------- | -------------:| ----------:|
| `babel-core` | `218ms` | `185ms` |
| `yarn` | `153ms` | `113ms` |
| `yarn` (bundled) | `228ms` | `105ms` |
_^ Includes the overhead of loading the cache itself._
## Acknowledgements
* The original [`v8-compile-cache`](https://github.com/zertosh/v8-compile-cache) from which this library is forked.
* `FileSystemBlobStore` and `NativeCompileCache` are based on Atom's implementation of their v8 compile cache:
- https://github.com/atom/atom/blob/b0d7a8a/src/file-system-blob-store.js
- https://github.com/atom/atom/blob/b0d7a8a/src/native-compile-cache.js
* `mkdirpSync` is based on:
- https://github.com/substack/node-mkdirp/blob/f2003bb/index.js#L55-L98
# 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'
```
# run-parallel [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url]
[travis-image]: https://img.shields.io/travis/feross/run-parallel/master.svg
[travis-url]: https://travis-ci.org/feross/run-parallel
[npm-image]: https://img.shields.io/npm/v/run-parallel.svg
[npm-url]: https://npmjs.org/package/run-parallel
[downloads-image]: https://img.shields.io/npm/dm/run-parallel.svg
[downloads-url]: https://npmjs.org/package/run-parallel
[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg
[standard-url]: https://standardjs.com
### Run an array of functions in parallel
 [](https://saucelabs.com/u/run-parallel)
### install
```
npm install run-parallel
```
### usage
#### parallel(tasks, [callback])
Run the `tasks` array of functions in parallel, without waiting until the previous
function has completed. If any of the functions pass an error to its callback, the main
`callback` is immediately called with the value of the error. Once the `tasks` have
completed, the results are passed to the final `callback` as an array.
It is also possible to use an object instead of an array. Each property will be run as a
function and the results will be passed to the final `callback` as an object instead of
an array. This can be a more readable way of handling the results.
##### arguments
- `tasks` - An array or object containing functions to run. Each function is passed a
`callback(err, result)` which it must call on completion with an error `err` (which can
be `null`) and an optional `result` value.
- `callback(err, results)` - An optional callback to run once all the functions have
completed. This function gets a results array (or object) containing all the result
arguments passed to the task callbacks.
##### example
```js
var parallel = require('run-parallel')
parallel([
function (callback) {
setTimeout(function () {
callback(null, 'one')
}, 200)
},
function (callback) {
setTimeout(function () {
callback(null, 'two')
}, 100)
}
],
// optional callback
function (err, results) {
// the results array will equal ['one','two'] even though
// the second function had a shorter timeout.
})
```
This module is basically equavalent to
[`async.parallel`](https://github.com/caolan/async#paralleltasks-callback), but it's
handy to just have the one function you need instead of the kitchen sink. Modularity!
Especially handy if you're serving to the browser and need to reduce your javascript
bundle size.
Works great in the browser with [browserify](http://browserify.org/)!
### see also
- [run-auto](https://github.com/feross/run-auto)
- [run-parallel-limit](https://github.com/feross/run-parallel-limit)
- [run-series](https://github.com/feross/run-series)
- [run-waterfall](https://github.com/feross/run-waterfall)
### license
MIT. Copyright (c) [Feross Aboukhadijeh](http://feross.org).
# `scheduler`
This is a package for cooperative scheduling in a browser environment. It is currently used internally by React, but we plan to make it more generic.
The public API for this package is not yet finalized.
### Thanks
The React team thanks [Anton Podviaznikov](https://podviaznikov.com/) for donating the `scheduler` package name.
# YAML <a href="https://www.npmjs.com/package/yaml"><img align="right" src="https://badge.fury.io/js/yaml.svg" title="npm package" /></a>
`yaml` is a JavaScript parser and stringifier for [YAML](http://yaml.org/), a human friendly data serialization standard. It supports both parsing and stringifying data using all versions of YAML, along with all common data schemas. As a particularly distinguishing feature, `yaml` fully supports reading and writing comments and blank lines in YAML documents.
The library is released under the ISC open source license, and the code is [available on GitHub](https://github.com/eemeli/yaml/). It has no external dependencies and runs on Node.js 6 and later, and in browsers from IE 11 upwards.
For the purposes of versioning, any changes that break any of the endpoints or APIs documented here will be considered semver-major breaking changes. Undocumented library internals may change between minor versions, and previous APIs may be deprecated (but not removed).
For more information, see the project's documentation site: [**eemeli.org/yaml/v1**](https://eemeli.org/yaml/v1/)
To install:
```sh
npm install yaml
```
**Note:** This is `yaml@1`. You may also be interested in the next version, currently available as [`yaml@next`](https://www.npmjs.com/package/yaml/v/next).
## API Overview
The API provided by `yaml` has three layers, depending on how deep you need to go: [Parse & Stringify](https://eemeli.org/yaml/v1/#parse-amp-stringify), [Documents](https://eemeli.org/yaml/#documents), and the [CST Parser](https://eemeli.org/yaml/#cst-parser). The first has the simplest API and "just works", the second gets you all the bells and whistles supported by the library along with a decent [AST](https://eemeli.org/yaml/#content-nodes), and the third is the closest to YAML source, making it fast, raw, and crude.
```js
import YAML from 'yaml'
// or
const YAML = require('yaml')
```
### Parse & Stringify
- [`YAML.parse(str, options): value`](https://eemeli.org/yaml/v1/#yaml-parse)
- [`YAML.stringify(value, options): string`](https://eemeli.org/yaml/v1/#yaml-stringify)
### YAML Documents
- [`YAML.createNode(value, wrapScalars, tag): Node`](https://eemeli.org/yaml/v1/#creating-nodes)
- [`YAML.defaultOptions`](https://eemeli.org/yaml/v1/#options)
- [`YAML.Document`](https://eemeli.org/yaml/v1/#yaml-documents)
- [`constructor(options)`](https://eemeli.org/yaml/v1/#creating-documents)
- [`defaults`](https://eemeli.org/yaml/v1/#options)
- [`#anchors`](https://eemeli.org/yaml/v1/#working-with-anchors)
- [`#contents`](https://eemeli.org/yaml/v1/#content-nodes)
- [`#errors`](https://eemeli.org/yaml/v1/#errors)
- [`YAML.parseAllDocuments(str, options): YAML.Document[]`](https://eemeli.org/yaml/v1/#parsing-documents)
- [`YAML.parseDocument(str, options): YAML.Document`](https://eemeli.org/yaml/v1/#parsing-documents)
```js
import { Pair, YAMLMap, YAMLSeq } from 'yaml/types'
```
- [`new Pair(key, value)`](https://eemeli.org/yaml/v1/#creating-nodes)
- [`new YAMLMap()`](https://eemeli.org/yaml/v1/#creating-nodes)
- [`new YAMLSeq()`](https://eemeli.org/yaml/v1/#creating-nodes)
### CST Parser
```js
import parseCST from 'yaml/parse-cst'
```
- [`parseCST(str): CSTDocument[]`](https://eemeli.org/yaml/v1/#parsecst)
- [`YAML.parseCST(str): CSTDocument[]`](https://eemeli.org/yaml/v1/#parsecst)
## YAML.parse
```yaml
# file.yml
YAML:
- A human-readable data serialization language
- https://en.wikipedia.org/wiki/YAML
yaml:
- A complete JavaScript implementation
- https://www.npmjs.com/package/yaml
```
```js
import fs from 'fs'
import YAML from 'yaml'
YAML.parse('3.14159')
// 3.14159
YAML.parse('[ true, false, maybe, null ]\n')
// [ true, false, 'maybe', null ]
const file = fs.readFileSync('./file.yml', 'utf8')
YAML.parse(file)
// { YAML:
// [ 'A human-readable data serialization language',
// 'https://en.wikipedia.org/wiki/YAML' ],
// yaml:
// [ 'A complete JavaScript implementation',
// 'https://www.npmjs.com/package/yaml' ] }
```
## YAML.stringify
```js
import YAML from 'yaml'
YAML.stringify(3.14159)
// '3.14159\n'
YAML.stringify([true, false, 'maybe', null])
// `- true
// - false
// - maybe
// - null
// `
YAML.stringify({ number: 3, plain: 'string', block: 'two\nlines\n' })
// `number: 3
// plain: string
// block: >
// two
//
// lines
// `
```
---
Browser testing provided by:
<a href="https://www.browserstack.com/open-source">
<img width=200 src="https://eemeli.org/yaml/images/browserstack.svg" />
</a>
A JSON with color names and its values. Based on http://dev.w3.org/csswg/css-color/#named-colors.
[](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>
<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>

[![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
# 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 :)
[](https://www.npmjs.com/package/ci-info)
[](https://travis-ci.org/watson/ci-info)
[](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)
# jsesc [](https://travis-ci.org/mathiasbynens/jsesc) [](https://coveralls.io/r/mathiasbynens/jsesc) [](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
| [](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.
#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.
# is-plain-object [](https://www.npmjs.com/package/is-plain-object) [](https://npmjs.org/package/is-plain-object) [](https://npmjs.org/package/is-plain-object) [](https://travis-ci.org/jonschlinkert/is-plain-object)
> Returns true if an object was created by the `Object` constructor, or Object.create(null).
Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support.
## Install
Install with [npm](https://www.npmjs.com/):
```sh
$ npm install --save is-plain-object
```
Use [isobject](https://github.com/jonschlinkert/isobject) if you only want to check if the value is an object and not an array or null.
## Usage
with es modules
```js
import { isPlainObject } from 'is-plain-object';
```
or with commonjs
```js
const { isPlainObject } = require('is-plain-object');
```
**true** when created by the `Object` constructor, or Object.create(null).
```js
isPlainObject(Object.create({}));
//=> true
isPlainObject(Object.create(Object.prototype));
//=> true
isPlainObject({foo: 'bar'});
//=> true
isPlainObject({});
//=> true
isPlainObject(null);
//=> true
```
**false** when not created by the `Object` constructor.
```js
isPlainObject(1);
//=> false
isPlainObject(['foo', 'bar']);
//=> false
isPlainObject([]);
//=> false
isPlainObject(new Foo);
//=> false
isPlainObject(Object.create(null));
//=> false
```
## About
<details>
<summary><strong>Contributing</strong></summary>
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
</details>
<details>
<summary><strong>Running Tests</strong></summary>
Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:
```sh
$ npm install && npm test
```
</details>
<details>
<summary><strong>Building docs</strong></summary>
_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
To generate the readme, run the following command:
```sh
$ npm install -g verbose/verb#dev verb-generate-readme && verb
```
</details>
### Related projects
You might also be interested in these projects:
* [is-number](https://www.npmjs.com/package/is-number): Returns true if a number or string value is a finite number. Useful for regexโฆ [more](https://github.com/jonschlinkert/is-number) | [homepage](https://github.com/jonschlinkert/is-number "Returns true if a number or string value is a finite number. Useful for regex matches, parsing, user input, etc.")
* [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject "Returns true if the value is an object and not an array or null.")
* [kind-of](https://www.npmjs.com/package/kind-of): Get the native type of a value. | [homepage](https://github.com/jonschlinkert/kind-of "Get the native type of a value.")
### Contributors
| **Commits** | **Contributor** |
| --- | --- |
| 19 | [jonschlinkert](https://github.com/jonschlinkert) |
| 6 | [TrySound](https://github.com/TrySound) |
| 6 | [stevenvachon](https://github.com/stevenvachon) |
| 3 | [onokumus](https://github.com/onokumus) |
| 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) |
### Author
**Jon Schlinkert**
* [GitHub Profile](https://github.com/jonschlinkert)
* [Twitter Profile](https://twitter.com/jonschlinkert)
* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert)
### License
Copyright ยฉ 2019, [Jon Schlinkert](https://github.com/jonschlinkert).
Released under the [MIT License](LICENSE).
***
_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on April 28, 2019._
# `react-error-overlay`
`react-error-overlay` is an overlay which displays when there is a runtime error.
## Development
When developing within this package, make sure you run `npm start` (or `yarn start`) so that the files are compiled as you work.
This is run in watch mode by default.
If you would like to build this for production, run `npm run build:prod` (or `yarn build:prod`).<br>
If you would like to build this one-off for development, you can run `NODE_ENV=development npm run build` (or `NODE_ENV=development yarn build`).
# clone-response
> Clone a Node.js HTTP response stream
[](https://travis-ci.org/lukechilds/clone-response)
[](https://coveralls.io/github/lukechilds/clone-response?branch=master)
[](https://www.npmjs.com/package/clone-response)
[](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
# Acorn
A tiny, fast JavaScript parser written in JavaScript.
## Community
Acorn is open source software released under an
[MIT license](https://github.com/acornjs/acorn/blob/master/acorn/LICENSE).
You are welcome to
[report bugs](https://github.com/acornjs/acorn/issues) or create pull
requests on [github](https://github.com/acornjs/acorn). For questions
and discussion, please use the
[Tern discussion forum](https://discuss.ternjs.net).
## Installation
The easiest way to install acorn is from [`npm`](https://www.npmjs.com/):
```sh
npm install acorn
```
Alternately, you can download the source and build acorn yourself:
```sh
git clone https://github.com/acornjs/acorn.git
cd acorn
npm install
```
## Interface
**parse**`(input, options)` is the main interface to the library. The
`input` parameter is a string, `options` must be an object setting
some of the options listed below. The return value will be an abstract
syntax tree object as specified by the [ESTree
spec](https://github.com/estree/estree).
```javascript
let acorn = require("acorn");
console.log(acorn.parse("1 + 1", {ecmaVersion: 2020}));
```
When encountering a syntax error, the parser will raise a
`SyntaxError` object with a meaningful message. The error object will
have a `pos` property that indicates the string offset at which the
error occurred, and a `loc` object that contains a `{line, column}`
object referring to that same position.
Options are provided by in a second argument, which should be an
object containing any of these fields (only `ecmaVersion` is
required):
- **ecmaVersion**: Indicates the ECMAScript version to parse. Must be
either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10 (2019),
11 (2020), 12 (2021), 13 (2022, partial support)
or `"latest"` (the latest the library supports). This influences
support for strict mode, the set of reserved words, and support
for new syntax features.
**NOTE**: Only 'stage 4' (finalized) ECMAScript features are being
implemented by Acorn. Other proposed new features must be
implemented through plugins.
- **sourceType**: Indicate the mode the code should be parsed in. Can be
either `"script"` or `"module"`. This influences global strict mode
and parsing of `import` and `export` declarations.
**NOTE**: If set to `"module"`, then static `import` / `export` syntax
will be valid, even if `ecmaVersion` is less than 6.
- **onInsertedSemicolon**: If given a callback, that callback will be
called whenever a missing semicolon is inserted by the parser. The
callback will be given the character offset of the point where the
semicolon is inserted as argument, and if `locations` is on, also a
`{line, column}` object representing this position.
- **onTrailingComma**: Like `onInsertedSemicolon`, but for trailing
commas.
- **allowReserved**: If `false`, using a reserved word will generate
an error. Defaults to `true` for `ecmaVersion` 3, `false` for higher
versions. When given the value `"never"`, reserved words and
keywords can also not be used as property names (as in Internet
Explorer's old parser).
- **allowReturnOutsideFunction**: By default, a return statement at
the top level raises an error. Set this to `true` to accept such
code.
- **allowImportExportEverywhere**: By default, `import` and `export`
declarations can only appear at a program's top level. Setting this
option to `true` allows them anywhere where a statement is allowed,
and also allows `import.meta` expressions to appear in scripts
(when `sourceType` is not `"module"`).
- **allowAwaitOutsideFunction**: If `false`, `await` expressions can
only appear inside `async` functions. Defaults to `true` for
`ecmaVersion` 2022 and later, `false` for lower versions. Setting this option to
`true` allows to have top-level `await` expressions. They are
still not allowed in non-`async` functions, though.
- **allowSuperOutsideMethod**: By default, `super` outside a method
raises an error. Set this to `true` to accept such code.
- **allowHashBang**: When this is enabled (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/>)", {ecmaVersion: 2020});
```
The `extend` method takes any number of plugin values, and returns a
new `Parser` class that includes the extra parser logic provided by
the plugins.
## Command line interface
The `bin/acorn` utility can be used to parse a file from the command
line. It accepts as arguments its input file and the following
options:
- `--ecma3|--ecma5|--ecma6|--ecma7|--ecma8|--ecma9|--ecma10`: Sets the ECMAScript version
to parse. Default is version 9.
- `--module`: Sets the parsing mode to `"module"`. Is set to `"script"` otherwise.
- `--locations`: Attaches a "loc" object to each node with "start" and
"end" subobjects, each of which contains the one-based line and
zero-based column numbers in `{line, column}` form.
- `--allow-hash-bang`: If the code starts with the characters #! (as
in a shellscript), the first line will be treated as a comment.
- `--allow-await-outside-function`: Allows top-level `await` expressions.
See the `allowAwaitOutsideFunction` option for more information.
- `--compact`: No whitespace is used in the AST output.
- `--silent`: Do not output the AST, just return the exit status.
- `--help`: Print the usage information and quit.
The utility spits out the syntax tree as JSON data.
## Existing plugins
- [`acorn-jsx`](https://github.com/RReverser/acorn-jsx): Parse [Facebook JSX syntax extensions](https://github.com/facebook/jsx)
# node-error-ex [](https://travis-ci.org/Qix-/node-error-ex) [](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).
Like `chown -R`.
Takes the same arguments as `fs.chown()`
<div align="center">
# utility-types
Collection of utility types, complementing TypeScript built-in mapped types and aliases (think "lodash" for static types).
[](https://www.npmjs.com/package/utility-types)
[](https://www.npmjs.com/package/utility-types)
[](https://www.npmjs.com/package/utility-types)
[](https://www.npmjs.com/package/utility-types)
[](https://semaphoreci.com/piotrekwitek/utility-types)
[](https://david-dm.org/piotrwitek/utility-types)
[](https://david-dm.org/piotrwitek/utility-types?type=peer)
[](https://spectrum.chat/utility-types)
_Found it useful? Want more updates?_
[**Show your support by giving a :star:**](https://github.com/piotrwitek/utility-types/stargazers)
<a href="https://www.buymeacoffee.com/piotrekwitek">
<img src="https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png" alt="Buy Me a Coffee">
</a>
<a href="https://www.patreon.com/piotrekwitek">
<img src="https://c5.patreon.com/external/logo/[email protected]" alt="Become a Patron" width="160">
</a>
<br/><hr/>
### **What's new?**
:tada: _Now updated to support **TypeScript v3.7**_ :tada:
<hr/><br/>
</div>
## Features
* Providing a set of [Common Types](#table-of-contents) for TypeScript projects that are idiomatic and complementary to existing [TypeScript Mapped Types](https://www.typescriptlang.org/docs/handbook/advanced-types.html) so you don't need to copy them between the projects.
* Providing a set of [Additional Types](#) compatible with [Flow's Utility Types](https://flow.org/en/docs/types/utilities/) to allow much easier migration to `TypeScript`.
## Goals
* Quality - thoroughly tested for type correctness with type-testing library `dts-jest`
* Secure and minimal - no third-party dependencies
* No runtime cost - it's type-level only
## Installation
```bash
# NPM
npm install utility-types
# YARN
yarn add utility-types
```
## Compatibility Notes
**TypeScript support**
* `v3.x.x` - TypeScript v3.1+
* `v2.x.x` - TypeScript v2.8.1+
* `v1.x.x` - TypeScript v2.7.2+
## Funding Issues
**Utility-Types** is an open-source project created by people investing their time for the benefit of our community.
Issues like bug fixes or feature requests can be very quickly resolved when funded through the IssueHunt platform.
I highly recommend adding a bounty to the issue that you're waiting for to attract some contributors willing to work on it.
[](https://issuehunt.io/repos/76400842)
## Contributing
We are open for contributions. If you're planning to contribute please make sure to read the contributing guide as it can save you from wasting your time: [CONTRIBUTING.md](/CONTRIBUTING.md)
---
* _(built-in)_ - types built-in TypeScript, no need to import
# Table of Contents
## Aliases & Type Guards
* [`Primitive`](#primitive)
* [`isPrimitive`](#isprimitive)
* [`Falsy`](#falsy)
* [`isFalsy`](#isfalsy)
## Union operators
* [`SetIntersection<A, B>`](#setintersectiona-b-same-as-extract)
* [`SetDifference<A, B>`](#setdifferencea-b-same-as-exclude)
* [`SetComplement<A, A1>`](#setcomplementa-a1)
* [`SymmetricDifference<A, B>`](#symmetricdifferencea-b)
* [`Exclude<A, B>`](#excludea-b) _(built-in)_
* [`Extract<A, B>`](#extracta-b) _(built-in)_
* [`NonNullable<T>`](#nonnullablea) _(built-in)_
* [`NonUndefined<T>`](#nonundefineda)
## Object operators
* [`FunctionKeys<T>`](#functionkeyst)
* [`NonFunctionKeys<T>`](#nonfunctionkeyst)
* [`MutableKeys<T>`](#mutablekeyst)
* [`ReadonlyKeys<T>`](#readonlykeyst)
* [`RequiredKeys<T>`](#requiredkeyst)
* [`OptionalKeys<T>`](#optionalkeyst)
* [`Optional<T, K>`](#optionalt-k)
* [`Partial<T>`](#partialt) _(built-in)_
* [`DeepPartial<T>`](#deeppartialt)
* [`Required<T, K>`](#requiredt-k)
* [`DeepRequired<T>`](#deeprequiredt)
* [`Readonly<T>`](#readonlyt) _(built-in)_
* [`DeepReadonly<T>`](#deepreadonlyt)
* [`Mutable<T>`](#mutablet)
* [`Pick<T, K>` _(built-in)_](#pickt-k-built-in)
* [`Omit<T, K>`](#omitt-k) _(built-in)_
* [`PickByValue<T, ValueType>`](#pickbyvaluet-valuetype)
* [`PickByValueExact<T, ValueType>`](#pickbyvalueexactt-valuetype)
* [`OmitByValue<T, ValueType>`](#omitbyvaluet-valuetype)
* [`OmitByValueExact<T, ValueType>`](#omitbyvalueexactt-valuetype)
* [`Intersection<T, U>`](#intersectiont-u)
* [`Diff<T, U>`](#difft-u)
* [`Subtract<T, T1>`](#subtractt-t1)
* [`Overwrite<T, U>`](#overwritet-u)
* [`Assign<T, U>`](#assignt-u)
* [`ValuesType<T>`](#valuestypet)
## Special operators
* [`ReturnType<T>`](#returntypet) _(built-in)_
* [`InstanceType<T>`](#instancetypet) _(built-in)_
* [`PromiseType<T>`](#promisetypet)
* [`Unionize<T>`](#unionizet)
* [`Brand<T, U>`](#brandt-u)
* [`UnionToIntersection<U>`](#uniontointersectionu)
## Flow's Utility Types
* [`$Keys<T>`](#keyst)
* [`$Values<T>`](#valuest)
* [`$ReadOnly<T>`](#readonly2)
* [`$Diff<T, U>`](#diff2)
* [`$PropertyType<T, K>`](#propertytypet-k)
* [`$ElementType<T, K>`](#elementtypet-k)
* [`$Call<T>`](#callt)
* [`$Shape<T>`](#shapet)
* [`$NonMaybeType<T>`](#nonmaybetypet)
* [`Class<T>`](#classt)
* [`mixed`](#mixed)
## Deprecated API (use at own risk)
* `getReturnOfExpression()` - from TS v2.0 it's better to use type-level `ReturnType` instead
---
### `Primitive`
Type representing primitive types in JavaScript, and thus TypeScript: `string | number | bigint | boolean | symbol | null | undefined`
You can test for singular of these types with [`typeof`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof)
### `isPrimitive`
This is a [TypeScript Typeguard](https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types) for the [`Primitive`](#primitive) type.
This can be useful to control the type of a parameter as the program flows. Example:
```ts
const consumer = (param: Primitive[] | Primitive): string => {
if (isPrimitive(param)) {
// typeof param === Primitive
return String(param) + ' was Primitive';
}
// typeof param === Primitive[]
const resultArray = param
.map(consumer)
.map(rootString => '\n\t' + rootString);
return resultArray.reduce((comm, newV) => comm + newV, 'this was nested:');
};
```
[โง back to top](#table-of-contents)
### `Falsy`
Type representing falsy values in TypeScript: `false | "" | 0 | null | undefined`
> Except `NaN` which cannot be represented as a type literal
### `isFalsy`
```ts
const consumer = (param: Falsy | string): string => {
if (isFalsy(param)) {
// typeof param === Falsy
return String(param) + ' was Falsy';
}
// typeof param === string
return param.toString();
};
```
[โง back to top](#table-of-contents)
### `SetIntersection<A, B>` (same as Extract)
Set intersection of given union types `A` and `B`
**Usage:**
```ts
import { SetIntersection } from 'utility-types';
// Expect: "2" | "3"
type ResultSet = SetIntersection<'1' | '2' | '3', '2' | '3' | '4'>;
// Expect: () => void
type ResultSetMixed = SetIntersection<string | number | (() => void), Function>;
```
[โง back to top](#table-of-contents)
### `SetDifference<A, B>` (same as Exclude)
Set difference of given union types `A` and `B`
**Usage:**
```ts
import { SetDifference } from 'utility-types';
// Expect: "1"
type ResultSet = SetDifference<'1' | '2' | '3', '2' | '3' | '4'>;
// Expect: string | number
type ResultSetMixed = SetDifference<string | number | (() => void), Function>;
```
[โง back to top](#table-of-contents)
### `SetComplement<A, A1>`
Set complement of given union types `A` and (it's subset) `A1`
**Usage:**
```ts
import { SetComplement } from 'utility-types';
// Expect: "1"
type ResultSet = SetComplement<'1' | '2' | '3', '2' | '3'>;
```
[โง back to top](#table-of-contents)
### `SymmetricDifference<A, B>`
Set difference of union and intersection of given union types `A` and `B`
**Usage:**
```ts
import { SymmetricDifference } from 'utility-types';
// Expect: "1" | "4"
type ResultSet = SymmetricDifference<'1' | '2' | '3', '2' | '3' | '4'>;
```
[โง back to top](#table-of-contents)
### `NonNullable<A>`
Exclude `null` and `undefined` from set `A`
[โง back to top](#table-of-contents)
### `NonUndefined<A>`
Exclude `undefined` from set `A`
[โง back to top](#table-of-contents)
### `Exclude<A, B>`
Exclude subset `B` from set `A`
[โง back to top](#table-of-contents)
### `Extract<A, B>`
Extract subset `B` from set `A`
[โง back to top](#table-of-contents)
## Operations on objects
### `FunctionKeys<T>`
Get union type of keys that are functions in object type `T`
**Usage:**
```ts
import { FunctionKeys } from 'utility-types';
type MixedProps = { name: string; setName: (name: string) => void };
// Expect: "setName"
type Keys = FunctionKeys<MixedProps>;
```
[โง back to top](#table-of-contents)
### `NonFunctionKeys<T>`
Get union type of keys that are non-functions in object type `T`
**Usage:**
```ts
import { NonFunctionKeys } from 'utility-types';
type MixedProps = { name: string; setName: (name: string) => void };
// Expect: "name"
type Keys = NonFunctionKeys<MixedProps>;
```
[โง back to top](#table-of-contents)
### `MutableKeys<T>`
Get union type of keys that are mutable (not readonly) in object type `T`
Alias: `WritableKeys<T>`
**Usage:**
```ts
import { MutableKeys } from 'utility-types';
type Props = { readonly foo: string; bar: number };
// Expect: "bar"
type Keys = MutableKeys<Props>;
```
[โง back to top](#table-of-contents)
### `ReadonlyKeys<T>`
Get union type of keys that are readonly in object type `T`
**Usage:**
```ts
import { ReadonlyKeys } from 'utility-types';
type Props = { readonly foo: string; bar: number };
// Expect: "foo"
type Keys = ReadonlyKeys<Props>;
```
[โง back to top](#table-of-contents)
### `RequiredKeys<T>`
Get union type of keys that are required in object type `T`
**Usage:**
```ts
import { RequiredKeys } from 'utility-types';
type Props = { req: number; reqUndef: number | undefined; opt?: string; optUndef?: number | undefined; };
// Expect: "req" | "reqUndef"
type Keys = RequiredKeys<Props>;
```
[โง back to top](#table-of-contents)
### `OptionalKeys<T>`
Get union type of keys that are optional in object type `T`
**Usage:**
```ts
import { OptionalKeys } from 'utility-types';
type Props = { req: number; reqUndef: number | undefined; opt?: string; optUndef?: number | undefined; };
// Expect: "opt" | "optUndef"
type Keys = OptionalKeys<Props>;
```
[โง back to top](#table-of-contents)
### `Optional<T, K>`
From `T` make a set of properties by key `K` become optional
**Usage:**
```ts
import { Optional } from 'utility-types';
type Props = { name: string; age: number; visible: boolean; };
// Expect: { name?: string; age?: number; visible?: boolean; }
type Props = Optional<Props>
// Expect: { name: string; age?: number; visible?: boolean; }
type Props = Optional<Props, 'age' | 'visible'>;
```
[โง back to top](#table-of-contents)
### `Pick<T, K>` _(built-in)_
From `T` pick a set of properties by key `K`
**Usage:**
```ts
type Props = { name: string; age: number; visible: boolean };
// Expect: { age: number; }
type Props = Pick<Props, 'age'>;
```
[โง back to top](#table-of-contents)
### `PickByValue<T, ValueType>`
From `T` pick a set of properties by value matching `ValueType`.
_(Credit: [Piotr Lewandowski](https://medium.com/dailyjs/typescript-create-a-condition-based-subset-types-9d902cea5b8c))_
**Usage:**
```ts
import { PickByValue } from 'utility-types';
type Props = { req: number; reqUndef: number | undefined; opt?: string; };
// Expect: { req: number }
type Props = PickByValue<Props, number>;
// Expect: { req: number; reqUndef: number | undefined; }
type Props = PickByValue<Props, number | undefined>;
```
[โง back to top](#table-of-contents)
### `PickByValueExact<T, ValueType>`
From `T` pick a set of properties by value matching exact `ValueType`.
**Usage:**
```ts
import { PickByValueExact } from 'utility-types';
type Props = { req: number; reqUndef: number | undefined; opt?: string; };
// Expect: { req: number }
type Props = PickByValueExact<Props, number>;
// Expect: { reqUndef: number | undefined; }
type Props = PickByValueExact<Props, number | undefined>;
```
[โง back to top](#table-of-contents)
### `Omit<T, K>`
From `T` remove a set of properties by key `K`
**Usage:**
```ts
import { Omit } from 'utility-types';
type Props = { name: string; age: number; visible: boolean };
// Expect: { name: string; visible: boolean; }
type Props = Omit<Props, 'age'>;
```
[โง back to top](#table-of-contents)
### `OmitByValue<T, ValueType>`
From `T` remove a set of properties by value matching `ValueType`.
_(Credit: [Piotr Lewandowski](https://medium.com/dailyjs/typescript-create-a-condition-based-subset-types-9d902cea5b8c))_
**Usage:**
```ts
import { OmitByValue } from 'utility-types';
type Props = { req: number; reqUndef: number | undefined; opt?: string; };
// Expect: { reqUndef: number | undefined; opt?: string; }
type Props = OmitByValue<Props, number>;
// Expect: { opt?: string; }
type Props = OmitByValue<Props, number | undefined>;
```
[โง back to top](#table-of-contents)
### `OmitByValueExact<T, ValueType>`
From `T` remove a set of properties by value matching exact `ValueType`.
**Usage:**
```ts
import { OmitByValueExact } from 'utility-types';
type Props = { req: number; reqUndef: number | undefined; opt?: string; };
// Expect: { reqUndef: number | undefined; opt?: string; }
type Props = OmitByValueExact<Props, number>;
// Expect: { req: number; opt?: string }
type Props = OmitByValueExact<Props, number | undefined>;
```
[โง back to top](#table-of-contents)
### `Intersection<T, U>`
From `T` pick properties that exist in `U`
**Usage:**
```ts
import { Intersection } from 'utility-types';
type Props = { name: string; age: number; visible: boolean };
type DefaultProps = { age: number };
// Expect: { age: number; }
type DuplicatedProps = Intersection<Props, DefaultProps>;
```
[โง back to top](#table-of-contents)
### `Diff<T, U>`
From `T` remove properties that exist in `U`
**Usage:**
```ts
import { Diff } from 'utility-types';
type Props = { name: string; age: number; visible: boolean };
type DefaultProps = { age: number };
// Expect: { name: string; visible: boolean; }
type RequiredProps = Diff<Props, DefaultProps>;
```
[โง back to top](#table-of-contents)
### `Subtract<T, T1>`
From `T` remove properties that exist in `T1` (`T1` has a subset of the properties of `T`)
**Usage:**
```ts
import { Subtract } from 'utility-types';
type Props = { name: string; age: number; visible: boolean };
type DefaultProps = { age: number };
// Expect: { name: string; visible: boolean; }
type RequiredProps = Subtract<Props, DefaultProps>;
```
[โง back to top](#table-of-contents)
### `Overwrite<T, U>`
From `U` overwrite properties to `T`
**Usage:**
```ts
import { Overwrite } from 'utility-types';
type Props = { name: string; age: number; visible: boolean };
type NewProps = { age: string; other: string };
// Expect: { name: string; age: string; visible: boolean; }
type ReplacedProps = Overwrite<Props, NewProps>;
```
[โง back to top](#table-of-contents)
### `Assign<T, U>`
From `U` assign properties to `T` (just like object assign)
**Usage:**
```ts
import { Assign } from 'utility-types';
type Props = { name: string; age: number; visible: boolean };
type NewProps = { age: string; other: string };
// Expect: { name: string; age: number; visible: boolean; other: string; }
type ExtendedProps = Assign<Props, NewProps>;
```
[โง back to top](#table-of-contents)
### `ValuesType<T>`
Get the union type of all the values in an object, tuple, array or array-like type `T`.
**Usage:**
```ts
import { ValuesType } from 'utility-types';
type Props = { name: string; age: number; visible: boolean };
// Expect: string | number | boolean
type PropsValues = ValuesType<Props>;
type NumberArray = number[];
// Expect: number
type NumberItems = ValuesType<NumberArray>;
type ReadonlyNumberTuple = readonly [1, 2];
// Expect: 1 | 2
type AnotherNumberUnion = ValuesType<NumberTuple>;
type BinaryArray = Uint8Array;
// Expect: number
type BinaryItems = ValuesType<BinaryArray>;
```
[โง back to top](#table-of-contents)
### `Partial<T>`
Make all properties of object type optional
[โง back to top](#table-of-contents)
### `Required<T, K>`
From `T` make a set of properties by key `K` become required
**Usage:**
```ts
import { Required } from 'utility-types';
type Props = { name?: string; age?: number; visible?: boolean; };
// Expect: { name: string; age: number; visible: boolean; }
type Props = Required<Props>
// Expect: { name?: string; age: number; visible: boolean; }
type Props = Required<Props, 'age' | 'visible'>;
```
[โง back to top](#table-of-contents)
### `Readonly<T>`
Make all properties of object type readonly
[โง back to top](#table-of-contents)
### `Mutable<T>`
From `T` make all properties become mutable
Alias: `Writable<T>`
```ts
import { Mutable } from 'utility-types';
type Props = {
readonly name: string;
readonly age: number;
readonly visible: boolean;
};
// Expect: { name: string; age: number; visible: boolean; }
Mutable<Props>;
```
[โง back to top](#table-of-contents)
### `ReturnType<T>`
Obtain the return type of a function
[โง back to top](#table-of-contents)
### `InstanceType<T>`
Obtain the instance type of a class
[โง back to top](#table-of-contents)
### `Unionize<T>`
Disjoin object to form union of objects, each with single property
**Usage:**
```ts
import { Unionize } from 'utility-types';
type Props = { name: string; age: number; visible: boolean };
// Expect: { name: string; } | { age: number; } | { visible: boolean; }
type UnionizedType = Unionize<Props>;
```
[โง back to top](#table-of-contents)
### `PromiseType<T>`
Obtain Promise resolve type
**Usage:**
```ts
import { PromiseType } from 'utility-types';
// Expect: string
type Response = PromiseType<Promise<string>>;
```
[โง back to top](#table-of-contents)
### `DeepReadonly<T>`
Readonly that works for deeply nested structures
**Usage:**
```ts
import { DeepReadonly } from 'utility-types';
type NestedProps = {
first: {
second: {
name: string;
};
};
};
// Expect: {
// readonly first: {
// readonly second: {
// readonly name: string;
// };
// };
// }
type ReadonlyNestedProps = DeepReadonly<NestedProps>;
```
[โง back to top](#table-of-contents)
### `DeepRequired<T>`
Required that works for deeply nested structures
**Usage:**
```ts
import { DeepRequired } from 'utility-types';
type NestedProps = {
first?: {
second?: {
name?: string;
};
};
};
// Expect: {
// first: {
// second: {
// name: string;
// };
// };
// }
type RequiredNestedProps = DeepRequired<NestedProps>;
```
[โง back to top](#table-of-contents)
### `DeepNonNullable<T>`
NonNullable that works for deeply nested structure
**Usage:**
```ts
import { DeepNonNullable } from 'utility-types';
type NestedProps = {
first?: null | {
second?: null | {
name?: string | null | undefined;
};
};
};
// Expect: {
// first: {
// second: {
// name: string;
// };
// };
// }
type RequiredNestedProps = DeepNonNullable<NestedProps>;
```
[โง back to top](#table-of-contents)
### `DeepPartial<T>`
Partial that works for deeply nested structures
**Usage:**
```ts
import { DeepPartial } from 'utility-types';
type NestedProps = {
first: {
second: {
name: string;
};
};
};
// Expect: {
// first?: {
// second?: {
// name?: string;
// };
// };
// }
type PartialNestedProps = DeepPartial<NestedProps>;
```
[โง back to top](#table-of-contents)
### `Brand<T, U>`
Define nominal type of `U` based on type of `T`. Similar to Opaque types in Flow.
**Usage:**
```ts
import { Brand } from 'utility-types';
type USD = Brand<number, "USD">
type EUR = Brand<number, "EUR">
const tax = 5 as USD;
const usd = 10 as USD;
const eur = 10 as EUR;
function gross(net: USD): USD {
return (net + tax) as USD;
}
gross(usd); // ok
gross(eur); // Type '"EUR"' is not assignable to type '"USD"'.
```
[โง back to top](#table-of-contents)
### `UnionToIntersection<U>`
Get intersection type given union type `U`
**Usage:**
```ts
import { UnionToIntersection } from 'utility-types';
// Expect: { name: string } & { age: number } & { visible: boolean }
UnionToIntersection<{ name: string } | { age: number } | { visible: boolean }>
```
[โง back to top](#table-of-contents)
---
## Flow's Utility Types
### `$Keys<T>`
get the union type of all the keys in an object type `T`<br>
https://flow.org/en/docs/types/utilities/#toc-keys
**Usage:**
```ts
import { $Keys } from 'utility-types';
type Props = { name: string; age: number; visible: boolean };
// Expect: "name" | "age" | "visible"
type PropsKeys = $Keys<Props>;
```
[โง back to top](#flows-utility-types)
### `$Values<T>`
get the union type of all the values in an object type `T`<br>
https://flow.org/en/docs/types/utilities/#toc-values
**Usage:**
```ts
import { $Values } from 'utility-types';
type Props = { name: string; age: number; visible: boolean };
// Expect: string | number | boolean
type PropsValues = $Values<Props>;
```
[โง back to top](#flows-utility-types)
### <a id="readonly2"></a> `$ReadOnly<T>`
get the read-only version of a given object type `T`<br>
https://flow.org/en/docs/types/utilities/#toc-readonly
**Usage:**
```ts
import { $ReadOnly } from 'utility-types';
type Props = { name: string; age: number; visible: boolean };
// Expect: Readonly<{ name: string; age?: number | undefined; visible: boolean; }>
type ReadOnlyProps = $ReadOnly<Props>;
```
[โง back to top](#flows-utility-types)
### <a id="diff2"></a> `$Diff<T, U>`
get the set difference of a given object types `T` and `U` (`T \ U`)<br>
https://flow.org/en/docs/types/utilities/#toc-diff
**Usage:**
```ts
import { $Diff } from 'utility-types';
type Props = { name: string; age: number; visible: boolean };
type DefaultProps = { age: number };
// Expect: { name: string; visible: boolean; }
type RequiredProps = $Diff<Props, DefaultProps>;
```
[โง back to top](#flows-utility-types)
### `$PropertyType<T, K>`
get the type of property of an object at a given key `K`<br>
https://flow.org/en/docs/types/utilities/#toc-propertytype
**Usage:**
```ts
import { $PropertyType } from 'utility-types';
type Props = { name: string; age: number; visible: boolean };
// Expect: string
type NameType = $PropertyType<Props, 'name'>;
type Tuple = [boolean, number];
// Expect: boolean
type A = $PropertyType<Tuple, '0'>;
// Expect: number
type B = $PropertyType<Tuple, '1'>;
```
[โง back to top](#flows-utility-types)
### `$ElementType<T, K>`
get the type of elements inside of array, tuple or object of type `T`, that matches the given index type `K`<br>
https://flow.org/en/docs/types/utilities/#toc-elementtype
**Usage:**
```ts
import { $ElementType } from 'utility-types';
type Props = { name: string; age: number; visible: boolean };
// Expect: string
type NameType = $ElementType<Props, 'name'>;
type Tuple = [boolean, number];
// Expect: boolean
type A = $ElementType<Tuple, 0>;
// Expect: number
type B = $ElementType<Tuple, 1>;
type Arr = boolean[];
// Expect: boolean
type ItemsType = $ElementType<Arr, number>;
type Obj = { [key: string]: number };
// Expect: number
type ValuesType = $ElementType<Obj, string>;
```
[โง back to top](#flows-utility-types)
### `$Call<T>`
get the return type of a given expression type<br>
https://flow.org/en/docs/types/utilities/#toc-call
**Usage:**
```ts
import { $Call } from 'utility-types';
// Common use-case
const add = (amount: number) => ({ type: 'ADD' as 'ADD', payload: amount });
type AddAction = $Call<typeof returnOfIncrement>; // { type: 'ADD'; payload: number }
// Examples migrated from Flow docs
type ExtractPropType<T extends { prop: any }> = (arg: T) => T['prop'];
type Obj = { prop: number };
type PropType = $Call<ExtractPropType<Obj>>; // number
// type Nope = $Call<ExtractPropType<{ nope: number }>>; // Error: argument doesn't match `Obj`.
type ExtractReturnType<T extends () => any> = (arg: T) => ReturnType<T>;
type Fn = () => number;
type FnReturnType = $Call<ExtractReturnType<Fn>>; // number
```
[โง back to top](#flows-utility-types)
### `$Shape<T>`
Copies the shape of the type supplied, but marks every field optional.<br>
https://flow.org/en/docs/types/utilities/#toc-shape
**Usage:**
```ts
import { $Shape } from 'utility-types';
type Props = { name: string; age: number; visible: boolean };
// Expect: Partial<Props>
type PartialProps = $Shape<Props>;
```
[โง back to top](#flows-utility-types)
### `$NonMaybeType<T>`
Converts a type `T` to a non-maybe type. In other words, the values of `$NonMaybeType<T>` are the values of `T` except for `null` and `undefined`.<br>
https://flow.org/en/docs/types/utilities/#toc-nonmaybe
**Usage:**
```ts
import { $NonMaybeType } from 'utility-types';
type MaybeName = string | null;
// Expect: string
type Name = $NonMaybeType<MaybeName>;
```
[โง back to top](#flows-utility-types)
### `Class<T>`
Given a type T representing instances of a class C, the type Class<T> is the type of the class C<br>
https://flow.org/en/docs/types/utilities/#toc-class
\* Differs from original Flow's util - implements only constructor part and won't include any static members. Additionally classes in Typescript are not treated as nominal
**Usage:**
```ts
import { Class } from 'utility-types';
function makeStore(storeClass: Class<Store>): Store {
return new storeClass();
}
```
[โง back to top](#flows-utility-types)
### mixed
An arbitrary type that could be anything (same as `unknown`)<br>
https://flow.org/en/docs/types/mixed
[โง back to top](#table-of-contents)
---
## Related Projects
- [`ts-toolbelt`](https://github.com/pirix-gh/ts-toolbelt) - Higher type safety for TypeScript
- [`$mol_type`](https://github.com/eigenmethod/mol/tree/master/type) - Collection of TypeScript meta types for complex logic
---
## License
[MIT License](/LICENSE)
Copyright (c) 2016 Piotr Witek <mailto:[email protected]> (http://piotrwitek.github.io)
# yargs-parser

[](https://www.npmjs.com/package/yargs-parser)
[](https://conventionalcommits.org)

The mighty option parser used by [yargs](https://github.com/yargs/yargs).
visit the [yargs website](http://yargs.js.org/) for more examples, and thorough usage instructions.
<img width="250" src="https://raw.githubusercontent.com/yargs/yargs-parser/main/yargs-logo.png">
## Example
```sh
npm i yargs-parser --save
```
```js
const argv = require('yargs-parser')(process.argv.slice(2))
console.log(argv)
```
```console
$ node example.js --foo=33 --bar hello
{ _: [], foo: 33, bar: 'hello' }
```
_or parse a string!_
```js
const argv = require('yargs-parser')('--foo=99 --bar=33')
console.log(argv)
```
```console
{ _: [], foo: 99, bar: 33 }
```
Convert an array of mixed types before passing to `yargs-parser`:
```js
const parse = require('yargs-parser')
parse(['-f', 11, '--zoom', 55].join(' ')) // <-- array to string
parse(['-f', 11, '--zoom', 55].map(String)) // <-- array of strings
```
## Deno Example
As of `v19` `yargs-parser` supports [Deno](https://github.com/denoland/deno):
```typescript
import parser from "https://deno.land/x/yargs_parser/deno.ts";
const argv = parser('--foo=99 --bar=9987930', {
string: ['bar']
})
console.log(argv)
```
## ESM Example
As of `v19` `yargs-parser` supports ESM (_both in Node.js and in the browser_):
**Node.js:**
```js
import parser from 'yargs-parser'
const argv = parser('--foo=99 --bar=9987930', {
string: ['bar']
})
console.log(argv)
```
**Browsers:**
```html
<!doctype html>
<body>
<script type="module">
import parser from "https://unpkg.com/[email protected]/browser.js";
const argv = parser('--foo=99 --bar=9987930', {
string: ['bar']
})
console.log(argv)
</script>
</body>
```
## API
### parser(args, opts={})
Parses command line arguments returning a simple mapping of keys and values.
**expects:**
* `args`: a string or array of strings representing the options to parse.
* `opts`: provide a set of hints indicating how `args` should be parsed:
* `opts.alias`: an object representing the set of aliases for a key: `{alias: {foo: ['f']}}`.
* `opts.array`: indicate that keys should be parsed as an array: `{array: ['foo', 'bar']}`.<br>
Indicate that keys should be parsed as an array and coerced to booleans / numbers:<br>
`{array: [{ key: 'foo', boolean: true }, {key: 'bar', number: true}]}`.
* `opts.boolean`: arguments should be parsed as booleans: `{boolean: ['x', 'y']}`.
* `opts.coerce`: provide a custom synchronous function that returns a coerced value from the argument provided
(or throws an error). For arrays the function is called only once for the entire array:<br>
`{coerce: {foo: function (arg) {return modifiedArg}}}`.
* `opts.config`: indicate a key that represents a path to a configuration file (this file will be loaded and parsed).
* `opts.configObjects`: configuration objects to parse, their properties will be set as arguments:<br>
`{configObjects: [{'x': 5, 'y': 33}, {'z': 44}]}`.
* `opts.configuration`: provide configuration options to the yargs-parser (see: [configuration](#configuration)).
* `opts.count`: indicate a key that should be used as a counter, e.g., `-vvv` = `{v: 3}`.
* `opts.default`: provide default values for keys: `{default: {x: 33, y: 'hello world!'}}`.
* `opts.envPrefix`: environment variables (`process.env`) with the prefix provided should be parsed.
* `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`.
* `opts.normalize`: `path.normalize()` will be applied to values set to this key.
* `opts.number`: keys should be treated as numbers.
* `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`).
**returns:**
* `obj`: an object representing the parsed value of `args`
* `key/value`: key value pairs for each argument and their aliases.
* `_`: an array representing the positional arguments.
* [optional] `--`: an array with arguments after the end-of-options flag `--`.
### require('yargs-parser').detailed(args, opts={})
Parses a command line string, returning detailed information required by the
yargs engine.
**expects:**
* `args`: a string or array of strings representing options to parse.
* `opts`: provide a set of hints indicating how `args`, inputs are identical to `require('yargs-parser')(args, opts={})`.
**returns:**
* `argv`: an object representing the parsed value of `args`
* `key/value`: key value pairs for each argument and their aliases.
* `_`: an array representing the positional arguments.
* [optional] `--`: an array with arguments after the end-of-options flag `--`.
* `error`: populated with an error object if an exception occurred during parsing.
* `aliases`: the inferred list of aliases built by combining lists in `opts.alias`.
* `newAliases`: any new aliases added via camel-case expansion:
* `boolean`: `{ fooBar: true }`
* `defaulted`: any new argument created by `opts.default`, no aliases included.
* `boolean`: `{ foo: true }`
* `configuration`: given by default settings and `opts.configuration`.
<a name="configuration"></a>
### Configuration
The yargs-parser applies several automated transformations on the keys provided
in `args`. These features can be turned on and off using the `configuration` field
of `opts`.
```js
var parsed = parser(['--no-dice'], {
configuration: {
'boolean-negation': false
}
})
```
### short option groups
* default: `true`.
* key: `short-option-groups`.
Should a group of short-options be treated as boolean flags?
```console
$ node example.js -abc
{ _: [], a: true, b: true, c: true }
```
_if disabled:_
```console
$ node example.js -abc
{ _: [], abc: true }
```
### camel-case expansion
* default: `true`.
* key: `camel-case-expansion`.
Should hyphenated arguments be expanded into camel-case aliases?
```console
$ node example.js --foo-bar
{ _: [], 'foo-bar': true, fooBar: true }
```
_if disabled:_
```console
$ node example.js --foo-bar
{ _: [], 'foo-bar': true }
```
### dot-notation
* default: `true`
* key: `dot-notation`
Should keys that contain `.` be treated as objects?
```console
$ node example.js --foo.bar
{ _: [], foo: { bar: true } }
```
_if disabled:_
```console
$ node example.js --foo.bar
{ _: [], "foo.bar": true }
```
### parse numbers
* default: `true`
* key: `parse-numbers`
Should keys that look like numbers be treated as such?
```console
$ node example.js --foo=99.3
{ _: [], foo: 99.3 }
```
_if disabled:_
```console
$ node example.js --foo=99.3
{ _: [], foo: "99.3" }
```
### parse positional numbers
* default: `true`
* key: `parse-positional-numbers`
Should positional keys that look like numbers be treated as such.
```console
$ node example.js 99.3
{ _: [99.3] }
```
_if disabled:_
```console
$ node example.js 99.3
{ _: ['99.3'] }
```
### boolean negation
* default: `true`
* key: `boolean-negation`
Should variables prefixed with `--no` be treated as negations?
```console
$ node example.js --no-foo
{ _: [], foo: false }
```
_if disabled:_
```console
$ node example.js --no-foo
{ _: [], "no-foo": true }
```
### combine arrays
* default: `false`
* key: `combine-arrays`
Should arrays be combined when provided by both command line arguments and
a configuration file.
### duplicate arguments array
* default: `true`
* key: `duplicate-arguments-array`
Should arguments be coerced into an array when duplicated:
```console
$ node example.js -x 1 -x 2
{ _: [], x: [1, 2] }
```
_if disabled:_
```console
$ node example.js -x 1 -x 2
{ _: [], x: 2 }
```
### flatten duplicate arrays
* default: `true`
* key: `flatten-duplicate-arrays`
Should array arguments be coerced into a single array when duplicated:
```console
$ node example.js -x 1 2 -x 3 4
{ _: [], x: [1, 2, 3, 4] }
```
_if disabled:_
```console
$ node example.js -x 1 2 -x 3 4
{ _: [], x: [[1, 2], [3, 4]] }
```
### greedy arrays
* default: `true`
* key: `greedy-arrays`
Should arrays consume more than one positional argument following their flag.
```console
$ node example --arr 1 2
{ _: [], arr: [1, 2] }
```
_if disabled:_
```console
$ node example --arr 1 2
{ _: [2], arr: [1] }
```
**Note: in `v18.0.0` we are considering defaulting greedy arrays to `false`.**
### nargs eats options
* default: `false`
* key: `nargs-eats-options`
Should nargs consume dash options as well as positional arguments.
### negation prefix
* default: `no-`
* key: `negation-prefix`
The prefix to use for negated boolean variables.
```console
$ node example.js --no-foo
{ _: [], foo: false }
```
_if set to `quux`:_
```console
$ node example.js --quuxfoo
{ _: [], foo: false }
```
### populate --
* default: `false`.
* key: `populate--`
Should unparsed flags be stored in `--` or `_`.
_If disabled:_
```console
$ node example.js a -b -- x y
{ _: [ 'a', 'x', 'y' ], b: true }
```
_If enabled:_
```console
$ node example.js a -b -- x y
{ _: [ 'a' ], '--': [ 'x', 'y' ], b: true }
```
### set placeholder key
* default: `false`.
* key: `set-placeholder-key`.
Should a placeholder be added for keys not set via the corresponding CLI argument?
_If disabled:_
```console
$ node example.js -a 1 -c 2
{ _: [], a: 1, c: 2 }
```
_If enabled:_
```console
$ node example.js -a 1 -c 2
{ _: [], a: 1, b: undefined, c: 2 }
```
### halt at non-option
* default: `false`.
* key: `halt-at-non-option`.
Should parsing stop at the first positional argument? This is similar to how e.g. `ssh` parses its command line.
_If disabled:_
```console
$ node example.js -a run b -x y
{ _: [ 'b' ], a: 'run', x: 'y' }
```
_If enabled:_
```console
$ node example.js -a run b -x y
{ _: [ 'b', '-x', 'y' ], a: 'run' }
```
### strip aliased
* default: `false`
* key: `strip-aliased`
Should aliases be removed before returning results?
_If disabled:_
```console
$ node example.js --test-field 1
{ _: [], 'test-field': 1, testField: 1, 'test-alias': 1, testAlias: 1 }
```
_If enabled:_
```console
$ node example.js --test-field 1
{ _: [], 'test-field': 1, testField: 1 }
```
### strip dashed
* default: `false`
* key: `strip-dashed`
Should dashed keys be removed before returning results? This option has no effect if
`camel-case-expansion` is disabled.
_If disabled:_
```console
$ node example.js --test-field 1
{ _: [], 'test-field': 1, testField: 1 }
```
_If enabled:_
```console
$ node example.js --test-field 1
{ _: [], testField: 1 }
```
### unknown options as args
* default: `false`
* key: `unknown-options-as-args`
Should unknown options be treated like regular arguments? An unknown option is one that is not
configured in `opts`.
_If disabled_
```console
$ node example.js --unknown-option --known-option 2 --string-option --unknown-option2
{ _: [], unknownOption: true, knownOption: 2, stringOption: '', unknownOption2: true }
```
_If enabled_
```console
$ node example.js --unknown-option --known-option 2 --string-option --unknown-option2
{ _: ['--unknown-option'], knownOption: 2, stringOption: '--unknown-option2' }
```
## Supported Node.js Versions
Libraries in this ecosystem make a best effort to track
[Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a
post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a).
## Special Thanks
The yargs project evolves from optimist and minimist. It owes its
existence to a lot of James Halliday's hard work. Thanks [substack](https://github.com/substack) **beep** **boop** \o/
## License
ISC
# ansi-align
> align-text with ANSI support for CLIs
[](https://travis-ci.org/nexdrew/ansi-align)
[](https://coveralls.io/github/nexdrew/ansi-align?branch=master)
[](https://github.com/conventional-changelog/standard-version)
[](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
# node-gyp-build
> Build tool and bindings loader for [`node-gyp`][node-gyp] that supports prebuilds.
```
npm install node-gyp-build
```
[](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
# 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.
# JavaScript MD5
## Contents
- [Demo](https://blueimp.github.io/JavaScript-MD5/)
- [Description](#description)
- [Usage](#usage)
- [Client-side](#client-side)
- [Server-side](#server-side)
- [Requirements](#requirements)
- [API](#api)
- [Tests](#tests)
- [License](#license)
## Description
JavaScript [MD5](https://en.wikipedia.org/wiki/MD5) implementation.
Compatible with server-side environments like [Node.js](https://nodejs.org/),
module loaders like [RequireJS](https://requirejs.org/) or
[webpack](https://webpack.js.org/) and all web browsers.
## Usage
### Client-side
Install the **blueimp-md5** package with [NPM](https://www.npmjs.org/):
```sh
npm install blueimp-md5
```
Include the (minified) JavaScript [MD5](https://en.wikipedia.org/wiki/MD5)
script in your HTML markup:
```html
<script src="js/md5.min.js"></script>
```
In your application code, calculate the
([hex](https://en.wikipedia.org/wiki/Hexadecimal)-encoded)
[MD5](https://en.wikipedia.org/wiki/MD5) hash of a string by calling the **md5**
method with the string as argument:
```js
var hash = md5('value') // "2063c1608d6e0baf80249c42e2be5804"
```
### Server-side
The following is an example how to use the JavaScript MD5 module on the
server-side with [Node.js](https://nodejs.org/).
Install the **blueimp-md5** package with [NPM](https://www.npmjs.org/):
```sh
npm install blueimp-md5
```
Add a file **server.js** with the following content:
```js
require('http')
.createServer(function (req, res) {
// The md5 module exports the md5() function:
var md5 = require('./md5'),
// Use the following version if you installed the package with npm:
// var md5 = require("blueimp-md5"),
url = require('url'),
query = url.parse(req.url).query
res.writeHead(200, { 'Content-Type': 'text/plain' })
// Calculate and print the MD5 hash of the url query:
res.end(md5(query))
})
.listen(8080, 'localhost')
console.log('Server running at http://localhost:8080/')
```
Run the application with the following command:
```sh
node server.js
```
## Requirements
The JavaScript MD5 script has zero dependencies.
## API
Calculate the ([hex](https://en.wikipedia.org/wiki/Hexadecimal)-encoded)
[MD5](https://en.wikipedia.org/wiki/MD5) hash of a given string value:
```js
var hash = md5('value') // "2063c1608d6e0baf80249c42e2be5804"
```
Calculate the ([hex](https://en.wikipedia.org/wiki/Hexadecimal)-encoded)
[HMAC](https://en.wikipedia.org/wiki/HMAC)-MD5 hash of a given string value and
key:
```js
var hash = md5('value', 'key') // "01433efd5f16327ea4b31144572c67f6"
```
Calculate the raw [MD5](https://en.wikipedia.org/wiki/MD5) hash of a given
string value:
```js
var hash = md5('value', null, true)
```
Calculate the raw [HMAC](https://en.wikipedia.org/wiki/HMAC)-MD5 hash of a given
string value and key:
```js
var hash = md5('value', 'key', true)
```
## Tests
The JavaScript MD5 project comes with
[Unit Tests](https://en.wikipedia.org/wiki/Unit_testing).
There are two different ways to run the tests:
- Open test/index.html in your browser or
- run `npm test` in the Terminal in the root path of the repository package.
The first one tests the browser integration, the second one the
[Node.js](https://nodejs.org/) integration.
## License
The JavaScript MD5 script is released under the
[MIT license](https://opensource.org/licenses/MIT).
`core-js-compat` exposes some files as JSON, and they cannot be
imported by Node.js ESM files.
This folder proxies `core-js-compat` to ensure that every entry
is CJS and can be safely imported.
# 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.
<p align="center">
<img width="250" src="https://raw.githubusercontent.com/yargs/yargs/main/yargs-logo.png">
</p>
<h1 align="center"> Yargs </h1>
<p align="center">
<b >Yargs be a node.js library fer hearties tryin' ter parse optstrings</b>
</p>
<br>

[![NPM version][npm-image]][npm-url]
[![js-standard-style][standard-image]][standard-url]
[![Coverage][coverage-image]][coverage-url]
[![Conventional Commits][conventional-commits-image]][conventional-commits-url]
[![Slack][slack-image]][slack-url]
## Description
Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface.
It gives you:
* commands and (grouped) options (`my-program.js serve --port=5000`).
* a dynamically generated help menu based on your arguments:
```
mocha [spec..]
Run tests with Mocha
Commands
mocha inspect [spec..] Run tests with Mocha [default]
mocha init <path> create a client-side Mocha setup at <path>
Rules & Behavior
--allow-uncaught Allow uncaught errors to propagate [boolean]
--async-only, -A Require all tests to use a callback (async) or
return a Promise [boolean]
```
* bash-completion shortcuts for commands and options.
* and [tons more](/docs/api.md).
## Installation
Stable version:
```bash
npm i yargs
```
Bleeding edge version with the most recent features:
```bash
npm i yargs@next
```
## Usage
### Simple Example
```javascript
#!/usr/bin/env node
const yargs = require('yargs/yargs')
const { hideBin } = require('yargs/helpers')
const argv = yargs(hideBin(process.argv)).argv
if (argv.ships > 3 && argv.distance < 53.5) {
console.log('Plunder more riffiwobbles!')
} else {
console.log('Retreat from the xupptumblers!')
}
```
```bash
$ ./plunder.js --ships=4 --distance=22
Plunder more riffiwobbles!
$ ./plunder.js --ships 12 --distance 98.7
Retreat from the xupptumblers!
```
> Note: `hideBin` is a shorthand for [`process.argv.slice(2)`](https://nodejs.org/en/knowledge/command-line/how-to-parse-command-line-arguments/). It has the benefit that it takes into account variations in some environments, e.g., [Electron](https://github.com/electron/electron/issues/4690).
### Complex Example
```javascript
#!/usr/bin/env node
const yargs = require('yargs/yargs')
const { hideBin } = require('yargs/helpers')
yargs(hideBin(process.argv))
.command('serve [port]', 'start the server', (yargs) => {
return yargs
.positional('port', {
describe: 'port to bind on',
default: 5000
})
}, (argv) => {
if (argv.verbose) console.info(`start server on :${argv.port}`)
serve(argv.port)
})
.option('verbose', {
alias: 'v',
type: 'boolean',
description: 'Run with verbose logging'
})
.parse()
```
Run the example above with `--help` to see the help for the application.
## Supported Platforms
### TypeScript
yargs has type definitions at [@types/yargs][type-definitions].
```
npm i @types/yargs --save-dev
```
See usage examples in [docs](/docs/typescript.md).
### Deno
As of `v16`, `yargs` supports [Deno](https://github.com/denoland/deno):
```typescript
import yargs from 'https://deno.land/x/yargs/deno.ts'
import { Arguments } from 'https://deno.land/x/yargs/deno-types.ts'
yargs(Deno.args)
.command('download <files...>', 'download a list of files', (yargs: any) => {
return yargs.positional('files', {
describe: 'a list of files to do something with'
})
}, (argv: Arguments) => {
console.info(argv)
})
.strictCommands()
.demandCommand(1)
.parse()
```
### ESM
As of `v16`,`yargs` supports ESM imports:
```js
import yargs from 'yargs'
import { hideBin } from 'yargs/helpers'
yargs(hideBin(process.argv))
.command('curl <url>', 'fetch the contents of the URL', () => {}, (argv) => {
console.info(argv)
})
.demandCommand(1)
.parse()
```
### Usage in Browser
See examples of using yargs in the browser in [docs](/docs/browser.md).
## Community
Having problems? want to contribute? join our [community slack](http://devtoolscommunity.herokuapp.com).
## Documentation
### Table of Contents
* [Yargs' API](/docs/api.md)
* [Examples](/docs/examples.md)
* [Parsing Tricks](/docs/tricks.md)
* [Stop the Parser](/docs/tricks.md#stop)
* [Negating Boolean Arguments](/docs/tricks.md#negate)
* [Numbers](/docs/tricks.md#numbers)
* [Arrays](/docs/tricks.md#arrays)
* [Objects](/docs/tricks.md#objects)
* [Quotes](/docs/tricks.md#quotes)
* [Advanced Topics](/docs/advanced.md)
* [Composing Your App Using Commands](/docs/advanced.md#commands)
* [Building Configurable CLI Apps](/docs/advanced.md#configuration)
* [Customizing Yargs' Parser](/docs/advanced.md#customizing)
* [Bundling yargs](/docs/bundling.md)
* [Contributing](/contributing.md)
## Supported Node.js Versions
Libraries in this ecosystem make a best effort to track
[Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a
post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a).
[npm-url]: https://www.npmjs.com/package/yargs
[npm-image]: https://img.shields.io/npm/v/yargs.svg
[standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg
[standard-url]: http://standardjs.com/
[conventional-commits-image]: https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg
[conventional-commits-url]: https://conventionalcommits.org/
[slack-image]: http://devtoolscommunity.herokuapp.com/badge.svg
[slack-url]: http://devtoolscommunity.herokuapp.com
[type-definitions]: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yargs
[coverage-image]: https://img.shields.io/nycrc/yargs/yargs
[coverage-url]: https://github.com/yargs/yargs/blob/main/.nycrc
<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 mangler/compressor toolkit for ES6+.
*note*: You can support this project on patreon: <a target="_blank" rel="nofollow" href="https://www.patreon.com/fabiosantoscode"><img src="https://c5.patreon.com/external/logo/[email protected]" alt="patron" width="100px" height="auto"></a>. Check out [PATRONS.md](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://app.travis-ci.com/terser/terser.svg?branch=master
[travis-url]: https://app.travis-ci.com/github/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
<!-- CLI_USAGE:START -->
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.
Command line arguments that take options (like --parse, --compress, --mangle and
--format) can take in a comma-separated list of default option overrides. For
instance:
terser input.js --compress ecma=2015,computed_props=false
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.
-f, --format [options] Specify format 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 e.g. "@license",
or start with "!". 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 `format` 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 `format` 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.
--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.
<!-- CLI_USAGE:END -->
# API Reference
<!-- API_REFERENCE:START -->
Assuming installation via NPM, you can load Terser in your application
like this:
```javascript
const { minify } = require("terser");
```
Or,
```javascript
import { minify } from "terser";
```
Browser loading is also supported:
```html
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/source-map.js"></script>
<script src="https://cdn.jsdelivr.net/npm/terser/dist/bundle.min.js"></script>
```
There is a single async high level function, **`async minify(code, options)`**,
which will perform all minification [phases](#minify-options) in a configurable
manner. By default `minify()` will enable [`compress`](#compress-options)
and [`mangle`](#mangle-options). Example:
```javascript
var code = "function add(first, second) { return first + second; }";
var result = await minify(code, { sourceMap: true });
console.log(result.code); // minified output: function add(n,d){return n+d}
console.log(result.map); // source map
```
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 = await 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 = await minify(code, options);
console.log(result.code);
// console.log(3+7);
```
The `nameCache` option:
```javascript
var options = {
mangle: {
toplevel: true,
},
nameCache: {}
};
var result1 = await minify({
"file1.js": "function add(first, second) { return first + second; }"
}, options);
var result2 = await 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", await minify({
"file1.js": fs.readFileSync("file1.js", "utf8"),
"file2.js": fs.readFileSync("file2.js", "utf8")
}, options).code, "utf8");
fs.writeFileSync("part2.js", await 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
},
format: {
preamble: "/* minified */"
}
};
var result = await minify(code, options);
console.log(result.code);
// /* minified */
// alert(10);"
```
An error example:
```javascript
try {
const result = await minify({"foo.js" : "if (0) else console.log(1);"});
// Do something with result
} catch (error) {
const { message, filename, line, col, pos } = error;
// Do something with error
}
```
## Minify options
- `ecma` (default `undefined`) - pass `5`, `2015`, `2016`, etc to override
`compress` and `format`'s `ecma` options.
- `enclose` (default `false`) - pass `true`, or a string in the format
of `"args[:values]"`, where `args` and `values` are comma-separated
argument names and values, respectively, to embed the output in a big
function with the configurable arguments and values.
- `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.
- `format` or `output` (default `null`) โ pass an object if you wish to specify
additional [format options](#format-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 function 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 [`format`](#format-options) for details.
## Minify options structure
```javascript
{
parse: {
// parse options
},
compress: {
// compress options
},
mangle: {
// mangle options
properties: {
// mangle property options
}
},
format: {
// format options (can also use `output` for backwards compatibility)
},
sourceMap: {
// source map options
},
ecma: 5, // specify one of: 5, 2015, 2016, etc.
enclose: false, // or specify true, or "args:values"
keep_classnames: false,
keep_fnames: false,
ie8: false,
module: false,
nameCache: null, // or specify a name cache object
safari10: false,
toplevel: false
}
```
### Source map options
To generate a source map:
```javascript
var result = await 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 = await 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 = await 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
- `html5_comments` (default `true`)
- `shebang` (default `true`) -- support `#!command` as the first line
- `spidermonkey` (default `false`) -- accept a Spidermonkey (Mozilla) AST
## 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-options).
- `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-options).
- `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_vars` (default: `true`) -- Improve optimization on variables assigned with and
used as constant values.
- `reduce_funcs` (default: `true`) -- Inline single-use functions when
possible. Depends on `reduce_vars` being enabled. Disabling this option
sometimes improves performance of the output code.
- `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`) -- Remove expressions which have no side effects
and whose results aren't used.
- `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"`)
## 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 function 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`.
- `nth_identifier` (default: an internal mangler that weights based on character
frequency analysis) -- Pass an object with a `get(n)` function that converts an
ordinal into the nth most favored (usually shortest) identifier.
Optionally also provide `reset()`, `sort()`, and `consider(chars, delta)` to
use character frequency analysis of the source code.
- `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` [format option](#format-options).
Examples:
```javascript
// test.js
var globalVar;
function funcName(firstLongName, anotherLongName) {
var myVariable = firstLongName + anotherLongName;
}
```
```javascript
var code = fs.readFileSync("test.js", "utf8");
await minify(code).code;
// 'function funcName(a,n){}var globalVar;'
await minify(code, { mangle: { reserved: ['firstLongName'] } }).code;
// 'function funcName(firstLongName,a){}var globalVar;'
await 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`) โ How quoting properties (`{"prop": ...}` and `obj["prop"]`) controls what gets mangled.
- `"strict"` (recommended) -- `obj.prop` is mangled.
- `false` -- `obj["prop"]` is mangled.
- `true` -- `obj.prop` is mangled unless there is `obj["prop"]` elsewhere in the code.
- `nth_identifer` (default: an internal mangler that weights based on character
frequency analysis) -- Pass an object with a `get(n)` function that converts an
ordinal into the nth most favored (usually shortest) identifier.
Optionally also provide `reset()`, `sort()`, and `consider(chars, delta)` to
use character frequency analysis of the source code.
- `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.
## Format options
These options control the format of Terser's output code. Previously known
as "output options".
- `ascii_only` (default `false`) -- escape Unicode characters in strings and
regexps (affects directives with non-ascii characters becoming invalid)
- `beautify` (default `false`) -- (DEPRECATED) whether to beautify the output.
When using the legacy `-b` CLI flag, this is set to true by default.
- `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", "@copyright", "@preserve" or start with `!`, 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 desired EcmaScript standard version for output.
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 your input will
still be output as is. For example: an `ecma` setting of `5` will **not**
convert modern 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)
- `spidermonkey` (default `false`) -- produce a Spidermonkey (Mozilla) AST
- `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 comments starting with "!" and JSDoc-style comments that
contain "@preserve", "@copyright", "@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 ]`
- `Array.from([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`.
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 = await 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
await minify("alert('hello');", {
compress: {
global_defs: {
"@alert": "console.log"
}
}
}).code;
// returns: 'console.log("hello");'
```
Otherwise it would be replaced as string literal:
```javascript
await minify("alert('hello');", {
compress: {
global_defs: {
"alert": "console.log"
}
}
}).code;
// returns: '"console.log"("hello");'
```
### 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()
```
### 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.
`spidermonkey` is also available in `minify` as `parse` and `format` options to
accept and/or produce a spidermonkey AST.
### Use Acorn for parsing
More for fun, I added the `-p acorn` option which will use Acorn to do all
the parsing. If you pass this option, Terser will `require("acorn")`.
Acorn is really fast (e.g. 250ms instead of 380ms on some 650K code), but
converting the SpiderMonkey tree that Acorn produces takes another 150ms so
in total it's a bit more than just using Terser's own parser.
[acorn]: https://github.com/ternjs/acorn
[sm-spec]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k
### Terser Fast Minify Mode
It's not well known, but whitespace removal and symbol mangling accounts
for 95% of the size reduction in minified code for most JavaScript - not
elaborate code transforms. One can simply disable `compress` to speed up
Terser builds by 3 to 4 times.
| d3.js | size | gzip size | time (s) |
| --- | ---: | ---: | ---: |
| original | 451,131 | 108,733 | - |
| [email protected] mangle=false, compress=false | 316,600 | 85,245 | 0.82 |
| [email protected] mangle=true, compress=false | 220,216 | 72,730 | 1.45 |
| [email protected] mangle=true, compress=true | 212,046 | 70,954 | 5.87 |
| [email protected] | 210,713 | 72,140 | 12.64 |
| [email protected] | 210,321 | 72,242 | 48.67 |
| [email protected] | 210,421 | 72,238 | 14.17 |
To enable fast minify mode from the CLI use:
```
terser file.js -m
```
To enable fast minify mode with the API use:
```js
await 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
```
<!-- API_REFERENCE:END -->
# 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 help you write good issues.
## Obtaining the source code given to Terser
Because users often don't control the call to `await minify()` or its arguments, Terser provides a `TERSER_DEBUG_DIR` environment variable to make terser output some debug logs. If you're using a bundler or a project that includes a bundler and are not sure what went wrong with your code, pass that variable like so:
```
$ TERSER_DEBUG_DIR=/path/to/logs command-that-uses-terser
$ ls /path/to/logs
terser-debug-123456.log
```
If you're not sure how to set an environment variable on your shell (the above example works in bash), you can try using cross-env:
```
> npx cross-env TERSER_DEBUG_DIR=/path/to/logs command-that-uses-terser
```
# 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/[email protected]" 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 
* 38elements 
## 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>
# 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.
# md5.js
[](https://www.npmjs.org/package/md5.js)
[](https://travis-ci.org/crypto-browserify/md5.js)
[](https://david-dm.org/crypto-browserify/md5.js#info=dependencies)
[](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
# regjsgen [![Build status][ci-img]][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 10, 12, 14, and 16.<br>
Compatible with regjsparser v0.7.0โs AST.
[ci]: https://github.com/bnjmnt4n/regjsgen/actions
[ci-img]: https://github.com/bnjmnt4n/regjsgen/workflows/Node.js%20CI/badge.svg
[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
# emoji-regex [](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
| [](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.
# caniuse-lite
A smaller version of caniuse-db, with only the essentials!
## Why?
The full data behind [Can I use][1] is incredibly useful for any front end
developer, and on the website all of the details from the database are displayed
to the user. However in automated tools, [many of these fields go unused][2];
it's not a problem for server side consumption but client side, the less
JavaScript that we send to the end user the better.
caniuse-lite then, is a smaller dataset that keeps essential parts of the data
in a compact format. It does this in multiple ways, such as converting `null`
array entries into empty strings, representing support data as an integer rather
than a string, and using base62 references instead of longer human-readable
keys.
This packed data is then reassembled (via functions exposed by this module) into
a larger format which is mostly compatible with caniuse-db, and so it can be
used as an almost drop-in replacement for caniuse-db for contexts where size on
disk is important; for example, usage in web browsers. The API differences are
very small and are detailed in the section below.
## API
```js
import * as lite from 'caniuse-lite';
```
### `lite.agents`
caniuse-db provides a full `data.json` file which contains all of the features
data. Instead of this large file, caniuse-lite provides this data subset
instead, which has the `browser`, `prefix`, `prefix_exceptions`, `usage_global`
and `versions` keys from the original.
In addition, the subset contains the `release_date` key with release dates (as timestamps) for each version:
```json
{
"release_date": {
"6": 998870400,
"7": 1161129600,
"8": 1237420800,
"9": 1300060800,
"10": 1346716800,
"11": 1381968000,
"5.5": 962323200
}
}
```
### `lite.feature(js)`
The `feature` method takes a file from `data/features` and converts it into
something that more closely represents the `caniuse-db` format. Note that only
the `title`, `stats` and `status` keys are kept from the original data.
### `lite.features`
The `features` index is provided as a way to query all of the features that
are listed in the `caniuse-db` dataset. Note that you will need to use the
`feature` method on values from this index to get a human-readable format.
### `lite.region(js)`
The `region` method takes a file from `data/regions` and converts it into
something that more closely represents the `caniuse-db` format. Note that *only*
the usage data is exposed here (the `data` key in the original files).
## License
The data in this repo is available for use under a CC BY 4.0 license
(http://creativecommons.org/licenses/by/4.0/). For attribution just mention
somewhere that the source is caniuse.com. If you have any questions about using
the data for your project please contact me here: http://a.deveria.com/contact
[1]: http://caniuse.com/
[2]: https://github.com/Fyrd/caniuse/issues/1827
## Security contact information
To report a security vulnerability, please use the
[Tidelift security contact](https://tidelift.com/security).
Tidelift will coordinate the fix and disclosure.
<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
# color-convert
[](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 © 2011-2016, Heather Arthur and Josh Junon. Licensed under the [MIT License](LICENSE).
# has-symbols <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]
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]: https://versionbadg.es/inspect-js/has-symbols.svg
[5]: https://david-dm.org/inspect-js/has-symbols.svg
[6]: https://david-dm.org/inspect-js/has-symbols
[7]: https://david-dm.org/inspect-js/has-symbols/dev-status.svg
[8]: https://david-dm.org/inspect-js/has-symbols#info=devDependencies
[11]: https://nodei.co/npm/has-symbols.png?downloads=true&stars=true
[license-image]: https://img.shields.io/npm/l/has-symbols.svg
[license-url]: LICENSE
[downloads-image]: https://img.shields.io/npm/dm/has-symbols.svg
[downloads-url]: https://npm-stat.com/charts.html?package=has-symbols
[codecov-image]: https://codecov.io/gh/inspect-js/has-symbols/branch/main/graphs/badge.svg
[codecov-url]: https://app.codecov.io/gh/inspect-js/has-symbols/
[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/has-symbols
[actions-url]: https://github.com/inspect-js/has-symbols/actions
# isarray
`Array#isArray` for older browsers.
[](http://travis-ci.org/juliangruber/isarray)
[](https://www.npmjs.org/package/isarray)
[
](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 <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# responselike
> A response-like object for mocking a Node.js HTTP response stream
[](https://travis-ci.org/lukechilds/responselike)
[](https://coveralls.io/github/lukechilds/responselike?branch=master)
[](https://www.npmjs.com/package/responselike)
[](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
<!--
BEFORE EDITING THIS README
Our README.md is auto-generated by combining pages in website/docs and website/readme-sources
If you are sending a pull request to improve documentation, submit your changes
in the source markdown files and we will generate the README from there.
You can build the readme with this command:
cd website && yarn build-readme
-->
# [](https://typestrong.org/ts-node)
[](https://npmjs.org/package/ts-node)
[](https://npmjs.org/package/ts-node)
[](https://github.com/TypeStrong/ts-node/actions?query=workflow%3A%22Continuous+Integration%22)
[](https://codecov.io/gh/TypeStrong/ts-node)
> TypeScript execution and REPL for node.js, with source map and native ESM support.
The latest documentation can also be found on our website: <https://typestrong.org/ts-node>
# Table of Contents
* [Overview](#overview)
* [Features](#features)
* [Installation](#installation)
* [Usage](#usage)
* [Command Line](#command-line)
* [Shebang](#shebang)
* [node flags and other tools](#node-flags-and-other-tools)
* [Programmatic](#programmatic)
* [Configuration](#configuration)
* [CLI flags](#cli-flags)
* [Via tsconfig.json (recommended)](#via-tsconfigjson-recommended)
* [@tsconfig/bases](#tsconfigbases)
* [Default config](#default-config)
* [`node` flags](#node-flags)
* [Options](#options)
* [CLI Options](#cli-options)
* [help](#help)
* [version](#version)
* [eval](#eval)
* [print](#print)
* [interactive](#interactive)
* [esm](#esm)
* [TSConfig Options](#tsconfig-options)
* [project](#project)
* [skipProject](#skipproject)
* [cwdMode](#cwdmode)
* [compilerOptions](#compileroptions)
* [showConfig](#showconfig)
* [Typechecking](#typechecking)
* [transpileOnly](#transpileonly)
* [typeCheck](#typecheck)
* [compilerHost](#compilerhost)
* [files](#files)
* [ignoreDiagnostics](#ignorediagnostics)
* [Transpilation Options](#transpilation-options)
* [ignore](#ignore)
* [skipIgnore](#skipignore)
* [compiler](#compiler)
* [swc](#swc)
* [transpiler](#transpiler)
* [preferTsExts](#prefertsexts)
* [Diagnostic Options](#diagnostic-options)
* [logError](#logerror)
* [pretty](#pretty)
* [TS_NODE_DEBUG](#ts_node_debug)
* [Advanced Options](#advanced-options)
* [require](#require)
* [cwd](#cwd)
* [emit](#emit)
* [scope](#scope)
* [scopeDir](#scopedir)
* [moduleTypes](#moduletypes)
* [TS_NODE_HISTORY](#ts_node_history)
* [noExperimentalReplAwait](#noexperimentalreplawait)
* [experimentalResolver](#experimentalresolver)
* [experimentalSpecifierResolution](#experimentalspecifierresolution)
* [API Options](#api-options)
* [SWC](#swc-1)
* [CommonJS vs native ECMAScript modules](#commonjs-vs-native-ecmascript-modules)
* [CommonJS](#commonjs)
* [Native ECMAScript modules](#native-ecmascript-modules)
* [Troubleshooting](#troubleshooting)
* [Configuration](#configuration-1)
* [Common errors](#common-errors)
* [`TSError`](#tserror)
* [`SyntaxError`](#syntaxerror)
* [Unsupported JavaScript syntax](#unsupported-javascript-syntax)
* [`ERR_REQUIRE_ESM`](#err_require_esm)
* [`ERR_UNKNOWN_FILE_EXTENSION`](#err_unknown_file_extension)
* [Missing Types](#missing-types)
* [npx, yarn dlx, and node_modules](#npx-yarn-dlx-and-node_modules)
* [Performance](#performance)
* [Skip typechecking](#skip-typechecking)
* [With typechecking](#with-typechecking)
* [Advanced](#advanced)
* [How it works](#how-it-works)
* [Ignored files](#ignored-files)
* [File extensions](#file-extensions)
* [Skipping `node_modules`](#skipping-node_modules)
* [Skipping pre-compiled TypeScript](#skipping-pre-compiled-typescript)
* [Scope by directory](#scope-by-directory)
* [Ignore by regexp](#ignore-by-regexp)
* [paths and baseUrl
](#paths-and-baseurl)
* [Why is this not built-in to ts-node?](#why-is-this-not-built-in-to-ts-node)
* [Third-party compilers](#third-party-compilers)
* [Transpilers](#transpilers)
* [Third-party plugins](#third-party-plugins)
* [Write your own plugin](#write-your-own-plugin)
* [Module type overrides](#module-type-overrides)
* [Caveats](#caveats)
* [API](#api)
* [Recipes](#recipes)
* [Watching and restarting](#watching-and-restarting)
* [AVA](#ava)
* [CommonJS](#commonjs-1)
* [Native ECMAScript modules](#native-ecmascript-modules-1)
* [Gulp](#gulp)
* [IntelliJ and Webstorm](#intellij-and-webstorm)
* [Mocha](#mocha)
* [Mocha 7 and newer](#mocha-7-and-newer)
* [Mocha <=6](#mocha-6)
* [Tape](#tape)
* [Visual Studio Code](#visual-studio-code)
* [Other](#other)
* [License](#license)
# Overview
ts-node is a TypeScript execution engine and REPL for Node.js.
It JIT transforms TypeScript into JavaScript, enabling you to directly execute TypeScript on Node.js without precompiling.
This is accomplished by hooking node's module loading APIs, enabling it to be used seamlessly alongside other Node.js
tools and libraries.
## Features
* Automatic sourcemaps in stack traces
* Automatic `tsconfig.json` parsing
* Automatic defaults to match your node version
* Typechecking (optional)
* REPL
* Write standalone scripts
* Native ESM loader
* Use third-party transpilers
* Use custom transformers
* Integrate with test runners, debuggers, and CLI tools
* Compatible with pre-compilation for production

# Installation
```shell
# Locally in your project.
npm install -D typescript
npm install -D ts-node
# Or globally with TypeScript.
npm install -g typescript
npm install -g ts-node
# Depending on configuration, you may also need these
npm install -D tslib @types/node
```
**Tip:** Installing modules locally allows you to control and share the versions through `package.json`. ts-node will always resolve the compiler from `cwd` before checking relative to its own installation.
# Usage
## Command Line
```shell
# Execute a script as `node` + `tsc`.
ts-node script.ts
# Starts a TypeScript REPL.
ts-node
# Execute code with TypeScript.
ts-node -e 'console.log("Hello, world!")'
# Execute, and print, code with TypeScript.
ts-node -p -e '"Hello, world!"'
# Pipe scripts to execute with TypeScript.
echo 'console.log("Hello, world!")' | ts-node
# Equivalent to ts-node --transpileOnly
ts-node-transpile-only script.ts
# Equivalent to ts-node --cwdMode
ts-node-cwd script.ts
# Equivalent to ts-node --esm
ts-node-esm script.ts
```
## Shebang
To write scripts with maximum portability, [specify options in your `tsconfig.json`](#via-tsconfigjson-recommended) and omit them from the shebang.
```typescript twoslash
#!/usr/bin/env ts-node
// ts-node options are read from tsconfig.json
console.log("Hello, world!")
```
Including options within the shebang requires the [`env -S` flag](https://manpages.debian.org/bullseye/coreutils/env.1.en.html#S), which is available on recent versions of `env`. ([compatibility](https://github.com/TypeStrong/ts-node/pull/1448#issuecomment-913895766))
```typescript twoslash
#!/usr/bin/env -S ts-node --files
// This shebang works on Mac and Linux with newer versions of env
// Technically, Mac allows omitting `-S`, but Linux requires it
```
To test your version of `env` for compatibility with `-S`:
```shell
# Note that these unusual quotes are necessary
/usr/bin/env --debug '-S echo foo bar'
```
## node flags and other tools
You can register ts-node without using our CLI: `node -r ts-node/register` and `node --loader ts-node/esm`
In many cases, setting [`NODE_OPTIONS`](https://nodejs.org/api/cli.html#cli_node_options_options) will enable `ts-node` within other node tools, child processes, and worker threads. This can be combined with other node flags.
```shell
NODE_OPTIONS="-r ts-node/register --no-warnings" node ./index.ts
```
Or, if you require native ESM support:
```shell
NODE_OPTIONS="--loader ts-node/esm"
```
This tells any node processes which receive this environment variable to install `ts-node`'s hooks before executing other code.
If you are invoking node directly, you can avoid the environment variable and pass those flags to node.
```shell
node --loader ts-node/esm --inspect ./index.ts
```
## Programmatic
You can require ts-node and register the loader for future requires by using `require('ts-node').register({ /* options */ })`.
Check out our [API](#api) for more features.
# Configuration
ts-node supports a variety of options which can be specified via `tsconfig.json`, as CLI flags, as environment variables, or programmatically.
For a complete list, see [Options](#options).
## CLI flags
ts-node CLI flags must come *before* the entrypoint script. For example:
```shell
$ ts-node --project tsconfig-dev.json say-hello.ts Ronald
Hello, Ronald!
```
## Via tsconfig.json (recommended)
ts-node automatically finds and loads `tsconfig.json`. Most ts-node options can be specified in a `"ts-node"` object using their programmatic, camelCase names. We recommend this because it works even when you cannot pass CLI flags, such as `node --require ts-node/register` and when using shebangs.
Use `--skipProject` to skip loading the `tsconfig.json`. Use `--project` to explicitly specify the path to a `tsconfig.json`.
When searching, it is resolved using [the same search behavior as `tsc`](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html). By default, this search is performed relative to the entrypoint script. In `--cwdMode` or if no entrypoint is specified -- for example when using the REPL -- the search is performed relative to `--cwd` / `process.cwd()`.
You can use this sample configuration as a starting point:
```jsonc title="tsconfig.json"
{
// This is an alias to @tsconfig/node16: https://github.com/tsconfig/bases
"extends": "ts-node/node16/tsconfig.json",
// Most ts-node options can be specified here using their programmatic names.
"ts-node": {
// It is faster to skip typechecking.
// Remove if you want ts-node to do typechecking.
"transpileOnly": true,
"files": true,
"compilerOptions": {
// compilerOptions specified here will override those declared below,
// but *only* in ts-node. Useful if you want ts-node and tsc to use
// different options with a single tsconfig.json.
}
},
"compilerOptions": {
// typescript options here
}
}
```
Our bundled [JSON schema](https://unpkg.com/browse/ts-node@latest/tsconfig.schema.json) lists all compatible options.
### @tsconfig/bases
[@tsconfig/bases](https://github.com/tsconfig/bases) maintains recommended configurations for several node versions.
As a convenience, these are bundled with ts-node.
```jsonc title="tsconfig.json"
{
"extends": "ts-node/node16/tsconfig.json",
// Or install directly with `npm i -D @tsconfig/node16`
"extends": "@tsconfig/node16/tsconfig.json",
}
```
### Default config
If no `tsconfig.json` is loaded from disk, ts-node will use the newest recommended defaults from
[@tsconfig/bases](https://github.com/tsconfig/bases/) compatible with your `node` and `typescript` versions.
With the latest `node` and `typescript`, this is [`@tsconfig/node16`](https://github.com/tsconfig/bases/blob/master/bases/node16.json).
Older versions of `typescript` are incompatible with `@tsconfig/node16`. In those cases we will use an older default configuration.
When in doubt, `ts-node --showConfig` will log the configuration being used, and `ts-node -vv` will log `node` and `typescript` versions.
## `node` flags
[`node` flags](https://nodejs.org/api/cli.html) must be passed directly to `node`; they cannot be passed to the ts-node binary nor can they be specified in `tsconfig.json`
We recommend using the [`NODE_OPTIONS`](https://nodejs.org/api/cli.html#cli_node_options_options) environment variable to pass options to `node`.
```shell
NODE_OPTIONS='--trace-deprecation --abort-on-uncaught-exception' ts-node ./index.ts
```
Alternatively, you can invoke `node` directly and install ts-node via `--require`/`-r`
```shell
node --trace-deprecation --abort-on-uncaught-exception -r ts-node/register ./index.ts
```
# Options
All command-line flags support both `--camelCase` and `--hyphen-case`.
Most options can be declared in your tsconfig.json: [Configuration via tsconfig.json](#via-tsconfigjson-recommended)
`ts-node` supports `--print` (`-p`), `--eval` (`-e`), `--require` (`-r`) and `--interactive` (`-i`) similar to the [node.js CLI](https://nodejs.org/api/cli.html).
`ts-node` supports `--project` and `--showConfig` similar to the [tsc CLI](https://www.typescriptlang.org/docs/handbook/compiler-options.html#compiler-options).
*Environment variables, where available, are in `ALL_CAPS`*
## CLI Options
### help
```shell
ts-node --help
```
Prints the help text
### version
```shell
ts-node -v
ts-node -vvv
```
Prints the version. `-vv` includes node and typescript compiler versions. `-vvv` includes absolute paths to ts-node and
typescript installations.
### eval
```shell
ts-node -e <typescript code>
# Example
ts-node -e 'console.log("Hello world!")'
```
Evaluate code
### print
```shell
ts-node -p -e <typescript code>
# Example
ts-node -p -e '"Hello world!"'
```
Print result of `--eval`
### interactive
```shell
ts-node -i
```
Opens the REPL even if stdin does not appear to be a terminal
### esm
```shell
ts-node --esm
ts-node-esm
```
Bootstrap with the ESM loader, enabling full ESM support
## TSConfig Options
### project
```shell
ts-node -P <path/to/tsconfig>
ts-node --project <path/to/tsconfig>
```
Path to tsconfig file.
*Note the uppercase `-P`. This is different from `tsc`'s `-p/--project` option.*
*Environment:* `TS_NODE_PROJECT`
### skipProject
```shell
ts-node --skipProject
```
Skip project config resolution and loading
*Default:* `false` <br/>
*Environment:* `TS_NODE_SKIP_PROJECT`
### cwdMode
```shell
ts-node -c
ts-node --cwdMode
ts-node-cwd
```
Resolve config relative to the current directory instead of the directory of the entrypoint script
### compilerOptions
```shell
ts-node -O <json compilerOptions>
ts-node --compilerOptions <json compilerOptions>
```
JSON object to merge with compiler options
*Environment:* `TS_NODE_COMPILER_OPTIONS`
### showConfig
```shell
ts-node --showConfig
```
Print resolved `tsconfig.json`, including `ts-node` options, and exit
## Typechecking
### transpileOnly
```shell
ts-node -T
ts-node --transpileOnly
```
Use TypeScript's faster `transpileModule`
*Default:* `false`<br/>
*Environment:* `TS_NODE_TRANSPILE_ONLY`
### typeCheck
```shell
ts-node --typeCheck
```
Opposite of `--transpileOnly`
*Default:* `true`<br/>
*Environment:* `TS_NODE_TYPE_CHECK`
### compilerHost
```shell
ts-node -H
ts-node --compilerHost
```
Use TypeScript's compiler host API
*Default:* `false` <br/>
*Environment:* `TS_NODE_COMPILER_HOST`
### files
```shell
ts-node --files
```
Load `files`, `include` and `exclude` from `tsconfig.json` on startup. This may
avoid certain typechecking failures. See [Missing types](#missing-types) for details.
*Default:* `false` <br/>
*Environment:* `TS_NODE_FILES`
### ignoreDiagnostics
```shell
ts-node -D <code,code>
ts-node --ignoreDiagnostics <code,code>
```
Ignore TypeScript warnings by diagnostic code
*Environment:* `TS_NODE_IGNORE_DIAGNOSTICS`
## Transpilation Options
### ignore
```shell
ts-node -I <regexp matching ignored files>
ts-node --ignore <regexp matching ignored files>
```
Override the path patterns to skip compilation
*Default:* `/node_modules/` <br/>
*Environment:* `TS_NODE_IGNORE`
### skipIgnore
```shell
ts-node --skipIgnore
```
Skip ignore checks
*Default:* `false` <br/>
*Environment:* `TS_NODE_SKIP_IGNORE`
### compiler
```shell
ts-node -C <name>
ts-node --compiler <name>
```
Specify a custom TypeScript compiler
*Default:* `typescript` <br/>
*Environment:* `TS_NODE_COMPILER`
### swc
```shell
ts-node --swc
```
Transpile with [swc](#swc). Implies `--transpileOnly`
*Default:* `false`
### transpiler
```shell
ts-node --transpiler <name>
# Example
ts-node --transpiler ts-node/transpilers/swc
```
Use a third-party, non-typechecking transpiler
### preferTsExts
```shell
ts-node --preferTsExts
```
Re-order file extensions so that TypeScript imports are preferred
*Default:* `false` <br/>
*Environment:* `TS_NODE_PREFER_TS_EXTS`
## Diagnostic Options
### logError
```shell
ts-node --logError
```
Logs TypeScript errors to stderr instead of throwing exceptions
*Default:* `false` <br/>
*Environment:* `TS_NODE_LOG_ERROR`
### pretty
```shell
ts-node --pretty
```
Use pretty diagnostic formatter
*Default:* `false` <br/>
*Environment:* `TS_NODE_PRETTY`
### TS_NODE_DEBUG
```shell
TS_NODE_DEBUG=true ts-node
```
Enable debug logging
## Advanced Options
### require
```shell
ts-node -r <module name or path>
ts-node --require <module name or path>
```
Require a node module before execution
### cwd
```shell
ts-node --cwd <path/to/directory>
```
Behave as if invoked in this working directory
*Default:* `process.cwd()`<br/>
*Environment:* `TS_NODE_CWD`
### emit
```shell
ts-node --emit
```
Emit output files into `.ts-node` directory. Requires `--compilerHost`
*Default:* `false` <br/>
*Environment:* `TS_NODE_EMIT`
### scope
```shell
ts-node --scope
```
Scope compiler to files within `scopeDir`. Anything outside this directory is ignored.
*Default:* `false` <br/>
*Environment:* `TS_NODE_SCOPE`
### scopeDir
```shell
ts-node --scopeDir <path/to/directory>
```
Directory within which compiler is limited when `scope` is enabled.
*Default:* First of: `tsconfig.json` "rootDir" if specified, directory containing `tsconfig.json`, or cwd if no `tsconfig.json` is loaded.<br/>
*Environment:* `TS_NODE_SCOPE_DIR`
### moduleTypes
Override the module type of certain files, ignoring the `package.json` `"type"` field. See [Module type overrides](#module-type-overrides) for details.
*Default:* obeys `package.json` `"type"` and `tsconfig.json` `"module"` <br/>
*Can only be specified via `tsconfig.json` or API.*
### TS_NODE_HISTORY
```shell
TS_NODE_HISTORY=<path/to/history/file> ts-node
```
Path to history file for REPL
*Default:* `~/.ts_node_repl_history`
### noExperimentalReplAwait
```shell
ts-node --noExperimentalReplAwait
```
Disable top-level await in REPL. Equivalent to node's [`--no-experimental-repl-await`](https://nodejs.org/api/cli.html#cli_no_experimental_repl_await)
*Default:* Enabled if TypeScript version is 3.8 or higher and target is ES2018 or higher.<br/>
*Environment:* `TS_NODE_EXPERIMENTAL_REPL_AWAIT` set `false` to disable
### experimentalResolver
Enable experimental hooks that re-map imports and require calls to support:
* remapping extensions, e.g. so that `import "./foo.js"` will execute `foo.ts`. Currently the following extensions will be mapped:
* `.js` to `.ts`, `.tsx`, or `.jsx`
* `.cjs` to `.cts`
* `.mjs` to `.mts`
* `.jsx` to `.tsx`
* including file extensions in CommonJS, for consistency with ESM where this is often mandatory
In the future, this hook will also support:
* `baseUrl`, `paths`
* `rootDirs`
* `outDir` to `rootDir` mappings for composite projects and monorepos
For details, see [#1514](https://github.com/TypeStrong/ts-node/issues/1514).
*Default:* `false`, but will likely be enabled by default in a future version<br/>
*Can only be specified via `tsconfig.json` or API.*
### experimentalSpecifierResolution
```shell
ts-node --experimentalSpecifierResolution node
```
Like node's [`--experimental-specifier-resolution`](https://nodejs.org/dist/latest-v18.x/docs/api/esm.html#customizing-esm-specifier-resolution-algorithm), but can also be set in your `tsconfig.json` for convenience.
Requires [`esm`](#esm) to be enabled.
*Default:* `explicit`<br/>
## API Options
The API includes [additional options](https://typestrong.org/ts-node/api/interfaces/RegisterOptions.html) not shown here.
# SWC
SWC support is built-in via the `--swc` flag or `"swc": true` tsconfig option.
[SWC](https://swc.rs) is a TypeScript-compatible transpiler implemented in Rust. This makes it an order of magnitude faster than vanilla `transpileOnly`.
To use it, first install `@swc/core` or `@swc/wasm`. If using `importHelpers`, also install `@swc/helpers`. If `target` is less than "es2015" and using `async`/`await` or generator functions, also install `regenerator-runtime`.
```shell
npm i -D @swc/core @swc/helpers regenerator-runtime
```
Then add the following to your `tsconfig.json`.
```jsonc title="tsconfig.json"
{
"ts-node": {
"swc": true
}
}
```
> SWC uses `@swc/helpers` instead of `tslib`. If you have enabled `importHelpers`, you must also install `@swc/helpers`.
# CommonJS vs native ECMAScript modules
TypeScript is almost always written using modern `import` syntax, but it is also transformed before being executed by the underlying runtime. You can choose to either transform to CommonJS or to preserve the native `import` syntax, using node's native ESM support. Configuration is different for each.
Here is a brief comparison of the two.
| CommonJS | Native ECMAScript modules |
|---|---|
| Write native `import` syntax | Write native `import` syntax |
| Transforms `import` into `require()` | Does not transform `import` |
| Node executes scripts using the classic [CommonJS loader](https://nodejs.org/dist/latest-v16.x/docs/api/modules.html) | Node executes scripts using the new [ESM loader](https://nodejs.org/dist/latest-v16.x/docs/api/esm.html) |
| Use any of:<br/>`ts-node`<br/>`node -r ts-node/register`<br/>`NODE_OPTIONS="ts-node/register" node`<br/>`require('ts-node').register({/* options */})` | Use any of:<br/>`ts-node --esm`<br/>`ts-node-esm`<br/>Set `"esm": true` in `tsconfig.json`<br />`node --loader ts-node/esm`<br/>`NODE_OPTIONS="--loader ts-node/esm" node` |
## CommonJS
Transforming to CommonJS is typically simpler and more widely supported because it is older. You must remove [`"type": "module"`](https://nodejs.org/api/packages.html#packages_type) from `package.json` and set [`"module": "CommonJS"`](https://www.typescriptlang.org/tsconfig/#module) in `tsconfig.json`.
```jsonc title="package.json"
{
// This can be omitted; commonjs is the default
"type": "commonjs"
}
```
```jsonc title="tsconfig.json"
{
"compilerOptions": {
"module": "CommonJS"
}
}
```
If you must keep `"module": "ESNext"` for `tsc`, webpack, or another build tool, you can set an override for ts-node.
```jsonc title="tsconfig.json"
{
"compilerOptions": {
"module": "ESNext"
},
"ts-node": {
"compilerOptions": {
"module": "CommonJS"
}
}
}
```
## Native ECMAScript modules
[Node's ESM loader hooks](https://nodejs.org/api/esm.html#esm_experimental_loaders) are [**experimental**](https://nodejs.org/api/documentation.html#documentation_stability_index) and subject to change. ts-node's ESM support is as stable as possible, but it relies on APIs which node can *and will* break in new versions of node. Thus it is not recommended for production.
For complete usage, limitations, and to provide feedback, see [#1007](https://github.com/TypeStrong/ts-node/issues/1007).
You must set [`"type": "module"`](https://nodejs.org/api/packages.html#packages_type) in `package.json` and [`"module": "ESNext"`](https://www.typescriptlang.org/tsconfig/#module) in `tsconfig.json`.
```jsonc title="package.json"
{
"type": "module"
}
```
```jsonc title="tsconfig.json"
{
"compilerOptions": {
"module": "ESNext" // or ES2015, ES2020
},
"ts-node": {
// Tell ts-node CLI to install the --loader automatically, explained below
"esm": true
}
}
```
You must also ensure node is passed `--loader`. The ts-node CLI will do this automatically with our `esm` option.
> Note: `--esm` must spawn a child process to pass it `--loader`. This may change if node adds the ability to install loader hooks
> into the current process.
```shell
# pass the flag
ts-node --esm
# Use the convenience binary
ts-node-esm
# or add `"esm": true` to your tsconfig.json to make it automatic
ts-node
```
If you are not using our CLI, pass the loader flag to node.
```shell
node --loader ts-node/esm ./index.ts
# Or via environment variable
NODE_OPTIONS="--loader ts-node/esm" node ./index.ts
```
# Troubleshooting
## Configuration
ts-node uses sensible default configurations to reduce boilerplate while still respecting `tsconfig.json` if you
have one. If you are unsure which configuration is used, you can log it with `ts-node --showConfig`. This is similar to
`tsc --showConfig` but includes `"ts-node"` options as well.
ts-node also respects your locally-installed `typescript` version, but global installations fallback to the globally-installed
`typescript`. If you are unsure which versions are used, `ts-node -vv` will log them.
```shell
$ ts-node -vv
ts-node v10.0.0
node v16.1.0
compiler v4.2.2
$ ts-node --showConfig
{
"compilerOptions": {
"target": "es6",
"lib": [
"es6",
"dom"
],
"rootDir": "./src",
"outDir": "./.ts-node",
"module": "commonjs",
"moduleResolution": "node",
"strict": true,
"declaration": false,
"sourceMap": true,
"inlineSources": true,
"types": [
"node"
],
"stripInternal": true,
"incremental": true,
"skipLibCheck": true,
"importsNotUsedAsValues": "error",
"inlineSourceMap": false,
"noEmit": false
},
"ts-node": {
"cwd": "/d/project",
"projectSearchDir": "/d/project",
"require": [],
"project": "/d/project/tsconfig.json"
}
}
```
## Common errors
It is important to differentiate between errors from ts-node, errors from the TypeScript compiler, and errors from `node`. It is also important to understand when errors are caused by a type error in your code, a bug in your code, or a flaw in your configuration.
### `TSError`
Type errors from the compiler are thrown as a `TSError`. These are the same as errors you get from `tsc`.
### `SyntaxError`
Any error that is not a `TSError` is from node.js (e.g. `SyntaxError`), and cannot be fixed by TypeScript or ts-node. These are bugs in your code or configuration.
#### Unsupported JavaScript syntax
Your version of `node` may not support all JavaScript syntax supported by TypeScript. The compiler must transform this syntax via "downleveling," which is controlled by
the [tsconfig `"target"` option](https://www.typescriptlang.org/tsconfig#target). Otherwise your code will compile fine, but node will throw a `SyntaxError`.
For example, `node` 12 does not understand the `?.` optional chaining operator. If you use `"target": "esnext"`, then the following TypeScript syntax:
```typescript twoslash
const bar: string | undefined = foo?.bar;
```
will compile into this JavaScript:
```javascript
const a = foo?.bar;
```
When you try to run this code, node 12 will throw a `SyntaxError`. To fix this, you must switch to `"target": "es2019"` or lower so TypeScript transforms `?.` into something `node` can understand.
### `ERR_REQUIRE_ESM`
This error is thrown by node when a module is `require()`d, but node believes it should execute as native ESM. This can happen for a few reasons:
* You have installed an ESM dependency but your own code compiles to CommonJS.
* Solution: configure your project to compile and execute as native ESM. [Docs](#native-ecmascript-modules)
* Solution: downgrade the dependency to an older, CommonJS version.
* You have moved your project to ESM but still have a config file, such as `webpack.config.ts`, which must be executed as CommonJS <!-- SYNC_WITH_MTO_DOCS -->
* Solution: if supported by the relevant tool, rename your config file to `.cts`
* Solution: Configure a module type override. [Docs](#module-type-overrides)
* You have a mix of CommonJS and native ESM in your project
* Solution: double-check all package.json "type" and tsconfig.json "module" configuration [Docs](#commonjs-vs-native-ecmascript-modules)
* Solution: consider simplifying by making your project entirely CommonJS or entirely native ESM
### `ERR_UNKNOWN_FILE_EXTENSION`
This error is thrown by node when a module has an unrecognized file extension, or no extension at all, and is being executed as native ESM. This can happen for a few reasons:
* You are using a tool which has an extensionless binary, such as `mocha`.
* CommonJS supports extensionless files but native ESM does not.
* Solution: upgrade to ts-node >=[v10.6.0](https://github.com/TypeStrong/ts-node/releases/tag/v10.6.0), which implements a workaround.
* Our ESM loader is not installed.
* Solution: Use `ts-node-esm`, `ts-node --esm`, or add `"ts-node": {"esm": true}` to your tsconfig.json. [Docs](#native-ecmascript-modules)
* You have moved your project to ESM but still have a config file, such as `webpack.config.ts`, which must be executed as CommonJS <!-- SYNC_WITH_MTO_DOCS -->
* Solution: if supported by the relevant tool, rename your config file to `.cts`
* Solution: Configure a module type override. [Docs](#module-type-overrides)
## Missing Types
ts-node does *not* eagerly load `files`, `include` or `exclude` by default. This is because a large majority of projects do not use all of the files in a project directory (e.g. `Gulpfile.ts`, runtime vs tests) and parsing every file for types slows startup time. Instead, ts-node starts with the script file (e.g. `ts-node index.ts`) and TypeScript resolves dependencies based on imports and references.
Occasionally, this optimization leads to missing types. Fortunately, there are other ways to include them in typechecking.
For global definitions, you can use the `typeRoots` compiler option. This requires that your type definitions be structured as type packages (not loose TypeScript definition files). More details on how this works can be found in the [TypeScript Handbook](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types).
Example `tsconfig.json`:
```jsonc
{
"compilerOptions": {
"typeRoots" : ["./node_modules/@types", "./typings"]
}
}
```
Example project structure:
```text
<project_root>/
-- tsconfig.json
-- typings/
-- <module_name>/
-- index.d.ts
```
Example module declaration file:
```typescript twoslash
declare module '<module_name>' {
// module definitions go here
}
```
For module definitions, you can use [`paths`](https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping):
```jsonc title="tsconfig.json"
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"custom-module-type": ["types/custom-module-type"]
}
}
}
```
Another option is [triple-slash directives](https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html). This may be helpful if you prefer not to change your `compilerOptions` or structure your type definitions for `typeRoots`. Below is an example of a triple-slash directive as a relative path within your project:
```typescript twoslash
/// <reference path="./types/lib_greeter" />
import {Greeter} from "lib_greeter"
const g = new Greeter();
g.sayHello();
```
If none of the above work, and you *must* use `files`, `include`, or `exclude`, enable our [`files`](#files) option.
## npx, yarn dlx, and node_modules
When executing TypeScript with `npx` or `yarn dlx`, the code resides within a temporary `node_modules` directory.
The contents of `node_modules` are ignored by default. If execution fails, enable [`skipIgnore`](#skipignore).
<!--See also: [npx and yarn dlx](./recipes/npx-and-yarn-dlx.md)-->
# Performance
These tricks will make ts-node faster.
## Skip typechecking
It is often better to use `tsc --noEmit` to typecheck as part of your tests or linting. In these cases, ts-node can skip typechecking.
* Enable [swc](#swc)
* This is by far the fastest option
* Enable [`transpileOnly`](#transpileonly) to skip typechecking without swc
## With typechecking
* Avoid dynamic `require()` which may trigger repeated typechecking; prefer `import`
* Try with and without `--files`; one may be faster depending on your project
* Check `tsc --showConfig`; make sure all executed files are included
* Enable [`skipLibCheck`](https://www.typescriptlang.org/tsconfig#skipLibCheck)
* Set a [`types`](https://www.typescriptlang.org/tsconfig#types) array to avoid loading unnecessary `@types`
# Advanced
## How it works
ts-node works by registering hooks for `.ts`, `.tsx`, `.js`, and/or `.jsx` extensions.
Vanilla `node` loads `.js` by reading code from disk and executing it. Our hook runs in the middle, transforming code from TypeScript to JavaScript and passing the result to `node` for execution. This transformation will respect your `tsconfig.json` as if you had compiled via `tsc`.
We also register a few other hooks to apply sourcemaps to stack traces and remap from `.js` imports to `.ts`.
## Ignored files
ts-node transforms certain files and ignores others. We refer to this mechanism as "scoping." There are various
options to configure scoping, so that ts-node transforms only the files in your project.
> **Warning:**
>
> An ignored file can still be executed by node.js. Ignoring a file means we do not transform it from TypeScript into JavaScript, but it does not prevent execution.
>
> If a file requires transformation but is ignored, node may either fail to resolve it or attempt to execute it as vanilla JavaScript. This may cause syntax errors or other failures, because node does not understand TypeScript type syntax nor bleeding-edge ECMAScript features.
### File extensions
`.js` and `.jsx` are only transformed when [`allowJs`](https://www.typescriptlang.org/docs/handbook/compiler-options.html#compiler-options) is enabled.
`.tsx` and `.jsx` are only transformed when [`jsx`](https://www.typescriptlang.org/docs/handbook/jsx.html) is enabled.
> **Warning:**
>
> When ts-node is used with `allowJs`, *all* non-ignored JavaScript files are transformed by ts-node.
### Skipping `node_modules`
By default, ts-node avoids compiling files in `/node_modules/` for three reasons:
1. Modules should always be published in a format node.js can consume
2. Transpiling the entire dependency tree will make your project slower
3. Differing behaviours between TypeScript and node.js (e.g. ES2015 modules) can result in a project that works until you decide to support a feature natively from node.js
If you need to import uncompiled TypeScript in `node_modules`, use [`--skipIgnore`](#skipignore) or [`TS_NODE_SKIP_IGNORE`](#skipignore) to bypass this restriction.
### Skipping pre-compiled TypeScript
If a compiled JavaScript file with the same name as a TypeScript file already exists, the TypeScript file will be ignored. ts-node will import the pre-compiled JavaScript.
To force ts-node to import the TypeScript source, not the precompiled JavaScript, use [`--preferTsExts`](#prefertsexts).
### Scope by directory
Our [`scope`](#scope) and [`scopeDir`](#scopedir) options will limit transformation to files
within a directory.
### Ignore by regexp
Our [`ignore`](#ignore) option will ignore files matching one or more regular expressions.
## paths and baseUrl

You can use ts-node together with [tsconfig-paths](https://www.npmjs.com/package/tsconfig-paths) to load modules according to the `paths` section in `tsconfig.json`.
```jsonc title="tsconfig.json"
{
"ts-node": {
// Do not forget to `npm i -D tsconfig-paths`
"require": ["tsconfig-paths/register"]
}
}
```
### Why is this not built-in to ts-node?
The official TypeScript Handbook explains the intended purpose for `"paths"` in ["Additional module resolution flags"](https://www.typescriptlang.org/docs/handbook/module-resolution.html#additional-module-resolution-flags).
> The TypeScript compiler has a set of additional flags to *inform* the compiler of transformations that are expected to happen to the sources to generate the final output.
>
> It is important to note that the compiler will not perform any of these transformations; it just uses these pieces of information to guide the process of resolving a module import to its definition file.
This means `"paths"` are intended to describe mappings that the build tool or runtime *already* performs, not to tell the build tool or
runtime how to resolve modules. In other words, they intend us to write our imports in a way `node` already understands. For this reason, ts-node does not modify `node`'s module resolution behavior to implement `"paths"` mappings.
## Third-party compilers
Some projects require a patched typescript compiler which adds additional features. For example, [`ttypescript`](https://github.com/cevek/ttypescript/tree/master/packages/ttypescript) and [`ts-patch`](https://github.com/nonara/ts-patch#readme)
add the ability to configure custom transformers. These are drop-in replacements for the vanilla `typescript` module and
implement the same API.
For example, to use `ttypescript` and `ts-transformer-keys`, add this to your `tsconfig.json`:
```jsonc title="tsconfig.json"
{
"ts-node": {
// This can be omitted when using ts-patch
"compiler": "ttypescript"
},
"compilerOptions": {
// plugin configuration is the same for both ts-patch and ttypescript
"plugins": [
{ "transform": "ts-transformer-keys/transformer" }
]
}
}
```
## Transpilers
ts-node supports third-party transpilers as plugins. Transpilers such as swc can transform TypeScript into JavaScript
much faster than the TypeScript compiler. You will still benefit from ts-node's automatic `tsconfig.json` discovery,
sourcemap support, and global ts-node CLI. Plugins automatically derive an appropriate configuration from your existing
`tsconfig.json` which simplifies project boilerplate.
> **What is the difference between a compiler and a transpiler?**
>
> For our purposes, a compiler implements TypeScript's API and can perform typechecking.
> A third-party transpiler does not. Both transform TypeScript into JavaScript.
### Third-party plugins
The `transpiler` option allows using third-party transpiler plugins with ts-node. `transpiler` must be given the
name of a module which can be `require()`d. The built-in `swc` plugin is exposed as `ts-node/transpilers/swc`.
For example, to use a hypothetical "@cspotcode/fast-ts-compiler", first install it into your project: `npm install @cspotcode/fast-ts-compiler`
Then add the following to your tsconfig:
```jsonc title="tsconfig.json"
{
"ts-node": {
"transpileOnly": true,
"transpiler": "@cspotcode/fast-ts-compiler"
}
}
```
### Write your own plugin
To write your own transpiler plugin, check our [API docs](https://typestrong.org/ts-node/api/interfaces/TranspilerModule.html).
Plugins are `require()`d by ts-node, so they can be a local script or a node module published to npm. The module must
export a `create` function described by our
[`TranspilerModule`](https://typestrong.org/ts-node/api/interfaces/TranspilerModule.html) interface. `create` is
invoked by ts-node at startup to create one or more transpiler instances. The instances are used to transform
TypeScript into JavaScript.
For a working example, check out out our bundled swc plugin: https://github.com/TypeStrong/ts-node/blob/main/src/transpilers/swc.ts
## Module type overrides
> Wherever possible, it is recommended to use TypeScript's [`NodeNext` or `Node16` mode](https://www.typescriptlang.org/docs/handbook/esm-node.html) instead of the options described
> in this section. Setting `"module": "NodeNext"` and using the `.cts` file extension should work well for most projects.
When deciding how a file should be compiled and executed -- as either CommonJS or native ECMAScript module -- ts-node matches
`node` and `tsc` behavior. This means TypeScript files are transformed according to your `tsconfig.json` `"module"`
option and executed according to node's rules for the `package.json` `"type"` field. Set `"module": "NodeNext"` and everything should work.
In rare cases, you may need to override this behavior for some files. For example, some tools read a `name-of-tool.config.ts`
and require that file to execute as CommonJS. If you have `package.json` configured with `"type": "module"` and `tsconfig.json` with
`"module": "esnext"`, the config is native ECMAScript by default and will raise an error. You will need to force the config and
any supporting scripts to execute as CommonJS.
In these situations, our `moduleTypes` option can override certain files to be
CommonJS or ESM. Similar overriding is possible by using `.mts`, `.cts`, `.cjs` and `.mjs` file extensions.
`moduleTypes` achieves the same effect for `.ts` and `.js` files, and *also* overrides your `tsconfig.json` `"module"`
config appropriately.
The following example tells ts-node to execute a webpack config as CommonJS:
```jsonc title="tsconfig.json"
{
"ts-node": {
"transpileOnly": true,
"moduleTypes": {
"webpack.config.ts": "cjs",
// Globs are also supported with the same behavior as tsconfig "include"
"webpack-config-scripts/**/*": "cjs"
}
},
"compilerOptions": {
"module": "es2020",
"target": "es2020"
}
}
```
Each key is a glob pattern with the same syntax as tsconfig's `"include"` array.
When multiple patterns match the same file, the last pattern takes precedence.
* `cjs` overrides matches files to compile and execute as CommonJS.
* `esm` overrides matches files to compile and execute as native ECMAScript modules.
* `package` resets either of the above to default behavior, which obeys `package.json` `"type"` and `tsconfig.json` `"module"` options.
### Caveats
Files with an overridden module type are transformed with the same limitations as [`isolatedModules`](https://www.typescriptlang.org/tsconfig#isolatedModules). This will only affect rare cases such as using `const enum`s with [`preserveConstEnums`](https://www.typescriptlang.org/tsconfig#preserveConstEnums) disabled.
This feature is meant to facilitate scenarios where normal `compilerOptions` and `package.json` configuration is not possible. For example, a `webpack.config.ts` cannot be given its own `package.json` to override `"type"`. Wherever possible you should favor using traditional `package.json` and `tsconfig.json` configurations.
## API
ts-node's complete API is documented here: [API Docs](https://typestrong.org/ts-node/api/)
Here are a few highlights of what you can accomplish:
* [`create()`](https://typestrong.org/ts-node/api/index.html#create) creates ts-node's compiler service without
registering any hooks.
* [`createRepl()`](https://typestrong.org/ts-node/api/index.html#createRepl) creates an instance of our REPL service, so
you can create your own TypeScript-powered REPLs.
* [`createEsmHooks()`](https://typestrong.org/ts-node/api/index.html#createEsmHooks) creates our ESM loader hooks,
suitable for composing with other loaders or augmenting with additional features.
# Recipes
## Watching and restarting
ts-node focuses on adding first-class TypeScript support to node. Watching files and code reloads are out of scope for the project.
If you want to restart the `ts-node` process on file change, existing node.js tools such as [nodemon](https://github.com/remy/nodemon), [onchange](https://github.com/Qard/onchange) and [node-dev](https://github.com/fgnass/node-dev) work.
There's also [`ts-node-dev`](https://github.com/whitecolor/ts-node-dev), a modified version of [`node-dev`](https://github.com/fgnass/node-dev) using `ts-node` for compilation that will restart the process on file change. Note that `ts-node-dev` is incompatible with our native ESM loader.
## AVA
Assuming you are configuring AVA via your `package.json`, add one of the following configurations.
### CommonJS
Use this configuration if your `package.json` does not have `"type": "module"`.
```jsonc title="package.json"
{
"ava": {
"extensions": [
"ts"
],
"require": [
"ts-node/register"
]
}
}
```
### Native ECMAScript modules
This configuration is necessary if your `package.json` has `"type": "module"`.
```jsonc title="package.json"
{
"ava": {
"extensions": {
"ts": "module"
},
"nonSemVerExperiments": {
"configurableModuleFormat": true
},
"nodeArguments": [
"--loader=ts-node/esm"
]
}
}
```
## Gulp
ts-node support is built-in to gulp.
```sh
# Create a `gulpfile.ts` and run `gulp`.
gulp
```
See also: https://gulpjs.com/docs/en/getting-started/javascript-and-gulpfiles#transpilation
## IntelliJ and Webstorm
Create a new Node.js configuration and add `-r ts-node/register` to "Node parameters."
**Note:** If you are using the `--project <tsconfig.json>` command line argument as per the [Configuration Options](#configuration), and want to apply this same behavior when launching in IntelliJ, specify under "Environment Variables": `TS_NODE_PROJECT=<tsconfig.json>`.
## Mocha
### Mocha 7 and newer
```shell
mocha --require ts-node/register --extensions ts,tsx --watch --watch-files src 'tests/**/*.{ts,tsx}' [...args]
```
Or specify options via your mocha config file.
```jsonc title=".mocharc.json"
{
// Specify "require" for CommonJS
"require": "ts-node/register",
// Specify "loader" for native ESM
"loader": "ts-node/esm",
"extensions": ["ts", "tsx"],
"spec": [
"tests/**/*.spec.*"
],
"watch-files": [
"src"
]
}
```
See also: https://mochajs.org/#configuring-mocha-nodejs
### Mocha <=6
```shell
mocha --require ts-node/register --watch-extensions ts,tsx "test/**/*.{ts,tsx}" [...args]
```
**Note:** `--watch-extensions` is only used in `--watch` mode.
## Tape
```shell
ts-node node_modules/tape/bin/tape [...args]
```
## Visual Studio Code
Create a new Node.js debug configuration, add `-r ts-node/register` to node args and move the `program` to the `args` list (so VS Code doesn't look for `outFiles`).
```jsonc title=".vscode/launch.json"
{
"configurations": [{
"type": "node",
"request": "launch",
"name": "Launch Program",
"runtimeArgs": [
"-r",
"ts-node/register"
],
"args": [
"${workspaceFolder}/src/index.ts"
]
}],
}
```
**Note:** If you are using the `--project <tsconfig.json>` command line argument as per the [Configuration Options](#configuration), and want to apply this same behavior when launching in VS Code, add an "env" key into the launch configuration: `"env": { "TS_NODE_PROJECT": "<tsconfig.json>" }`.
## Other
In many cases, setting [`NODE_OPTIONS`](https://nodejs.org/api/cli.html#cli_node_options_options) will enable `ts-node` within other node tools, child processes, and worker threads.
```shell
NODE_OPTIONS="-r ts-node/register"
```
Or, if you require native ESM support:
```shell
NODE_OPTIONS="--loader ts-node/esm"
```
This tells any node processes which receive this environment variable to install `ts-node`'s hooks before executing other code.
# License
ts-node is licensed under the MIT license. [MIT](https://github.com/TypeStrong/ts-node/blob/main/LICENSE)
ts-node includes source code from Node.js which is licensed under the MIT license. [Node.js license information](https://raw.githubusercontent.com/nodejs/node/master/LICENSE)
ts-node includes source code from the TypeScript compiler which is licensed under the Apache License 2.0. [TypeScript license information](https://github.com/microsoft/TypeScript/blob/master/LICENSE.txt)
# 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).
# minimatch
A minimal matching utility.
[](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.
# Regenerate [](https://travis-ci.org/mathiasbynens/regenerate) [](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
```
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
| [](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.
# Website
This website is built using [Docusaurus 2](https://docusaurus.io/), a modern static website generator.
## Installation
```console
yarn install
```
## Local Development
```console
yarn start
```
This command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server.
## Build
```console
yarn build
```
This command generates static content into the `build` directory and can be served using any static contents hosting service.
## Deployment
```console
GIT_USER=<Your GitHub username> USE_SSH=true yarn deploy
```
If you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch.
# queue-microtask [![ci][ci-image]][ci-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url]
[ci-image]: https://img.shields.io/github/workflow/status/feross/queue-microtask/ci/master
[ci-url]: https://github.com/feross/queue-microtask/actions
[npm-image]: https://img.shields.io/npm/v/queue-microtask.svg
[npm-url]: https://npmjs.org/package/queue-microtask
[downloads-image]: https://img.shields.io/npm/dm/queue-microtask.svg
[downloads-url]: https://npmjs.org/package/queue-microtask
[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg
[standard-url]: https://standardjs.com
### fast, tiny [`queueMicrotask`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/queueMicrotask) shim for modern engines
- Use [`queueMicrotask`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/queueMicrotask) in all modern JS engines.
- No dependencies. Less than 10 lines. No shims or complicated fallbacks.
- Optimal performance in all modern environments
- Uses `queueMicrotask` in modern environments
- Fallback to `Promise.resolve().then(fn)` in Node.js 10 and earlier, and old browsers (same performance as `queueMicrotask`)
## install
```
npm install queue-microtask
```
## usage
```js
const queueMicrotask = require('queue-microtask')
queueMicrotask(() => { /* this will run soon */ })
```
## What is `queueMicrotask` and why would one use it?
The `queueMicrotask` function is a WHATWG standard. It queues a microtask to be executed prior to control returning to the event loop.
A microtask is a short function which will run after the current task has completed its work and when there is no other code waiting to be run before control of the execution context is returned to the event loop.
The code `queueMicrotask(fn)` is equivalent to the code `Promise.resolve().then(fn)`. It is also very similar to [`process.nextTick(fn)`](https://nodejs.org/api/process.html#process_process_nexttick_callback_args) in Node.
Using microtasks lets code run without interfering with any other, potentially higher priority, code that is pending, but before the JS engine regains control over the execution context.
See the [spec](https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#microtask-queuing) or [Node documentation](https://nodejs.org/api/globals.html#globals_queuemicrotask_callback) for more information.
## Who is this package for?
This package allows you to use `queueMicrotask` safely in all modern JS engines. Use it if you prioritize small JS bundle size over support for old browsers.
If you just need to support Node 12 and later, use `queueMicrotask` directly. If you need to support all versions of Node, use this package.
## Why not use `process.nextTick`?
In Node, `queueMicrotask` and `process.nextTick` are [essentially equivalent](https://nodejs.org/api/globals.html#globals_queuemicrotask_callback), though there are [subtle differences](https://github.com/YuzuJS/setImmediate#macrotasks-and-microtasks) that don't matter in most situations.
You can think of `queueMicrotask` as a standardized version of `process.nextTick` that works in the browser. No need to rely on your browser bundler to shim `process` for the browser environment.
## Why not use `setTimeout(fn, 0)`?
This approach is the most compatible, but it has problems. Modern browsers throttle timers severely, so `setTimeout(โฆ, 0)` usually takes at least 4ms to run. Furthermore, the throttling gets even worse if the page is backgrounded. If you have many `setTimeout` calls, then this can severely limit the performance of your program.
## Why not use a microtask library like [`immediate`](https://www.npmjs.com/package/immediate) or [`asap`](https://www.npmjs.com/package/asap)?
These packages are great! However, if you prioritize small JS bundle size over optimal performance in old browsers then you may want to consider this package.
This package (`queue-microtask`) is four times smaller than `immediate`, twice as small as `asap`, and twice as small as using `process.nextTick` and letting the browser bundler shim it automatically.
Note: This package throws an exception in JS environments which lack `Promise` support -- which are usually very old browsers and Node.js versions.
Since the `queueMicrotask` API is supported in Node.js, Chrome, Firefox, Safari, Opera, and Edge, **the vast majority of users will get optimal performance**. Any JS environment with `Promise`, which is almost all of them, also get optimal performance. If you need support for JS environments which lack `Promise` support, use one of the alternative packages.
## What is a shim?
> In computer programming, a shim is a library that transparently intercepts API calls and changes the arguments passed, handles the operation itself or redirects the operation elsewhere. โ [Wikipedia](https://en.wikipedia.org/wiki/Shim_(computing))
This package could also be described as a "ponyfill".
> A ponyfill is almost the same as a polyfill, but not quite. Instead of patching functionality for older browsers, a ponyfill provides that functionality as a standalone module you can use. โ [PonyFoo](https://ponyfoo.com/articles/polyfills-or-ponyfills)
## API
### `queueMicrotask(fn)`
The `queueMicrotask()` method queues a microtask.
The `fn` argument is a function to be executed after all pending tasks have completed but before yielding control to the browser's event loop.
## license
MIT. Copyright (c) [Feross Aboukhadijeh](https://feross.org).
near-blank-project 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`.
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
# htmlparser2
[](https://npmjs.org/package/htmlparser2)
[](https://npmjs.org/package/htmlparser2)
[](https://github.com/fb55/htmlparser2/actions?query=workflow%3A%22Node.js+Test%22)
[](https://coveralls.io/r/fb55/htmlparser2)
The fast & forgiving HTML/XML parser.
## Installation
npm install htmlparser2
A live demo of `htmlparser2` is available [here](https://astexplorer.net/#/2AmVrGuGVJ).
## Ecosystem
| Name | Description |
| ------------------------------------------------------------- | ------------------------------------------------------- |
| [htmlparser2](https://github.com/fb55/htmlparser2) | Fast & forgiving HTML/XML parser |
| [domhandler](https://github.com/fb55/domhandler) | Handler for htmlparser2 that turns documents into a DOM |
| [domutils](https://github.com/fb55/domutils) | Utilities for working with domhandler's DOM |
| [css-select](https://github.com/fb55/css-select) | CSS selector engine, compatible with domhandler's DOM |
| [cheerio](https://github.com/cheeriojs/cheerio) | The jQuery API for domhandler's DOM |
| [dom-serializer](https://github.com/cheeriojs/dom-serializer) | Serializer for domhandler's DOM |
## Usage
`htmlparser2` itself provides a callback interface that allows consumption of documents with minimal allocations.
For a more ergonomic experience, read [Getting a DOM](#getting-a-dom) below.
```javascript
const htmlparser2 = require("htmlparser2");
const parser = new htmlparser2.Parser({
onopentag(name, attributes) {
/*
* This fires when a new tag is opened.
*
* If you don't need an aggregated `attributes` object,
* have a look at the `onopentagname` and `onattribute` events.
*/
if (name === "script" && attributes.type === "text/javascript") {
console.log("JS! Hooray!");
}
},
ontext(text) {
/*
* Fires whenever a section of text was processed.
*
* Note that this can fire at any point within text and you might
* have to stich together multiple pieces.
*/
console.log("-->", text);
},
onclosetag(tagname) {
/*
* Fires when a tag is closed.
*
* You can rely on this event only firing when you have received an
* equivalent opening tag before. Closing tags without corresponding
* opening tags will be ignored.
*/
if (tagname === "script") {
console.log("That's it?!");
}
},
});
parser.write(
"Xyz <script type='text/javascript'>const foo = '<<bar>>';</ script>"
);
parser.end();
```
Output (with multiple text events combined):
```
--> Xyz
JS! Hooray!
--> const foo = '<<bar>>';
That's it?!
```
This example only shows three of the possible events.
Read more about the parser, its events and options in the [wiki](https://github.com/fb55/htmlparser2/wiki/Parser-options).
### Usage with streams
While the `Parser` interface closely resembles Node.js streams, it's not a 100% match.
Use the `WritableStream` interface to process a streaming input:
```javascript
const { WritableStream } = require("htmlparser2/lib/WritableStream");
const parserStream = new WritableStream({
ontext(text) {
console.log("Streaming:", text);
},
});
const htmlStream = fs.createReadStream("./my-file.html");
htmlStream.pipe(parserStream).on("finish", () => console.log("done"));
```
## Getting a DOM
The `DomHandler` produces a DOM (document object model) that can be manipulated using the [`DomUtils`](https://github.com/fb55/DomUtils) helper.
```js
const htmlparser2 = require("htmlparser2");
const dom = htmlparser2.parseDocument(htmlString);
```
The `DomHandler`, while still bundled with this module, was moved to its [own module](https://github.com/fb55/domhandler).
Have a look at that for further information.
## Parsing RSS/RDF/Atom Feeds
```javascript
const feed = htmlparser2.parseFeed(content, options);
```
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 GitHub Actions (sourced from [here](https://github.com/AndreasMadsen/htmlparser-benchmark/blob/e78cd8fc6c2adac08deedd4f274c33537451186b/stats.txt)):
```
htmlparser2 : 2.17215 ms/file ยฑ 3.81587
node-html-parser : 2.35983 ms/file ยฑ 1.54487
html5parser : 2.43468 ms/file ยฑ 2.81501
neutron-html5parser: 2.61356 ms/file ยฑ 1.70324
htmlparser2-dom : 3.09034 ms/file ยฑ 4.77033
html-dom-parser : 3.56804 ms/file ยฑ 5.15621
libxmljs : 4.07490 ms/file ยฑ 2.99869
htmljs-parser : 6.15812 ms/file ยฑ 7.52497
parse5 : 9.70406 ms/file ยฑ 6.74872
htmlparser : 15.0596 ms/file ยฑ 89.0826
html-parser : 28.6282 ms/file ยฑ 22.6652
saxes : 45.7921 ms/file ยฑ 128.691
html5 : 120.844 ms/file ยฑ 153.944
```
## How does this module differ from [node-htmlparser](https://github.com/tautologistics/node-htmlparser)?
In 2011, this module started as a fork of the `htmlparser` module.
`htmlparser2` was rewritten multiple times and, while it maintains an API that's mostly compatible with `htmlparser` in most cases, the projects don't share any code anymore.
The parser now provides a callback interface inspired by [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.
## 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.
## `htmlparser2` for enterprise
Available as part of the Tidelift Subscription
The maintainers of `htmlparser2` 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-htmlparser2?utm_source=npm-htmlparser2&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
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.
# micromatch [](https://www.npmjs.com/package/micromatch) [](https://npmjs.org/package/micromatch) [](https://npmjs.org/package/micromatch) [](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._
# signal-exit
[](https://travis-ci.org/tapjs/signal-exit)
[](https://coveralls.io/r/tapjs/signal-exit?branch=master)
[](https://www.npmjs.com/package/signal-exit)
[](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.
# is-typedarray [](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
[](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.
# msgpackr
[](https://www.npmjs.org/package/msgpackr)
[](https://www.npmjs.org/package/msgpackr)
[](benchmark.md)
[](benchmark.md)
[](README.md)
[](README.md)
[](LICENSE)
<img align="right" src="./assets/performance.png" width="380"/>
The msgpackr package is an extremely fast MessagePack NodeJS/JavaScript implementation. Currently, it is significantly faster than any other known implementations, faster than Avro (for JS), and generally faster than native V8 JSON.stringify/parse, on NodeJS. It also includes an optional record extension (the `r` in msgpackr), for defining record structures that makes MessagePack even faster and more compact, often over twice as fast as even native JSON functions, several times faster than other JS implementations, and 15-50% more compact. See the performance section for more details. Structured cloning (with support for cyclical references) is also supported through optional extensions.
## Basic Usage
Install with:
```
npm i msgpackr
```
And `import` or `require` it for basic standard serialization/encoding (`pack`) and deserialization/decoding (`unpack`) functions:
```js
import { unpack, pack } from 'msgpackr';
let serializedAsBuffer = pack(value);
let data = unpack(serializedAsBuffer);
```
This `pack` function will generate standard MessagePack without any extensions that should be compatible with any standard MessagePack parser/decoder. It will serialize JavaScript objects as MessagePack `map`s by default. The `unpack` function will deserialize MessagePack `map`s as an `Object` with the properties from the map.
## Node Usage
The msgpackr package runs on any modern JS platform, but is optimized for NodeJS usage (and will use a node addon for performance boost as an optional dependency).
### Streams
We can use the including streaming functionality (which further improves performance). The `PackrStream` is a NodeJS transform stream that can be used to serialize objects to a binary stream (writing to network/socket, IPC, etc.), and the `UnpackrStream` can be used to deserialize objects from a binary sream (reading from network/socket, etc.):
```js
import { PackrStream } from 'msgpackr';
let stream = new PackrStream();
stream.write(myData);
```
Or for a full example of sending and receiving data on a stream:
```js
import { PackrStream } from 'msgpackr';
let sendingStream = new PackrStream();
let receivingStream = new UnpackrStream();
// we are just piping to our own stream, but normally you would send and
// receive over some type of inter-process or network connection.
sendingStream.pipe(receivingStream);
sendingStream.write(myData);
receivingStream.on('data', (data) => {
// received data
});
```
The `PackrStream` and `UnpackrStream` instances will have also the record structure extension enabled by default (see below).
## Deno Usage
Msgpackr modules are standard ESM modules and can be loaded directly from the [deno.land registry for msgpackr](https://deno.land/x/msgpackr) for use in Deno. The standard pack/encode and unpack/decode functionality is available on Deno, like other platforms.
## Browser Usage
Msgpackr works as standalone JavaScript as well, and runs on modern browsers. It includes a bundled script, at `dist/index.js` for ease of direct loading:
```html
<script src="node_modules/msgpackr/dist/index.js"></script>
```
This is UMD based, and will register as a module if possible, or create a `msgpackr` global with all the exported functions.
For module-based development, it is recommended that you directly import the module of interest, to minimize dependencies that get pulled into your application:
```js
import { unpack } from 'msgpackr/unpack' // if you only need to unpack
```
## Structured Cloning
You can also use msgpackr for [structured cloning](https://html.spec.whatwg.org/multipage/structured-data.html). By enabling the `structuredClone` option, you can include references to other objects or cyclic references, and object identity will be preserved. Structured cloning also enables preserving certain typed objects like `Error`, `Set`, `RegExp` and TypedArray instances. For example:
```js
let obj = {
set: new Set(['a', 'b']),
regular: /a\spattern/
};
obj.self = obj;
let packr = new Packr({ structuredClone: true });
let serialized = packr.pack(obj);
let copy = packr.unpack(serialized);
copy.self === copy // true
copy.set.has('a') // true
```
This option is disabled by default because it uses extensions and reference checking degrades performance (by about 25-30%). (Note this implementation doesn't serialize every class/type specified in the HTML specification since not all of them make sense for storing across platforms.)
### Alternate Terminology
If you prefer to use encoder/decode terminology, msgpackr exports aliases, so `decode` is equivalent to `unpack`, `encode` is `pack`, `Encoder` is `Packr`, `Decoder` is `Unpackr`, and `EncoderStream` and `DecoderStream` can be used as well.
## Record / Object Structures
There is a critical difference between maps (or dictionaries) that hold an arbitrary set of keys and values (JavaScript `Map` is designed for these), and records or object structures that have a well-defined set of fields. Typical JS objects/records may have many instances re(use) the same structure. By using the record extension, this distinction is preserved in MessagePack and the encoding can reuse structures and not only provides better type preservation, but yield much more compact encodings and increase decoding performance by 2-3x. Msgpackr automatically generates record definitions that are reused and referenced by objects with the same structure. There are a number of ways to use this to our advantage. For large object structures with repeating nested objects with similar structures, simply serializing with the record extension can yield significant benefits. To use the record structures extension, we create a new `Packr` instance. By default a new `Packr` instance will have the record extension enabled:
```js
import { Packr } from 'msgpackr';
let packr = new Packr();
packr.pack(bigDataWithLotsOfObjects);
```
Another way to further leverage the benefits of the msgpackr record structures is to use streams that naturally allow for data to reuse based on previous record structures. The stream classes have the record structure extension enabled by default and provide excellent out-of-the-box performance.
When creating a new `Packr`, `Unpackr`, `PackrStream`, or `UnpackrStream` instance, we can enable or disable the record structure extension with the `useRecords` property. When this is `false`, the record structure extension will be disabled (standard/compatibility mode), and all objects will revert to being serialized using MessageMap `map`s, and all `map`s will be deserialized to JS `Object`s as properties (like the standalone `pack` and `unpack` functions).
Streaming with record structures works by encoding a structure the first time it is seen in a stream and referencing the structure in later messages that are sent across that stream. When an encoder can expect a decoder to understand previous structure references, this can be configured using the `sequential: true` flag, which is auto-enabled by streams, but can also be used with Packr instances.
### Shared Record Structures
Another useful way of using msgpackr, and the record extension, is for storing data in a databases, files, or other storage systems. If a number of objects with common data structures are being stored, a shared structure can be used to greatly improve data storage and deserialization efficiency. In the simplest form, provide a `structures` array, which is updated if any new object structure is encountered:
```js
import { Packr } from 'msgpackr';
let packr = new Packr({
structures: [... structures that were last generated ...]
});
```
If you are working with persisted data, you will need to persist the `structures` data when it is updated. Msgpackr provides an API for loading and saving the `structures` on demand (which is robust and can be used in multiple-process situations where other processes may be updating this same `structures` array), we just need to provide a way to store the generated shared structure so it is available to deserialize stored data in the future:
```js
import { Packr } from 'msgpackr';
let packr = new Packr({
getStructures() {
// storing our data in file (but we could also store in a db or key-value store)
return unpack(readFileSync('my-shared-structures.mp')) || [];
},
saveStructures(structures) {
writeFileSync('my-shared-structures.mp', pack(structures));
}
});
```
Msgpackr will automatically add and saves structures as it encounters any new object structures (up to a limit of 32, by default). It will always add structures in an incremental/compatible way: Any object encoded with an earlier structure can be decoded with a later version (as long as it is persisted).
#### Shared Structures Options
By default there is a limit of 32 shared structures. This default is designed to record common shared structures, but also be resilient against sharing too many structures if there are many objects with dynamic properties that are likely to be repeated. This also allows for slightly more efficient one byte encoding. However, if your application has more structures that are commonly repeated, you can increase this limit by setting `maxSharedStructures` to a higher value. The maximum supported shared structures is 8160.
You can also provide a `shouldShareStructure` function in the options if you want to specifically indicate which structures should be shared. This is called during the encoding process with the array of keys for a structure that is being considered for addition to the shared structure. For example, you might want:
```
maxSharedStructures: 100,
shouldShareStructure(keys) {
return !(keys[0] > 1) // don't share structures that consist of numbers as keys
}
```
### Reading Multiple Values
If you have a buffer with multiple values sequentially encoded, you can choose to parse and read multiple values. This can be done using the `unpackMultiple` function/method, which can return an array of all the values it can sequentially parse within the provided buffer. For example:
```js
let data = new Uint8Array([1, 2, 3]) // encodings of values 1, 2, and 3
let values = unpackMultiple(data) // [1, 2, 3]
```
Alternately, you can provide a callback function that is called as the parsing occurs with each value, and can optionally terminate the parsing by returning `false`:
```js
let data = new Uint8Array([1, 2, 3]) // encodings of values 1, 2, and 3
unpackMultiple(data, (value) => {
// called for each value
// return false if you wish to end the parsing
})
```
## Options
The following options properties can be provided to the Packr or Unpackr constructor:
* `useRecords` - Setting this to `false` disables the record extension and stores JavaScript objects as MessagePack maps, and unpacks maps as JavaScript `Object`s, which ensures compatibilty with other decoders.
* `structures` - Provides the array of structures that is to be used for record extension, if you want the structures saved and used again. This array will be modified in place with new record structures that are serialized (if less than 32 structures are in the array).
* `moreTypes` - Enable serialization of additional built-in types/classes including typed arrays, `Set`s, `Map`s, and `Error`s.
* `structuredClone` - This enables the structured cloning extensions that will encode object/cyclic references. `moreTypes` is enabled by default when this is enabled.
* `mapsAsObjects` - If `true`, this will decode MessagePack maps and JS `Object`s with the map entries decoded to object properties. If `false`, maps are decoded as JavaScript `Map`s. This is disabled by default if `useRecords` is enabled (which allows `Map`s to be preserved), and is enabled by default if `useRecords` is disabled.
* `useFloat32` - This will enable msgpackr to encode non-integer numbers as `float32`. See next section for possible values.
* `variableMapSize` - This will use varying map size definition (fixmap, map16, map32) based on the number of keys when encoding objects, which yields slightly more compact encodings (for small objects), but is typically 5-10% slower during encoding. This is necessary if you need to use objects with more than 65535 keys. This is only relevant when record extension is disabled.
* `bundleStrings` - If `true` this uses a custom extension that bundles strings together, so that they can be decoded more quickly on browsers and Deno that do not have access to the NodeJS addon. This a custom extension, so both encoder and decoder need to support this. This can yield significant decoding performance increases on browsers (30%-50%).
* `copyBuffers` - When decoding a MessagePack with binary data (Buffers are encoded as binary data), copy the buffer rather than providing a slice/view of the buffer. If you want your input data to be collected or modified while the decoded embedded buffer continues to live on, you can use this option (there is extra overhead to copying).
* `useTimestamp32` - Encode JS `Date`s in 32-bit format when possible by dropping the milliseconds. This is a more efficient encoding of dates. You can also cause dates to use 32-bit format by manually setting the milliseconds to zero (`date.setMilliseconds(0)`).
* `sequential` - Encode structures in serialized data, and reference previously encoded structures with expectation that decoder will read the encoded structures in the same order as encoded, with `unpackMultiple`.
* `largeBigIntToFloat` - If a bigint needs to be encoded that is larger than will fit in 64-bit integers, it will be encoded as a float-64 (otherwise will throw a RangeError).
* `encodeUndefinedAsNil` - Encodes a value of `undefined` as a MessagePack `nil`, the same as a `null`.
* `int64AsNumber` - This will decode uint64 and int64 numbers as standard JS numbers rather than as bigint numbers.
* `onInvalidDate` - This can be provided as function that will be called when an invalid date is provided. The function can throw an error, or return a value that will be encoded in place of the invalid date. If not provided, an invalid date will be encoded as an invalid timestamp (which decodes with msgpackr back to an invalid date).
### 32-bit Float Options
By default all non-integer numbers are serialized as 64-bit float (double). This is fast, and ensures maximum precision. However, often real-world data doesn't not need 64-bits of precision, and using 32-bit encoding can be much more space efficient. There are several options that provide more efficient encodings. Using the decimal rounding options for encoding and decoding provides lossless storage of common decimal representations like 7.99, in more efficient 32-bit format (rather than 64-bit). The `useFloat32` property has several possible options, available from the module as constants:
```js
import { FLOAT32_OPTIONS } from 'msgpackr';
const { ALWAYS, DECIMAL_ROUND, DECIMAL_FIT } = FLOAT32_OPTIONS;
```
* `ALWAYS` (1) - Always will encode non-integers (absolute less than 2147483648) as 32-bit float.
* `DECIMAL_ROUND` (3) - Always will encode non-integers as 32-bit float, and when decoding 32-bit float, round to the significant decimal digits (usually 7, but 6 or 8 digits for some ranges).
* `DECIMAL_FIT` (4) - Only encode non-integers as 32-bit float if all significant digits (usually up to 7) can be unambiguously encoded as a 32-bit float, and decode/unpack with decimal rounding (same as above). This will ensure round-trip encoding/decoding without loss in precision and uses 32-bit when possible.
Note, that the performance is decreased with decimal rounding by about 20-25%, although if only 5% of your values are floating point, that will only have about a 1% impact overall.
In addition, msgpackr exports a `roundFloat32(number)` function that can be used to round floating point numbers to the maximum significant decimal digits that can be stored in 32-bit float, just as DECIMAL_ROUND does when decoding. This can be useful for determining how a number will be decoded prior to encoding it.
## Performance
### Native Acceleration
Msgpackr employs an optional native node-addon to accelerate the parsing of strings. This should be automatically installed and utilized on NodeJS. However, you can verify this by checking the `isNativeAccelerationEnabled` property that is exported from msgpackr. If this is `false`, the `msgpackr-extract` package may not have been properly installed, and you may want to verify that it is installed correctly:
```js
import { isNativeAccelerationEnabled } from 'msgpackr'
if (!isNativeAccelerationEnabled)
console.warn('Native acceleration not enabled, verify that install finished properly')
```
### Benchmarks
Msgpackr is fast. Really fast. Here is comparison with the next fastest JS projects using the benchmark tool from `msgpack-lite` (and the sample data is from some clinical research data we use that has a good mix of different value types and structures). It also includes comparison to V8 native JSON functionality, and JavaScript Avro (`avsc`, a very optimized Avro implementation):
operation | op | ms | op/s
---------------------------------------------------------- | ------: | ----: | -----:
buf = Buffer(JSON.stringify(obj)); | 81600 | 5002 | 16313
obj = JSON.parse(buf); | 90700 | 5004 | 18125
require("msgpackr").pack(obj); | 169700 | 5000 | 33940
require("msgpackr").unpack(buf); | 109700 | 5003 | 21926
msgpackr w/ shared structures: packr.pack(obj); | 190400 | 5001 | 38072
msgpackr w/ shared structures: packr.unpack(buf); | 422900 | 5000 | 84580
buf = require("msgpack-lite").encode(obj); | 31300 | 5005 | 6253
obj = require("msgpack-lite").decode(buf); | 15700 | 5007 | 3135
buf = require("@msgpack/msgpack").encode(obj); | 103100 | 5003 | 20607
obj = require("@msgpack/msgpack").decode(buf); | 59100 | 5004 | 11810
buf = require("notepack").encode(obj); | 65500 | 5007 | 13081
obj = require("notepack").decode(buf); | 33400 | 5009 | 6667
obj = require("msgpack-unpack").decode(buf); | 6900 | 5036 | 1370
require("avsc")...make schema/type...type.toBuffer(obj); | 89300 | 5005 | 17842
require("avsc")...make schema/type...type.fromBuffer(obj); | 108400 | 5001 | 21675
All benchmarks were performed on Node 15 / V8 8.6 (Windows i7-4770 3.4Ghz).
(`avsc` is schema-based and more comparable in style to msgpackr with shared structures).
Here is a benchmark of streaming data (again borrowed from `msgpack-lite`'s benchmarking), where msgpackr is able to take advantage of the structured record extension and really demonstrate its performance capabilities:
operation (1000000 x 2) | op | ms | op/s
------------------------------------------------ | ------: | ----: | -----:
new PackrStream().write(obj); | 1000000 | 372 | 2688172
new UnpackrStream().write(buf); | 1000000 | 247 | 4048582
stream.write(msgpack.encode(obj)); | 1000000 | 2898 | 345065
stream.write(msgpack.decode(buf)); | 1000000 | 1969 | 507872
stream.write(notepack.encode(obj)); | 1000000 | 901 | 1109877
stream.write(notepack.decode(buf)); | 1000000 | 1012 | 988142
msgpack.Encoder().on("data",ondata).encode(obj); | 1000000 | 1763 | 567214
msgpack.createDecodeStream().write(buf); | 1000000 | 2222 | 450045
msgpack.createEncodeStream().write(obj); | 1000000 | 1577 | 634115
msgpack.Decoder().on("data",ondata).decode(buf); | 1000000 | 2246 | 445235
See the [benchmark.md](benchmark.md) for more benchmarks and information about benchmarking.
## Custom Extensions
You can add your own custom extensions, which can be used to encode specific types/classes in certain ways. This is done by using the `addExtension` function, and specifying the class, extension `type` code (should be a number from 1-100, reserving negatives for MessagePack, 101-127 for msgpackr), and your `pack` and `unpack` functions (or just the one you need).
```js
import { addExtension, Packr } from 'msgpackr';
class MyCustomClass {...}
let extPackr = new Packr();
addExtension({
Class: MyCustomClass,
type: 11, // register your own extension code (a type code from 1-100)
pack(instance) {
// define how your custom class should be encoded
return Buffer.from([instance.myData]); // return a buffer
}
unpack(buffer) {
// define how your custom class should be decoded
let instance = new MyCustomClass();
instance.myData = buffer[0];
return instance; // decoded value from buffer
}
});
```
If you want to use msgpackr to encode and decode the data within your extensions, you can use the `read` and `write` functions and read and write data/objects that will be encoded and decoded by msgpackr, which can be easier and faster than creating and receiving separate buffers (note that you can't just return the instance from `write` or msgpackr will recursively try to use extension infinitely):
```js
import { addExtension, Packr } from 'msgpackr';
class MyCustomClass {...}
let extPackr = new Packr();
addExtension({
Class: MyCustomClass,
type: 11, // register your own extension code (a type code from 1-100)
write(instance) {
// define how your custom class should be encoded
return instance.myData; // return some data to be encoded
}
read(data) {
// define how your custom class should be decoded,
// data will already be unpacked/decoded
let instance = new MyCustomClass();
instance.myData = data;
return instance; // return decoded value
}
});
```
You can also create an extension with `Class` and `write` methods, but no `type` (or `read`), if you just want to customize how a class is serialized without using MessagePack extension encoding.
### Additional Performance Optimizations
Msgpackr is already fast, but here are some tips for making it faster:
#### Buffer Reuse
Msgpackr is designed to work well with reusable buffers. Allocating new buffers can be relatively expensive, so if you have Node addons, it can be much faster to reuse buffers and use memcpy to copy data into existing buffers. Then msgpackr `unpack` can be executed on the same buffer, with new data, and optionally take a second paramter indicating the effective size of the available data in the buffer.
#### Arena Allocation (`useBuffer()`)
During the serialization process, data is written to buffers. Again, allocating new buffers is a relatively expensive process, and the `useBuffer` method can help allow reuse of buffers that will further improve performance. With `useBuffer` method, you can provide a buffer, serialize data into it, and when it is known that you are done using that buffer, you can call `useBuffer` again to reuse it. The use of `useBuffer` is never required, buffers will still be handled and cleaned up through GC if not used, it just provides a small performance boost.
## Record Structure Extension Definition
The record struction extension uses extension id 0x72 ("r") to declare the use of this functionality. The extension "data" byte (or bytes) identifies the byte or bytes used to identify the start of a record in the subsequent MessagePack block or stream. The identifier byte (or the first byte in a sequence) must be from 0x40 - 0x7f (and therefore replaces one byte representations of positive integers 64 - 127, which can alternately be represented with int or uint types). The extension declaration must be immediately follow by an MessagePack array that defines the field names of the record structure.
Once a record identifier and record field names have been defined, the parser/decoder should proceed to read the next value. Any subsequent use of the record identifier as a value in the block or stream should parsed as a record instance, and the next n values, where is n is the number of fields (as defined in the array of field names), should be read as the values of the fields. For example, here we have defined a structure with fields "foo" and "bar", with the record identifier 0x40, and then read a record instance that defines the field values of 4 and 2, respectively:
```
+--------+--------+--------+~~~~~~~~~~~~~~~~~~~~~~~~~+--------+--------+--------+
| 0xd4 | 0x72 | 0x40 | array: [ "foo", "bar" ] | 0x40 | 0x04 | 0x02 |
+--------+--------+--------+~~~~~~~~~~~~~~~~~~~~~~~~~+--------+--------+--------+
```
Which should generate an object that would correspond to JSON:
```js
{ "foo": 4, "bar": 2}
```
## Additional value types
msgpackr supports `undefined` (using fixext1 + type: 0 + data: 0 to match other JS implementations), `NaN`, `Infinity`, and `-Infinity` (using standard IEEE 754 representations with doubles/floats).
### Dates
msgpackr saves all JavaScript `Date`s using the standard MessagePack date extension (type -1), using the smallest of 32-bit, 64-bit or 96-bit format needed to store the date without data loss (or using 32-bit if useTimestamp32 options is specified).
### Structured Cloning
With structured cloning enabled, msgpackr will also use extensions to store Set, Map, Error, RegExp, ArrayBufferView objects and preserve their types.
## Alternate Encoding/Package
The high-performance serialization and deserialization algorithms in the msgpackr package are also available in the [cbor-x](https://github.com/kriszyp/cbor-x) for the CBOR format, with the same API and design. A quick summary of the pros and cons of using MessagePack vs CBOR are:
* MessagePack has wider adoption, and, at least with this implementation is slightly more efficient (by roughly 1%).
* CBOR has an [official IETF standardization track](https://tools.ietf.org/html/rfc7049), and the record extensions is conceptually/philosophically a better fit for CBOR tags.
## License
MIT
### Browser Consideration
MessagePack can be a great choice for high-performance data delivery to browsers, as reasonable data size is possible without compression. And msgpackr works very well in modern browsers. However, it is worth noting that if you want highly compact data, brotli or gzip are most effective in compressing, and MessagePack's character frequency tends to defeat Huffman encoding used by these standard compression algorithms, resulting in less compact data than compressed JSON.
### Credits
Various projects have been inspirations for this, and code has been borrowed from https://github.com/msgpack/msgpack-javascript and https://github.com/mtth/avsc.
# ripemd160
[](https://www.npmjs.org/package/ripemd160)
[](https://travis-ci.org/crypto-browserify/ripemd160)
[](https://david-dm.org/crypto-browserify/ripemd160#info=dependencies)
[](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
# cosmiconfig
[](https://travis-ci.org/davidtheclark/cosmiconfig) [](https://ci.appveyor.com/project/davidtheclark/cosmiconfig/branch/main)
[](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`, `.js`, or `.cjs`
- a `.config.js` or `.config.cjs` CommonJS module
For example, if your module's name is "myapp", cosmiconfig will search up the directory tree for configuration in the following places:
- a `myapp` property in `package.json`
- a `.myapprc` file in JSON or YAML format
- a `.myapprc.json`, `.myapprc.yaml`, `.myapprc.yml`, `.myapprc.js`, or `.myapprc.cjs` file
- a `myapp.config.js` or `myapp.config.cjs` CommonJS module exporting an 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).
## Table of contents
- [Installation](#installation)
- [Usage](#usage)
- [Result](#result)
- [Asynchronous API](#asynchronous-api)
- [cosmiconfig()](#cosmiconfig-1)
- [explorer.search()](#explorersearch)
- [explorer.load()](#explorerload)
- [explorer.clearLoadCache()](#explorerclearloadcache)
- [explorer.clearSearchCache()](#explorerclearsearchcache)
- [explorer.clearCaches()](#explorerclearcaches)
- [Synchronous API](#synchronous-api)
- [cosmiconfigSync()](#cosmiconfigsync)
- [explorerSync.search()](#explorersyncsearch)
- [explorerSync.load()](#explorersyncload)
- [explorerSync.clearLoadCache()](#explorersyncclearloadcache)
- [explorerSync.clearSearchCache()](#explorersyncclearsearchcache)
- [explorerSync.clearCaches()](#explorersyncclearcaches)
- [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 10+.
## Usage
Create a Cosmiconfig explorer, then either `search` for or directly `load` a configuration file.
```js
const { cosmiconfig, cosmiconfigSync } = 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 explorerSync = cosmiconfigSync(moduleName);
const searchedFor = explorerSync.search();
const loaded = explorerSync.load(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.
## Asynchronous API
### cosmiconfig()
```js
const { cosmiconfig } = require('cosmiconfig');
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`].
If your [`searchPlaces`] value will include files, as it does by default (e.g. `${moduleName}rc`), your `moduleName` must consist of characters allowed in filenames. That means you should not copy scoped package names, such as `@my-org/my-package`, directly into `moduleName`.
**[`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 [`explorerSync.search()`].
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`, `.goldengrahamsrc.yaml`, `.goldengrahamsrc.yml`, `.goldengrahamsrc.js`, or `.goldengrahamsrc.cjs` file.
4. A `goldengrahams.config.js` or `goldengrahams.config.cjs` CommonJS module 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 parsable configuration is found, the [`search()`] Promise resolves with its [result] \(or, with [`explorerSync.search()`], the [result] is returned).
- If no configuration object is found, the [`search()`] Promise resolves with `null` (or, with [`explorerSync.search()`], `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 [`explorerSync.search()`], 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.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`].
You can do the same thing synchronously with [`explorerSync.load()`].
### explorer.clearLoadCache()
Clears the cache used in [`load()`].
### explorer.clearSearchCache()
Clears the cache used in [`search()`].
### explorer.clearCaches()
Performs both [`clearLoadCache()`] and [`clearSearchCache()`].
## Synchronous API
### cosmiconfigSync()
```js
const { cosmiconfigSync } = require('cosmiconfig');
const explorerSync = cosmiconfigSync(moduleName[, cosmiconfigOptions])
```
Creates a *synchronous* cosmiconfig instance ("explorerSync") configured according to the arguments, and initializes its caches.
See [`cosmiconfig()`].
### explorerSync.search()
```js
const result = explorerSync.search([searchFrom]);
```
Synchronous version of [`explorer.search()`].
Returns a [result] or `null`.
### explorerSync.load()
```js
const result = explorerSync.load(loadPath);
```
Synchronous version of [`explorer.load()`].
Returns a [result].
### explorerSync.clearLoadCache()
Clears the cache used in [`load()`].
### explorerSync.clearSearchCache()
Clears the cache used in [`search()`].
### explorerSync.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}rc.cjs`,
`${moduleName}.config.js`,
`${moduleName}.config.cjs`,
]
```
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 on a named export `defaultLoaders`.
**Default `loaders`:**
```js
const { defaultLoaders } = require('cosmiconfig');
console.log(Object.entries(defaultLoaders))
// [
// [ '.cjs', [Function: loadJs] ],
// [ '.js', [Function: loadJs] ],
// [ '.json', [Function: loadJson] ],
// [ '.yaml', [Function: loadYaml] ],
// [ '.yml', [Function: loadYaml] ],
// [ 'noExt', [Function: 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 `.myapprc`.
**Values in `loaders`** are a loader function (described below) 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: defaultLoaders['.json']
}
```
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.
A few things to note:
- If you use a custom loader, be aware of whether it's sync or async: you cannot use async customer loaders with the sync API ([`cosmiconfigSync()`]).
- **Special JS syntax can also be handled by using a `require` hook**, because `defaultLoaders['.js']` just uses `require`.
Whether you use custom loaders or a `require` hook is up to you.
Examples:
```js
// Allow JSON5 syntax:
{
'.json': json5Loader
}
// 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': defaultLoaders['.js'],
'.ts': defaultLoaders['.js'],
'.coffee': defaultLoaders['.js']
}
```
### 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 `cosmiconfigSync`, [`search()`] or [`load()`], 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
[`search()`]: #explorersearch
[`clearloadcache()`]: #explorerclearloadcache
[`clearsearchcache()`]: #explorerclearsearchcache
[`cosmiconfig()`]: #cosmiconfig
[`cosmiconfigSync()`]: #cosmiconfigsync
[`clearcaches()`]: #explorerclearcaches
[`packageprop`]: #packageprop
[`cache`]: #cache
[`stopdir`]: #stopdir
[`searchplaces`]: #searchplaces
[`loaders`]: #loaders
[`cosmiconfigoptions`]: #cosmiconfigoptions
[`explorerSync.search()`]: #explorersyncsearch
[`explorerSync.load()`]: #explorersyncload
[`explorer.search()`]: #explorersearch
[`explorer.load()`]: #explorerload
# yargs-parser

[](https://www.npmjs.com/package/yargs-parser)
[](https://conventionalcommits.org)

The mighty option parser used by [yargs](https://github.com/yargs/yargs).
visit the [yargs website](http://yargs.js.org/) for more examples, and thorough usage instructions.
<img width="250" src="https://raw.githubusercontent.com/yargs/yargs-parser/main/yargs-logo.png">
## Example
```sh
npm i yargs-parser --save
```
```js
const argv = require('yargs-parser')(process.argv.slice(2))
console.log(argv)
```
```console
$ node example.js --foo=33 --bar hello
{ _: [], foo: 33, bar: 'hello' }
```
_or parse a string!_
```js
const argv = require('yargs-parser')('--foo=99 --bar=33')
console.log(argv)
```
```console
{ _: [], foo: 99, bar: 33 }
```
Convert an array of mixed types before passing to `yargs-parser`:
```js
const parse = require('yargs-parser')
parse(['-f', 11, '--zoom', 55].join(' ')) // <-- array to string
parse(['-f', 11, '--zoom', 55].map(String)) // <-- array of strings
```
## Deno Example
As of `v19` `yargs-parser` supports [Deno](https://github.com/denoland/deno):
```typescript
import parser from "https://deno.land/x/yargs_parser/deno.ts";
const argv = parser('--foo=99 --bar=9987930', {
string: ['bar']
})
console.log(argv)
```
## ESM Example
As of `v19` `yargs-parser` supports ESM (_both in Node.js and in the browser_):
**Node.js:**
```js
import parser from 'yargs-parser'
const argv = parser('--foo=99 --bar=9987930', {
string: ['bar']
})
console.log(argv)
```
**Browsers:**
```html
<!doctype html>
<body>
<script type="module">
import parser from "https://unpkg.com/[email protected]/browser.js";
const argv = parser('--foo=99 --bar=9987930', {
string: ['bar']
})
console.log(argv)
</script>
</body>
```
## API
### parser(args, opts={})
Parses command line arguments returning a simple mapping of keys and values.
**expects:**
* `args`: a string or array of strings representing the options to parse.
* `opts`: provide a set of hints indicating how `args` should be parsed:
* `opts.alias`: an object representing the set of aliases for a key: `{alias: {foo: ['f']}}`.
* `opts.array`: indicate that keys should be parsed as an array: `{array: ['foo', 'bar']}`.<br>
Indicate that keys should be parsed as an array and coerced to booleans / numbers:<br>
`{array: [{ key: 'foo', boolean: true }, {key: 'bar', number: true}]}`.
* `opts.boolean`: arguments should be parsed as booleans: `{boolean: ['x', 'y']}`.
* `opts.coerce`: provide a custom synchronous function that returns a coerced value from the argument provided
(or throws an error). For arrays the function is called only once for the entire array:<br>
`{coerce: {foo: function (arg) {return modifiedArg}}}`.
* `opts.config`: indicate a key that represents a path to a configuration file (this file will be loaded and parsed).
* `opts.configObjects`: configuration objects to parse, their properties will be set as arguments:<br>
`{configObjects: [{'x': 5, 'y': 33}, {'z': 44}]}`.
* `opts.configuration`: provide configuration options to the yargs-parser (see: [configuration](#configuration)).
* `opts.count`: indicate a key that should be used as a counter, e.g., `-vvv` = `{v: 3}`.
* `opts.default`: provide default values for keys: `{default: {x: 33, y: 'hello world!'}}`.
* `opts.envPrefix`: environment variables (`process.env`) with the prefix provided should be parsed.
* `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`.
* `opts.normalize`: `path.normalize()` will be applied to values set to this key.
* `opts.number`: keys should be treated as numbers.
* `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`).
**returns:**
* `obj`: an object representing the parsed value of `args`
* `key/value`: key value pairs for each argument and their aliases.
* `_`: an array representing the positional arguments.
* [optional] `--`: an array with arguments after the end-of-options flag `--`.
### require('yargs-parser').detailed(args, opts={})
Parses a command line string, returning detailed information required by the
yargs engine.
**expects:**
* `args`: a string or array of strings representing options to parse.
* `opts`: provide a set of hints indicating how `args`, inputs are identical to `require('yargs-parser')(args, opts={})`.
**returns:**
* `argv`: an object representing the parsed value of `args`
* `key/value`: key value pairs for each argument and their aliases.
* `_`: an array representing the positional arguments.
* [optional] `--`: an array with arguments after the end-of-options flag `--`.
* `error`: populated with an error object if an exception occurred during parsing.
* `aliases`: the inferred list of aliases built by combining lists in `opts.alias`.
* `newAliases`: any new aliases added via camel-case expansion:
* `boolean`: `{ fooBar: true }`
* `defaulted`: any new argument created by `opts.default`, no aliases included.
* `boolean`: `{ foo: true }`
* `configuration`: given by default settings and `opts.configuration`.
<a name="configuration"></a>
### Configuration
The yargs-parser applies several automated transformations on the keys provided
in `args`. These features can be turned on and off using the `configuration` field
of `opts`.
```js
var parsed = parser(['--no-dice'], {
configuration: {
'boolean-negation': false
}
})
```
### short option groups
* default: `true`.
* key: `short-option-groups`.
Should a group of short-options be treated as boolean flags?
```console
$ node example.js -abc
{ _: [], a: true, b: true, c: true }
```
_if disabled:_
```console
$ node example.js -abc
{ _: [], abc: true }
```
### camel-case expansion
* default: `true`.
* key: `camel-case-expansion`.
Should hyphenated arguments be expanded into camel-case aliases?
```console
$ node example.js --foo-bar
{ _: [], 'foo-bar': true, fooBar: true }
```
_if disabled:_
```console
$ node example.js --foo-bar
{ _: [], 'foo-bar': true }
```
### dot-notation
* default: `true`
* key: `dot-notation`
Should keys that contain `.` be treated as objects?
```console
$ node example.js --foo.bar
{ _: [], foo: { bar: true } }
```
_if disabled:_
```console
$ node example.js --foo.bar
{ _: [], "foo.bar": true }
```
### parse numbers
* default: `true`
* key: `parse-numbers`
Should keys that look like numbers be treated as such?
```console
$ node example.js --foo=99.3
{ _: [], foo: 99.3 }
```
_if disabled:_
```console
$ node example.js --foo=99.3
{ _: [], foo: "99.3" }
```
### parse positional numbers
* default: `true`
* key: `parse-positional-numbers`
Should positional keys that look like numbers be treated as such.
```console
$ node example.js 99.3
{ _: [99.3] }
```
_if disabled:_
```console
$ node example.js 99.3
{ _: ['99.3'] }
```
### boolean negation
* default: `true`
* key: `boolean-negation`
Should variables prefixed with `--no` be treated as negations?
```console
$ node example.js --no-foo
{ _: [], foo: false }
```
_if disabled:_
```console
$ node example.js --no-foo
{ _: [], "no-foo": true }
```
### combine arrays
* default: `false`
* key: `combine-arrays`
Should arrays be combined when provided by both command line arguments and
a configuration file.
### duplicate arguments array
* default: `true`
* key: `duplicate-arguments-array`
Should arguments be coerced into an array when duplicated:
```console
$ node example.js -x 1 -x 2
{ _: [], x: [1, 2] }
```
_if disabled:_
```console
$ node example.js -x 1 -x 2
{ _: [], x: 2 }
```
### flatten duplicate arrays
* default: `true`
* key: `flatten-duplicate-arrays`
Should array arguments be coerced into a single array when duplicated:
```console
$ node example.js -x 1 2 -x 3 4
{ _: [], x: [1, 2, 3, 4] }
```
_if disabled:_
```console
$ node example.js -x 1 2 -x 3 4
{ _: [], x: [[1, 2], [3, 4]] }
```
### greedy arrays
* default: `true`
* key: `greedy-arrays`
Should arrays consume more than one positional argument following their flag.
```console
$ node example --arr 1 2
{ _: [], arr: [1, 2] }
```
_if disabled:_
```console
$ node example --arr 1 2
{ _: [2], arr: [1] }
```
**Note: in `v18.0.0` we are considering defaulting greedy arrays to `false`.**
### nargs eats options
* default: `false`
* key: `nargs-eats-options`
Should nargs consume dash options as well as positional arguments.
### negation prefix
* default: `no-`
* key: `negation-prefix`
The prefix to use for negated boolean variables.
```console
$ node example.js --no-foo
{ _: [], foo: false }
```
_if set to `quux`:_
```console
$ node example.js --quuxfoo
{ _: [], foo: false }
```
### populate --
* default: `false`.
* key: `populate--`
Should unparsed flags be stored in `--` or `_`.
_If disabled:_
```console
$ node example.js a -b -- x y
{ _: [ 'a', 'x', 'y' ], b: true }
```
_If enabled:_
```console
$ node example.js a -b -- x y
{ _: [ 'a' ], '--': [ 'x', 'y' ], b: true }
```
### set placeholder key
* default: `false`.
* key: `set-placeholder-key`.
Should a placeholder be added for keys not set via the corresponding CLI argument?
_If disabled:_
```console
$ node example.js -a 1 -c 2
{ _: [], a: 1, c: 2 }
```
_If enabled:_
```console
$ node example.js -a 1 -c 2
{ _: [], a: 1, b: undefined, c: 2 }
```
### halt at non-option
* default: `false`.
* key: `halt-at-non-option`.
Should parsing stop at the first positional argument? This is similar to how e.g. `ssh` parses its command line.
_If disabled:_
```console
$ node example.js -a run b -x y
{ _: [ 'b' ], a: 'run', x: 'y' }
```
_If enabled:_
```console
$ node example.js -a run b -x y
{ _: [ 'b', '-x', 'y' ], a: 'run' }
```
### strip aliased
* default: `false`
* key: `strip-aliased`
Should aliases be removed before returning results?
_If disabled:_
```console
$ node example.js --test-field 1
{ _: [], 'test-field': 1, testField: 1, 'test-alias': 1, testAlias: 1 }
```
_If enabled:_
```console
$ node example.js --test-field 1
{ _: [], 'test-field': 1, testField: 1 }
```
### strip dashed
* default: `false`
* key: `strip-dashed`
Should dashed keys be removed before returning results? This option has no effect if
`camel-case-expansion` is disabled.
_If disabled:_
```console
$ node example.js --test-field 1
{ _: [], 'test-field': 1, testField: 1 }
```
_If enabled:_
```console
$ node example.js --test-field 1
{ _: [], testField: 1 }
```
### unknown options as args
* default: `false`
* key: `unknown-options-as-args`
Should unknown options be treated like regular arguments? An unknown option is one that is not
configured in `opts`.
_If disabled_
```console
$ node example.js --unknown-option --known-option 2 --string-option --unknown-option2
{ _: [], unknownOption: true, knownOption: 2, stringOption: '', unknownOption2: true }
```
_If enabled_
```console
$ node example.js --unknown-option --known-option 2 --string-option --unknown-option2
{ _: ['--unknown-option'], knownOption: 2, stringOption: '--unknown-option2' }
```
## Supported Node.js Versions
Libraries in this ecosystem make a best effort to track
[Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a
post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a).
## Special Thanks
The yargs project evolves from optimist and minimist. It owes its
existence to a lot of James Halliday's hard work. Thanks [substack](https://github.com/substack) **beep** **boop** \o/
## License
ISC
# 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.
# 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.
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 <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
https-proxy-agent
================
### An HTTP(s) proxy `http.Agent` implementation for HTTPS
[](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 <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[CONNECT]: http://en.wikipedia.org/wiki/HTTP_tunnel#HTTP_CONNECT_Tunneling

[`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
import compat from 'core-js-compat';
const {
list, // array of required modules
targets, // object with targets for each module
} = compat({
targets: '> 1%', // browserslist query or object of minimum environment versions to support, see below
modules: [ // optional list / filter of modules - regex, sting or an array of them:
'core-js/actual', // - an entry point
'esnext.array.unique-by', // - a module name (or just a start of a module name)
/^web\./, // - regex that a module name must satisfy
],
exclude: [ // optional list / filter of modules to exclude, the signature is similar to `modules` option
'web.atob',
],
version: '3.23', // used `core-js` version, by default - the latest
});
console.log(targets);
/* =>
{
'es.error.cause': { ios: '14.5-14.8' },
'es.aggregate-error.cause': { ios: '14.5-14.8' },
'es.array.at': { ios: '14.5-14.8' },
'es.array.find-last': { firefox: '100', ios: '14.5-14.8' },
'es.array.find-last-index': { firefox: '100', ios: '14.5-14.8' },
'es.array.includes': { firefox: '100' },
'es.array.push': { chrome: '100', edge: '101', ios: '14.5-14.8', safari: '15.4' },
'es.array.unshift': { ios: '14.5-14.8', safari: '15.4' },
'es.object.has-own': { ios: '14.5-14.8' },
'es.regexp.flags': { chrome: '100', edge: '101' },
'es.string.at-alternative': { ios: '14.5-14.8' },
'es.typed-array.at': { ios: '14.5-14.8' },
'es.typed-array.find-last': { firefox: '100', ios: '14.5-14.8' },
'es.typed-array.find-last-index': { firefox: '100', ios: '14.5-14.8' },
'esnext.array.group': { chrome: '100', edge: '101', firefox: '100', ios: '14.5-14.8', safari: '15.4' },
'esnext.array.group-by': { chrome: '100', edge: '101', firefox: '100', ios: '14.5-14.8', safari: '15.4' },
'esnext.array.group-by-to-map': { chrome: '100', edge: '101', firefox: '100', ios: '14.5-14.8', safari: '15.4' },
'esnext.array.group-to-map': { chrome: '100', edge: '101', firefox: '100', ios: '14.5-14.8', safari: '15.4' },
'esnext.array.to-reversed': { chrome: '100', edge: '101', firefox: '100', ios: '14.5-14.8', safari: '15.4' },
'esnext.array.to-sorted': { chrome: '100', edge: '101', firefox: '100', ios: '14.5-14.8', safari: '15.4' },
'esnext.array.to-spliced': { chrome: '100', edge: '101', firefox: '100', ios: '14.5-14.8', safari: '15.4' },
'esnext.array.unique-by': { chrome: '100', edge: '101', firefox: '100', ios: '14.5-14.8', safari: '15.4' },
'esnext.array.with': { chrome: '100', edge: '101', firefox: '100', ios: '14.5-14.8', safari: '15.4' },
'esnext.typed-array.to-reversed': { chrome: '100', edge: '101', firefox: '100', ios: '14.5-14.8', safari: '15.4' },
'esnext.typed-array.to-sorted': { chrome: '100', edge: '101', firefox: '100', ios: '14.5-14.8', safari: '15.4' },
'esnext.typed-array.to-spliced': { chrome: '100', edge: '101', firefox: '100', ios: '14.5-14.8', safari: '15.4' },
'esnext.typed-array.with': { chrome: '100', edge: '101', firefox: '100', ios: '14.5-14.8', safari: '15.4' },
'web.dom-exception.stack': { chrome: '100', edge: '101', ios: '14.5-14.8', safari: '15.4' },
'web.immediate': { chrome: '100', edge: '101', firefox: '100', ios: '14.5-14.8', safari: '15.4' },
'web.structured-clone': { chrome: '100', edge: '101', firefox: '100', ios: '14.5-14.8', safari: '15.4' }
}
*/
```
### `targets` option
`targets` could be [a `browserslist` query](https://github.com/browserslist/browserslist) or a targets object that specifies minimum environment versions to support:
```js
// browserslist query:
'defaults, not IE 11, maintained node versions'
// object:
{
android: '4.0', // Android WebView version
chrome: '38', // Chrome version
deno: '1.12', // Deno version
edge: '13', // Edge version
electron: '5.0', // Electron framework version
firefox: '15', // Firefox version
ie: '8', // Internet Explorer version
ios: '13.0', // iOS Safari version
node: 'current', // NodeJS version, you could use 'current' for set it to currently used
opera: '12', // Opera version
opera_mobile: '7', // Opera Mobile version
phantom: '1.9', // PhantomJS headless browser version
rhino: '1.7.13', // Rhino engine version
safari: '14.0', // Safari version
samsung: '14.0', // Samsung Internet version
esmodules: true, // That option set target to minimum supporting ES Modules versions of all browsers
browsers: '> 0.25%', // Browserslist query or object with target browsers
}
```
### Additional API:
```js
// equals of of the method from the example above
require('core-js-compat/compat')({ targets, modules, version }); // => { list: Array<ModuleName>, targets: { [ModuleName]: { [EngineName]: EngineVersion } } }
// or
require('core-js-compat').compat({ targets, modules, 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.23'); // => Array<ModuleName>
// or
require('core-js-compat').getModulesListForTargetVersion('3.23'); // => Array<ModuleName>
```
If you wanna help to improve this data, you could take a look at the related section of [`CONTRIBUTING.md`](https://github.com/zloirock/core-js/blob/master/CONTRIBUTING.md#how-to-update-core-js-compat-data). The visualization of compatibility data and the browser tests runner is available [here](http://es6.zloirock.ru/compat/), the example:

# lru cache
A cache object that deletes the least-recently-used items.
[](https://travis-ci.org/isaacs/node-lru-cache) [](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
# 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)
# homedir-polyfill [](https://www.npmjs.com/package/homedir-polyfill) [](https://npmjs.org/package/homedir-polyfill) [](https://npmjs.org/package/homedir-polyfill) [](https://travis-ci.org/doowb/homedir-polyfill) [](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._
# Arrgv
Parsing string to array of args like node on bash do.
[![Build Status][travis-image]][travis-url]
[![NPM version][npm-image]][npm-url]
When you type something like `node script.js bla bla bla` in shell and do `myArgs = process.argv.slice(2)` you get the same. All slashes, quotes and special symbols are handled same way.
## Install
```bash
npm install arrgv
```
## Tests
```bash
$ npm test
```
## Use cases
1. `spawn` a command that is given as a string
2. test `argv` parser with complicated example string
3. something else
## Example
```js
var arrgv = require('arrgv');
var str = '-param --format="hh:mm:ss" filename.ext';
console.log(arrgv(str));
/*
['-param',
'--format=hh:mm:ss',
'filename.ext' ]
*/
```
## License
MIT
[travis-url]: https://travis-ci.org/astur/arrgv
[travis-image]: https://travis-ci.org/astur/arrgv.svg?branch=master
[npm-url]: https://npmjs.org/package/arrgv
[npm-image]: https://badge.fury.io/js/arrgv.svg
# unicode-match-property-ecmascript [](https://travis-ci.org/mathiasbynens/unicode-match-property-ecmascript) [](https://www.npmjs.com/package/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
```
## For maintainers
### How to publish a new release
1. On the `main` branch, bump the version number in `package.json`:
```sh
npm version patch -m 'Release v%s'
```
Instead of `patch`, use `minor` or `major` [as needed](https://semver.org/).
Note that this produces a Git commit + tag.
1. Push the release commit and tag:
```sh
git push && git push --tags
```
Our CI then automatically publishes the new release to npm.
## Author
| [](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.
# 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.
# core-util-is
The `util.is*` functions introduced in Node v0.12.
# pump
pump is a small node module that pipes streams together and destroys all of them if one of them closes.
```
npm install pump
```
[](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.
# emoji-regex [](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
| [](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.
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)
[](https://nodei.co/npm/node-addon-api/) [](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:









## **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
[](https://github.com/hildjj/nofilter/actions/workflows/node.js.yml)
[](https://codecov.io/gh/hildjj/nofilter)
# NoFilter
A node.js package to read and write a stream of data into or out of what looks
like a growable [Buffer](https://nodejs.org/api/buffer.html).
I kept needing this, and none of the existing packages seemed to have enough
features, test coverage, etc.
# Examples
As a data sink:
```js
const NoFilter = require('nofilter')
// In ES6:
// import NoFilter from 'nofilter'
// In typescript:
// import NoFilter = require('nofilter')
const nf = new NoFilter()
nf.on('finish', () => {
console.log(nf.toString('base64'))
})
process.stdin.pipe(nf)
```
As a data source:
```js
const NoFilter = require('nofilter')
const nf = new NoFilter('010203', 'hex')
nf.pipe(process.stdout)
```
Read the [API Docs](http://hildjj.github.io/nofilter/).
# clone
[](http://travis-ci.org/pvorb/clone) [](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
<[email protected]>. 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.
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
## Stable
A stable array sort, because `Array#sort()` is not guaranteed stable.
MIT licensed.
[](http://travis-ci.org/Two-Screen/stable)
[](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.
[](https://www.npmjs.org/package/ordered-binary)
[](https://www.npmjs.org/package/ordered-binary)
[](LICENSE)
<a href="https://dev.doctorevidence.com/"><img src="./assets/powers-dre.png" width="203" /></a>
The ordered-binary package provides a representation of JavaScript primitives, serialized into binary format (NodeJS Buffers or Uint8Arrays), such that the binary values are naturally ordered such that it matches the natural ordering or values. For example, since -2.0321 > -2.04, then `toBufferKey(-2.0321)` will be greater than `toBufferKey(-2.04)` as a binary representation, in left-to-right evaluation. This is particular useful for storing keys as binaries with something like LMDB or LevelDB, to avoid any custom sorting.
The ordered-binary package supports strings, numbers, booleans, symbols, null, as well as an array of primitives. Here is an example of ordering of primitive values:
```
Buffer.from([0]) // buffers are left unchanged, and this is the minimum value
Symbol.for('even symbols')
-10 // negative supported
-1.1 // decimals supported
400
3E10
'Hello'
['Hello', 'World']
'World'
'hello'
['hello', 1, 'world']
['hello', 'world']
Buffer.from([0xff])
```
The main module exports these functions:
`writeKey(key: string | number | boolean | null | Array, target: Buffer, position: integer, inSequence?: boolean)` - Writes the provide key to the target buffer
`readKey(buffer, start, end, inSequence)` - Reads the key from the buffer, given the provided start and end, as a primitive value
`toBufferKey(jsPrimitive)` - This accepts a string, number, or boolean as the argument, and returns a `Buffer`.
`fromBufferKey(bufferKey, multiple)` - This accepts a Buffer and returns a JavaScript primitive value. This can also parse buffers that hold multiple values delimited by a byte `30`, by setting the second argument to true (in which case it will return an array).
And these constants:
`MINIMUM_KEY` - The minimum key supported (`null`, which is represented as single zero byte)
`MAXIMUM_KEY` - A maximum key larger than any supported primitive (single 0xff byte)
# well-known-symbols
Check whether a symbol is [well-known](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Well-known_symbols).
Requires Node.js 6 or above. Note that not all Node.js versions support the same
well-known symbols.
## Installation
```console
$ npm install --save well-known-symbols
```
## Usage
```js
const wellKnownSymbols = require('well-known-symbols')
wellKnownSymbols.isWellKnown(Symbol.iterator) // true
wellKnownSymbols.isWellKnown(Symbol()) // false
wellKnownSymbols.getLabel(Symbol.iterator) // 'Symbol.iterator'
wellKnownSymbols.getLabel(Symbol()) // undefined
```
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.
[
](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)
randombytes
===
[](https://www.npmjs.org/package/randombytes) [](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
});
```
base64-js
=========
`base64-js` does basic base64 encoding/decoding in pure JS.
[](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
# xxhash-wasm
[![Node.js][actions-nodejs-badge]][actions-nodejs-link]
[![npm][npm-badge]][npm-link]
A WebAssembly implementation of [xxHash][xxhash], a fast non-cryptographic hash
algorithm. It can be called seamlessly from JavaScript. You can use it like any
other JavaScript library but still get the benefits of WebAssembly, no special
setup needed.
## Table of Contents
<!-- vim-markdown-toc GFM -->
* [Installation](#installation)
* [From npm](#from-npm)
* [From Unpkg](#from-unpkg)
* [ES Modules](#es-modules)
* [UMD build](#umd-build)
* [Usage](#usage)
* [Node](#node)
* [API](#api)
* [Comparison to xxhashjs](#comparison-to-xxhashjs)
* [Benchmarks](#benchmarks)
* [Bundle size](#bundle-size)
<!-- vim-markdown-toc -->
## Installation
### From npm
```sh
npm install --save xxhash-wasm
```
Or with Yarn:
```sh
yarn add xxhash-wasm
```
### From [Unpkg][unpkg]
#### ES Modules
```html
<script type="module">
import xxhash from "https://unpkg.com/xxhash-wasm/esm/xxhash-wasm.js";
</script>
```
#### UMD build
```html
<script src="https://unpkg.com/xxhash-wasm/umd/xxhash-wasm.js"></script>
```
The global `xxhash` will be available.
## Usage
The WebAssembly is contained in the JavaScript bundle, so you don't need to
manually fetch it and create a new WebAssembly instance.
```javascript
import xxhash from "xxhash-wasm";
// Creates the WebAssembly instance.
xxhash().then(hasher => {
const input = "The string that is being hashed";
// 32-bit version
hasher.h32(input); // ee563564
// 64-bit version
hasher.h64(input); // 502b0c5fc4a5704c
});
```
Or with `async`/`await` and destructuring:
```javascript
// Creates the WebAssembly instance.
const { h32, h64, h32Raw, h64Raw } = await xxhash();
const input = "The string that is being hashed";
// 32-bit version
h32(input); // ee563564
// 64-bit version
h64(input); // 502b0c5fc4a5704c
```
### Node
This was initially meant for the browser, but Node 8 also added support for
WebAssembly, so it can be run in Node as well. The implementation uses
the browser API [`TextEncoder`][textencoder-mdn], which is has been added
recently to Node as [`util.TextEncoder`][textencoder-node], but it is not
a global. To compensate for that, a CommonJS bundle is created which
automatically imports `util.TextEncoder`.
*Note: You will see a warning that it's experimental, but it should work just
fine.*
The `main` field in `package.json` points to the CommonJS bundle, so you can
require it as usual.
```javascript
const xxhash = require("xxhash-wasm");
// Or explicitly use the cjs bundle
const xxhash = require("xxhash-wasm/cjs/xxhash-wasm");
```
If you want to bundle your application for Node with a module bundler that uses
the `module` field in `package.json`, such as webpack or Rollup, you will need
to explicitly import `xxhash-wasm/cjs/xxhash-wasm` otherwise the browser version
is used.
## API
`const { h32, h64 } = await xxhash()`
Create a WebAssembly instance.
`h32(input: string, [seed: u32]): string`
Generate a 32-bit hash of `input`. The optional `seed` is a `u32` and any number
greater than the maximum (`0xffffffff`) is wrapped, which means that
`0xffffffff + 1 = 0`.
Returns a string of the hash in hexadecimal.
`h32Raw(input: Uint8Array, [seed: u32]): number`
Same as `h32` but with a Uint8Array as input instead of a string and returns the
hash as a number.
`h64(input: string, [seedHigh: u32, seedLow: u32]): string`
Generate a 64-bit hash of `input`. Because JavaScript doesn't support `u64` the
seed is split into two `u32`, where `seedHigh` represents the first 32-bits of
the `u64` and `seedLow` the remaining 32-bits. For example:
```javascript
// Hex
seed64: ffffffff22222222
seedhigh: ffffffff
seedLow: 22222222
// Binary
seed64: 1111111111111111111111111111111100100010001000100010001000100010
seedhigh: 11111111111111111111111111111111
seedLow: 00100010001000100010001000100010
```
Each individual part of the seed is a `u32` and they are also wrapped
individually for numbers greater than the maximum.
Returns a string of the hash in hexadecimal.
`h64Raw(input: Uint8Array, [seedHigh: u32, seedLow: u32]): Uint8Array`
Same as `h64` but with a Uint8Array as input and output.
## Comparison to [xxhashjs][xxhashjs]
[`xxhashjs`][xxhashjs] is implemented in pure JavaScript and because JavaScript
is lacking support for 64-bit integers, it uses a workaround with
[`cuint`][cuint]. Not only is that a big performance hit, but it also increases
the bundle size by quite a bit when it's used in the browser.
This library (`xxhash-wasm`) has the big advantage that WebAssembly supports
`u64` and also some instructions (e.g. `rotl`), which would otherwise have
to be emulated. However, The downside is that you have to initialise
a WebAssembly instance, which takes a little over 2ms in Node and about 1ms in
the browser. But once the instance is created, it can be used without any
further overhead. For the benchmarks below, the instantiation is done before the
benchmark and therefore it's excluded from the results, since it wouldn't make
sense to always create a new WebAssembly instance.
There is still the problem that JavaScript can't represent 64-bit integers and
both the seed and the result of the 64-bit algorithm are `u64`. To work around
this, the seed and the result are split into two `u32`, which are assembled and
disassembled into/from a `u64`. Splitting the seed into two `u32` isn't a big
deal, but the result is more problematic because to assemble the 64-bit hash in
JavaScript, 3 strings have to be created: The hex representation of the first
`u32` and the hex representation of the second `u32`, which are then
concatenated to a 64-bit hex representation. That are 2 additional strings and
this is a notable overhead when the input is small.
### Benchmarks
Benchmarks are using [Benchmark.js][benchmarkjs] with random strings of
different lengths. *Higher is better*
| String length | xxhashjs 32-bit | xxhashjs 64-bit | xxhash-wasm 32-bit | xxhash-wasm 64-bit |
| ------------------------: | ------------------ | ------------------ | ------------------------- | ---------------------- |
| 1 byte | 683,014 ops/sec | 12,048 ops/sec | ***1,475,214 ops/sec*** | 979,656 ops/sec |
| 10 bytes | 577,761 ops/sec | 12,073 ops/sec | ***1,427,115 ops/sec*** | 960,567 ops/sec |
| 100 bytes | 379,348 ops/sec | 10,242 ops/sec | ***1,186,211 ops/sec*** | 682,422 ops/sec |
| 1,000 bytes | 88,732 ops/sec | 7,755 ops/sec | ***522,107 ops/sec*** | 504,409 ops/sec |
| 10,000 bytes | 11,754 ops/sec | 1,694 ops/sec | 93,817 ops/sec | ***97,087 ops/sec*** |
| 100,000 bytes | 721 ops/sec | 174 ops/sec | 10,247 ops/sec | ***11,069 ops/sec*** |
| 1,000,000 bytes | 55.38 ops/sec | 15.98 ops/sec | 1,019 ops/sec | ***1,101 ops/sec*** |
| 10,000,000 bytes | 5.98 ops/sec | 1.77 ops/sec | 98.92 ops/sec | ***107 ops/sec*** |
| 100,000,000 bytes | 0.63 ops/sec* | 0.19 ops/sec* | 9.95 ops/sec | ***10.80 ops/sec*** |
`*` = Runs out of memory with the default heap size.
`xxhash-wasm` outperforms `xxhashjs` significantly, the 32-bit is up to 18 times
faster (increases as the size of the input grows), and the 64-bit is up to 81
times faster (decreases as the size of the input grows).
The 64-bit version is the faster algorithm, but it only starts to become faster
at a little over 1kB because of the above mentioned limitations of JavaScript
numbers. After that the 64-bit version is roughly 10% faster than the 32-bit
version. For `xxhashjs` the 64-bit is strictly worse.
### Bundle size
Both libraries can be used in the browser and they provide a UMD bundle. The
bundles are self-contained, that means they can be included and used without
having to add any other dependencies. The table shows the bundle size of the
minified versions. *Lower is better*.
| | xxhashjs | xxhash-wasm |
| -------------- | ---------- | ------------- |
| Bundle size | 41.5kB | ***3.7kB*** |
| Gzipped Size | 10.3kB | ***1.2kB*** |
[actions-nodejs-badge]: https://github.com/jungomi/xxhash-wasm/actions/workflows/nodejs.yml/badge.svg
[actions-nodejs-link]: https://github.com/jungomi/xxhash-wasm/actions/workflows/nodejs.yml
[benchmarkjs]: https://benchmarkjs.com/
[cuint]: https://github.com/pierrec/js-cuint
[npm-badge]: https://img.shields.io/npm/v/xxhash-wasm.svg?style=flat-square
[npm-link]: https://www.npmjs.com/package/xxhash-wasm
[textencoder-mdn]: https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder/TextEncoder
[textencoder-node]: https://nodejs.org/api/util.html#util_class_util_textencoder
[travis]: https://travis-ci.org/jungomi/xxhash-wasm
[travis-badge]: https://img.shields.io/travis/jungomi/xxhash-wasm/master.svg?style=flat-square
[unpkg]: https://unpkg.com/
[xxhash]: https://github.com/Cyan4973/xxHash
[xxhashjs]: https://github.com/pierrec/js-xxhash
## Summary
This module is designed to do fast and efficient native/C-level extraction of strings from MessagePack binary data. This works by calling `extractStrings(buffer, start, end)`, and it will extract strings by doing partial MessagePack parsing, and scanning to find the string data in the range specified in the buffer. It will return an array of strings that it finds. When it finds strings that can be represented with latin-1/one-byte strings (and important V8 optimization), it will attempt return a continuous string of MessagePack data that contains multiple sub-strings, so the decoder can slice off strings by offset. When a string contains non-latin characters, and must be represented as a two-byte string, this will always be returned as the string alone without combination with any other strings. The extractor will return an array of a maximum of 256 strings. The decoder can call the extractStrings again, with a new offset to continue extracting more strings as necessary.
## License
MIT
# registry-auth-token
[](http://browsenpm.org/package/registry-auth-token)[](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.
# emoji-regex [](https://travis-ci.org/mathiasbynens/emoji-regex)
_emoji-regex_ offers a regular expression to match all emoji symbols and sequences (including textual representations of emoji) as per the Unicode Standard.
This repository contains a script that generates this regular expression based on [Unicode data](https://github.com/node-unicode/node-unicode-data). Because of this, the regular expression can easily be updated whenever new emoji are added to the Unicode standard.
## Installation
Via [npm](https://www.npmjs.com/):
```bash
npm install emoji-regex
```
In [Node.js](https://nodejs.org/):
```js
const emojiRegex = require('emoji-regex/RGI_Emoji.js');
// Note: because the regular expression has the global flag set, this module
// exports a function that returns the regex rather than exporting the regular
// expression itself, to make it impossible to (accidentally) mutate the
// original regular expression.
const text = `
\u{231A}: โ default emoji presentation character (Emoji_Presentation)
\u{2194}\u{FE0F}: โ๏ธ default text presentation character rendered as emoji
\u{1F469}: ๐ฉ emoji modifier base (Emoji_Modifier_Base)
\u{1F469}\u{1F3FF}: ๐ฉ๐ฟ emoji modifier base followed by a modifier
`;
const regex = emojiRegex();
let match;
while (match = regex.exec(text)) {
const emoji = match[0];
console.log(`Matched sequence ${ emoji } โ code points: ${ [...emoji].length }`);
}
```
Console output:
```
Matched sequence โ โ code points: 1
Matched sequence โ โ code points: 1
Matched sequence โ๏ธ โ code points: 2
Matched sequence โ๏ธ โ code points: 2
Matched sequence ๐ฉ โ code points: 1
Matched sequence ๐ฉ โ code points: 1
Matched sequence ๐ฉ๐ฟ โ code points: 2
Matched sequence ๐ฉ๐ฟ โ code points: 2
```
## Regular expression flavors
The package comes with three distinct regular expressions:
```js
// This is the recommended regular expression to use. It matches all
// emoji recommended for general interchange, as defined via the
// `RGI_Emoji` property in the Unicode Standard.
// https://unicode.org/reports/tr51/#def_rgi_set
// When in doubt, use this!
const emojiRegexRGI = require('emoji-regex/RGI_Emoji.js');
// This is the old regular expression, prior to `RGI_Emoji` being
// standardized. In addition to all `RGI_Emoji` sequences, it matches
// some emoji you probably donโt want to match (such as emoji component
// symbols that are not meant to be used separately).
const emojiRegex = require('emoji-regex/index.js');
// This regular expression matches even more emoji than the previous
// one, including emoji that render as text instead of icons (i.e.
// emoji that are not `Emoji_Presentation` symbols and that arenโt
// forced to render as emoji by a variation selector).
const emojiRegexText = require('emoji-regex/text.js');
```
Additionally, in environments which support ES2015 Unicode escapes, you may `require` ES2015-style versions of the regexes:
```js
const emojiRegexRGI = require('emoji-regex/es2015/RGI_Emoji.js');
const emojiRegex = require('emoji-regex/es2015/index.js');
const emojiRegexText = require('emoji-regex/es2015/text.js');
```
## For maintainers
### How to update emoji-regex after new Unicode Standard releases
1. Update the Unicode data dependency in `package.json` by running the following commands:
```sh
# Example: updating from Unicode v12 to Unicode v13.
npm uninstall @unicode/unicode-12.0.0
npm install @unicode/unicode-13.0.0 --save-dev
````
1. Generate the new output:
```sh
npm run build
```
1. Verify that tests still pass:
```sh
npm test
```
1. Send a pull request with the changes, and get it reviewed & merged.
1. On the `main` branch, bump the emoji-regex version number in `package.json`:
```sh
npm version patch -m 'Release v%s'
```
Instead of `patch`, use `minor` or `major` [as needed](https://semver.org/).
Note that this produces a Git commit + tag.
1. Push the release commit and tag:
```sh
git push
```
Our CI then automatically publishes the new release to npm.
## Author
| [](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.
# call-bind
Robustly `.call.bind()` a function.
Deep Extend
===========
Recursive object extending.
[](https://travis-ci.org/unclechu/node-deep-extend)
[](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)
# picocolors
The tiniest and the fastest library for terminal output formatting with ANSI colors.
```javascript
import pc from "picocolors"
console.log(
pc.green(`How are ${pc.italic(`you`)} doing?`)
)
```
- **No dependencies.**
- **14 times** smaller and **2 times** faster than chalk.
- Used by popular tools like PostCSS, SVGO, Stylelint, and Browserslist.
- Node.js v6+ & browsers support. Support for both CJS and ESM projects.
- TypeScript type declarations included.
- [`NO_COLOR`](https://no-color.org/) friendly.
## Docs
Read **[full docs](https://github.com/alexeyraspopov/picocolors#readme)** on GitHub.
argparse
========
[](http://travis-ci.org/nodeca/argparse)
[](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.
<!--
-- This file is auto-generated from README_js.md. Changes should be made there.
-->
# uuid [](https://github.com/uuidjs/uuid/actions?query=workflow%3ACI) [](https://github.com/uuidjs/uuid/actions?query=workflow%3ABrowser)
For the creation of [RFC4122](http://www.ietf.org/rfc/rfc4122.txt) UUIDs
- **Complete** - Support for RFC4122 version 1, 3, 4, and 5 UUIDs
- **Cross-platform** - Support for ...
- CommonJS, [ECMAScript Modules](#ecmascript-modules) and [CDN builds](#cdn-builds)
- Node 8, 10, 12, 14
- Chrome, Safari, Firefox, Edge, IE 11 browsers
- Webpack and rollup.js module bundlers
- [React Native / Expo](#react-native--expo)
- **Secure** - Cryptographically-strong random values
- **Small** - Zero-dependency, small footprint, plays nice with "tree shaking" packagers
- **CLI** - Includes the [`uuid` command line](#command-line) utility
**Upgrading from `[email protected]`?** Your code is probably okay, but check out [Upgrading From `[email protected]`](#upgrading-from-uuid3x) for details.
## Quickstart
To create a random UUID...
**1. Install**
```shell
npm install uuid
```
**2. Create a UUID** (ES6 module syntax)
```javascript
import { v4 as uuidv4 } from 'uuid';
uuidv4(); // โจ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'
```
... or using CommonJS syntax:
```javascript
const { v4: uuidv4 } = require('uuid');
uuidv4(); // โจ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
```
For timestamp UUIDs, namespace UUIDs, and other options read on ...
## API Summary
| | | |
| --- | --- | --- |
| [`uuid.NIL`](#uuidnil) | The nil UUID string (all zeros) | New in `[email protected]` |
| [`uuid.parse()`](#uuidparsestr) | Convert UUID string to array of bytes | New in `[email protected]` |
| [`uuid.stringify()`](#uuidstringifyarr-offset) | Convert array of bytes to UUID string | New in `[email protected]` |
| [`uuid.v1()`](#uuidv1options-buffer-offset) | Create a version 1 (timestamp) UUID | |
| [`uuid.v3()`](#uuidv3name-namespace-buffer-offset) | Create a version 3 (namespace w/ MD5) UUID | |
| [`uuid.v4()`](#uuidv4options-buffer-offset) | Create a version 4 (random) UUID | |
| [`uuid.v5()`](#uuidv5name-namespace-buffer-offset) | Create a version 5 (namespace w/ SHA-1) UUID | |
| [`uuid.validate()`](#uuidvalidatestr) | Test a string to see if it is a valid UUID | New in `[email protected]` |
| [`uuid.version()`](#uuidversionstr) | Detect RFC version of a UUID | New in `[email protected]` |
## API
### uuid.NIL
The nil UUID string (all zeros).
Example:
```javascript
import { NIL as NIL_UUID } from 'uuid';
NIL_UUID; // โจ '00000000-0000-0000-0000-000000000000'
```
### uuid.parse(str)
Convert UUID string to array of bytes
| | |
| --------- | ---------------------------------------- |
| `str` | A valid UUID `String` |
| _returns_ | `Uint8Array[16]` |
| _throws_ | `TypeError` if `str` is not a valid UUID |
Note: Ordering of values in the byte arrays used by `parse()` and `stringify()` follows the left ↠ 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 ↠ 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.
⚠️ Note: Per the RFC, "_If backward compatibility is not an issue, SHA-1 [Version 5] is preferred_."
### uuid.v4([options[, buffer[, offset]]])
Create an RFC version 4 (random) UUID
| | |
| --- | --- |
| [`options`] | `Object` with one or more of the following properties: |
| [`options.random`] | `Array` of 16 random bytes (0-255) |
| [`options.rng`] | Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) |
| [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` |
| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` |
| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` |
Example:
```javascript
import { v4 as uuidv4 } from 'uuid';
uuidv4(); // โจ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
```
Example using predefined `random` values:
```javascript
import { v4 as uuidv4 } from 'uuid';
const v4options = {
random: [
0x10,
0x91,
0x56,
0xbe,
0xc4,
0xfb,
0xc1,
0xea,
0x71,
0xb4,
0xef,
0xe1,
0x67,
0x1c,
0x58,
0x36,
],
};
uuidv4(v4options); // โจ '109156be-c4fb-41ea-b1b4-efe1671c5836'
```
### uuid.v5(name, namespace[, buffer[, offset]])
Create an RFC version 5 (namespace w/ SHA-1) UUID
| | |
| --- | --- |
| `name` | `String \| Array` |
| `namespace` | `String \| Array[16]` Namespace UUID |
| [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` |
| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` |
| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` |
Note: The RFC `DNS` and `URL` namespaces are available as `v5.DNS` and `v5.URL`.
Example with custom namespace:
```javascript
import { v5 as uuidv5 } from 'uuid';
// Define a custom namespace. Readers, create your own using something like
// https://www.uuidgenerator.net/
const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341';
uuidv5('Hello, World!', MY_NAMESPACE); // โจ '630eb68f-e0fa-5ecc-887a-7c7a62614681'
```
Example with RFC `URL` namespace:
```javascript
import { v5 as uuidv5 } from 'uuid';
uuidv5('https://www.w3.org/', uuidv5.URL); // โจ 'c106a26a-21bb-5538-8bf2-57095d1976c1'
```
### uuid.validate(str)
Test a string to see if it is a valid UUID
| | |
| --------- | --------------------------------------------------- |
| `str` | `String` to validate |
| _returns_ | `true` if string is a valid UUID, `false` otherwise |
Example:
```javascript
import { validate as uuidValidate } from 'uuid';
uuidValidate('not a UUID'); // โจ false
uuidValidate('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // โจ true
```
Using `validate` and `version` together it is possible to do per-version validation, e.g. validate for only v4 UUIds.
```javascript
import { version as uuidVersion } from 'uuid';
import { validate as uuidValidate } from 'uuid';
function uuidValidateV4(uuid) {
return uuidValidate(uuid) && uuidVersion(uuid) === 4;
}
const v1Uuid = 'd9428888-122b-11e1-b85c-61cd3cbb3210';
const v4Uuid = '109156be-c4fb-41ea-b1b4-efe1671c5836';
uuidValidateV4(v4Uuid); // โจ true
uuidValidateV4(v1Uuid); // โจ false
```
### uuid.version(str)
Detect RFC version of a UUID
| | |
| --------- | ---------------------------------------- |
| `str` | A valid UUID `String` |
| _returns_ | `Number` The RFC version of the UUID |
| _throws_ | `TypeError` if `str` is not a valid UUID |
Example:
```javascript
import { version as uuidVersion } from 'uuid';
uuidVersion('45637ec4-c85f-11ea-87d0-0242ac130003'); // โจ 1
uuidVersion('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // โจ 4
```
## Command Line
UUIDs can be generated from the command line using `uuid`.
```shell
$ uuid
ddeb27fb-d9a0-4624-be4d-4615062daed4
```
The default is to generate version 4 UUIDS, however the other versions are supported. Type `uuid --help` for details:
```shell
$ uuid --help
Usage:
uuid
uuid v1
uuid v3 <name> <namespace uuid>
uuid v4
uuid v5 <name> <namespace uuid>
uuid --help
Note: <namespace uuid> may be "URL" or "DNS" to use the corresponding UUIDs
defined by RFC4122
```
## ECMAScript Modules
This library comes with [ECMAScript Modules](https://www.ecma-international.org/ecma-262/6.0/#sec-modules) (ESM) support for Node.js versions that support it ([example](./examples/node-esmodules/)) as well as bundlers like [rollup.js](https://rollupjs.org/guide/en/#tree-shaking) ([example](./examples/browser-rollup/)) and [webpack](https://webpack.js.org/guides/tree-shaking/) ([example](./examples/browser-webpack/)) (targeting both, Node.js and browser environments).
```javascript
import { v4 as uuidv4 } from 'uuid';
uuidv4(); // โจ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
```
To run the examples you must first create a dist build of this library in the module root:
```shell
npm run build
```
## CDN Builds
### ECMAScript Modules
To load this module directly into modern browsers that [support loading ECMAScript Modules](https://caniuse.com/#feat=es6-module) you can make use of [jspm](https://jspm.org/):
```html
<script type="module">
import { v4 as uuidv4 } from 'https://jspm.dev/uuid';
console.log(uuidv4()); // โจ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
</script>
```
### UMD
To load this module directly into older browsers you can use the [UMD (Universal Module Definition)](https://github.com/umdjs/umd) builds from any of the following CDNs:
**Using [UNPKG](https://unpkg.com/uuid@latest/dist/umd/)**:
```html
<script src="https://unpkg.com/uuid@latest/dist/umd/uuidv4.min.js"></script>
```
**Using [jsDelivr](https://cdn.jsdelivr.net/npm/uuid@latest/dist/umd/)**:
```html
<script src="https://cdn.jsdelivr.net/npm/uuid@latest/dist/umd/uuidv4.min.js"></script>
```
**Using [cdnjs](https://cdnjs.com/libraries/uuid)**:
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/uuid/8.1.0/uuidv4.min.js"></script>
```
These CDNs all provide the same [`uuidv4()`](#uuidv4options-buffer-offset) method:
```html
<script>
uuidv4(); // โจ '55af1e37-0734-46d8-b070-a1e42e4fc392'
</script>
```
Methods for the other algorithms ([`uuidv1()`](#uuidv1options-buffer-offset), [`uuidv3()`](#uuidv3name-namespace-buffer-offset) and [`uuidv5()`](#uuidv5name-namespace-buffer-offset)) are available from the files `uuidv1.min.js`, `uuidv3.min.js` and `uuidv5.min.js` respectively.
## "getRandomValues() not supported"
This error occurs in environments where the standard [`crypto.getRandomValues()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) API is not supported. This issue can be resolved by adding an appropriate polyfill:
### React Native / Expo
1. Install [`react-native-get-random-values`](https://github.com/LinusU/react-native-get-random-values#readme)
1. Import it _before_ `uuid`. Since `uuid` might also appear as a transitive dependency of some other imports it's safest to just import `react-native-get-random-values` as the very first thing in your entry point:
```javascript
import 'react-native-get-random-values';
import { v4 as uuidv4 } from 'uuid';
```
Note: If you are using Expo, you must be using at least `[email protected]` and `[email protected]`.
### Web Workers / Service Workers (Edge <= 18)
[In Edge <= 18, Web Crypto is not supported in Web Workers or Service Workers](https://caniuse.com/#feat=cryptography) and we are not aware of a polyfill (let us know if you find one, please).
## Upgrading From `[email protected]`
### Only Named Exports Supported When Using with Node.js ESM
`[email protected]` did not come with native ECMAScript Module (ESM) support for Node.js. Importing it in Node.js ESM consequently imported the CommonJS source with a default export. This library now comes with true Node.js ESM support and only provides named exports.
Instead of doing:
```javascript
import uuid from 'uuid';
uuid.v4();
```
you will now have to use the named exports:
```javascript
import { v4 as uuidv4 } from 'uuid';
uuidv4();
```
### Deep Requires No Longer Supported
Deep requires like `require('uuid/v4')` [which have been deprecated in `[email protected]`](#deep-requires-now-deprecated) are no longer supported.
## Upgrading From `[email protected]`
"_Wait... what happened to `[email protected]` - `[email protected]`?!?_"
In order to avoid confusion with RFC [version 4](#uuidv4options-buffer-offset) and [version 5](#uuidv5name-namespace-buffer-offset) UUIDs, and a possible [version 6](http://gh.peabody.io/uuidv6/), releases 4 thru 6 of this module have been skipped.
### Deep Requires Now Deprecated
`[email protected]` encouraged the use of deep requires to minimize the bundle size of browser builds:
```javascript
const uuidv4 = require('uuid/v4'); // <== NOW DEPRECATED!
uuidv4();
```
As of `[email protected]` this library now provides ECMAScript modules builds, which allow packagers like Webpack and Rollup to do "tree-shaking" to remove dead code. Instead, use the `import` syntax:
```javascript
import { v4 as uuidv4 } from 'uuid';
uuidv4();
```
... or for CommonJS:
```javascript
const { v4: uuidv4 } = require('uuid');
uuidv4();
```
### Default Export Removed
`[email protected]` was exporting the Version 4 UUID method as a default export:
```javascript
const uuid = require('uuid'); // <== REMOVED!
```
This usage pattern was already discouraged in `[email protected]` and has been removed in `[email protected]`.
----
Markdown generated from [README_js.md](README_js.md) by [](https://github.com/broofa/runmd)
# hash-base
[](https://www.npmjs.org/package/hash-base)
[](https://travis-ci.org/crypto-browserify/hash-base)
[](https://david-dm.org/crypto-browserify/hash-base#info=dependencies)
[](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
# mustache.js - Logic-less {{mustache}} templates with JavaScript
> What could be more logical awesome than no logic at all?
[](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:

## 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
*
* <b>GitHub</b>
* <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
# emoji-regex [](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
| [](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.
<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
<p align="center">
<a href="https://parceljs.org/" target="_blank">
<img alt="Parcel" src="https://user-images.githubusercontent.com/19409/135924939-03845d0b-e7bb-414b-89b6-e627dfa9f614.png" width="749">
</a>
</p>
[](#backers) [](#sponsors)
[](https://dev.azure.com/devongovett/devongovett/_build/latest?definitionId=1)
[](https://www.npmjs.com/package/parcel)
[](https://www.npmjs.com/package/parcel)
[](https://discord.gg/XSCzqGRuvr)
[](https://twitter.com/parceljs)
Parcel is a zero configuration build tool for the web. It combines a great out-of-the-box development experience with a scalable architecture that can take your project from just getting started to massive production application.
## Features
- ๐ **Zero config** โ Parcel supports many languages and file types out of the box, from web technologies like HTML, CSS, and JavaScript, to assets like images, fonts, videos, and more. It has a built-in dev server with hot reloading, beautiful error diagnostics, and much more. No configuration needed!
- โก๏ธ **Lighting fast** โ Parcel's JavaScript compiler is written in Rust for native performance. Your code is built in parallel using worker threads, utilizing all of the cores on your machine. Everything is cached, so you never build the same code twice. It's like using watch mode, but even when you restart Parcel!
- ๐ **Automatic production optimization** โ Parcel optimizes your whole app for production automatically. This includes tree-shaking and minifying your JavaScript, CSS, and HTML, resizing and optimizing images, content hashing, automatic code splitting, and much more.
- ๐ฏ **Ship for any target** โ Parcel automatically transforms your code for your target environments. From modern and legacy browser support, to zero config JSX and TypeScript compilation, Parcel makes it easy to build for any target โ or many!
- ๐ **Scalable** โ Parcel requires zero configuration to get started. But as your application grows and your build requirements become more complex, it's possible to extend Parcel in just about every way. A simple configuration format and powerful plugin system that's designed from the ground up for performance means Parcel can support projects of any size.
## Getting Started
See the following guides in our documentation on how to get started with Parcel.
* [Building a webapp with Parcel](https://parceljs.org/getting-started/webapp/)
* [Building a library with Parcel](https://parceljs.org/getting-started/library/)
* [Migrating from Parcel v1](https://parceljs.org/getting-started/migration/)
## Documentation
Read the docs at https://parceljs.org/docs/.
## Community
- โ Ask questions on [GitHub Discussions](https://github.com/parcel-bundler/parcel/discussions).
- ๐ฌ Join the community on [Discord](https://discord.gg/XSCzqGRuvr).
- ๐ฃ Stay up to date on new features and announcements on [Twitter](https://twitter.com/parceljs).
## Contributors
This project exists thanks to all the people who contribute. [[Contribute]](CONTRIBUTING.md).
<a href="https://github.com/parcel-bundler/parcel/graphs/contributors"><img src="https://opencollective.com/parcel/contributors.svg?width=890" title="contributors" alt="contributors" /></a>
## Backers
Thank you to all our backers! ๐ [[Become a backer](https://opencollective.com/parcel#backer)]
<a href="https://opencollective.com/parcel#backers" target="_blank"><img src="https://opencollective.com/parcel/backers.svg?width=890"></a>
## Sponsors
Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/parcel#sponsor)]
<a href="https://opencollective.com/parcel/sponsor/0/website" target="_blank"><img src="https://opencollective.com/parcel/sponsor/0/avatar.svg"></a>
<a href="https://opencollective.com/parcel/sponsor/1/website" target="_blank"><img src="https://opencollective.com/parcel/sponsor/1/avatar.svg"></a>
<a href="https://opencollective.com/parcel/sponsor/2/website" target="_blank"><img src="https://opencollective.com/parcel/sponsor/2/avatar.svg"></a>
<a href="https://opencollective.com/parcel/sponsor/3/website" target="_blank"><img src="https://opencollective.com/parcel/sponsor/3/avatar.svg"></a>
<a href="https://opencollective.com/parcel/sponsor/4/website" target="_blank"><img src="https://opencollective.com/parcel/sponsor/4/avatar.svg"></a>
<a href="https://opencollective.com/parcel/sponsor/5/website" target="_blank"><img src="https://opencollective.com/parcel/sponsor/5/avatar.svg"></a>
<a href="https://opencollective.com/parcel/sponsor/6/website" target="_blank"><img src="https://opencollective.com/parcel/sponsor/6/avatar.svg"></a>
<a href="https://opencollective.com/parcel/sponsor/7/website" target="_blank"><img src="https://opencollective.com/parcel/sponsor/7/avatar.svg"></a>
<a href="https://opencollective.com/parcel/sponsor/8/website" target="_blank"><img src="https://opencollective.com/parcel/sponsor/8/avatar.svg"></a>
<a href="https://opencollective.com/parcel/sponsor/9/website" target="_blank"><img src="https://opencollective.com/parcel/sponsor/9/avatar.svg"></a>
<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.
[](https://npmjs.org/package/nodemon)
[](https://travis-ci.org/remy/nodemon) [](#backers) [](#sponsors)
# Installation
Either through cloning with git or by using [npm](http://npmjs.org) (the recommended way):
```bash
npm install -g nodemon # or using yarn: yarn global add 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 # or using yarn: yarn add nodemon -D
```
With a local installation, nodemon will not be available in your system path or you can't use it directly from the command line. 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.
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 ([ref](https://github.com/remy/nodemon/issues/14)).
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)! ๐
[](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)
<div style="overflow: hidden; margin-bottom: 80px;">
<a href='https://padlet.com/'><img src='https://images.opencollective.com/padlet/320fa3e/logo/256.png' style='object-fit: contain; float: left; margin:12px' height='120' width='120'></a><a href='https://topaussiecasinos.com/'>
<!-- generated with https://jqterm.com/8d123effeb793313c2a0ad559adbc6a4?query=def+getImage%3A%0A%09.+as+%24_+%7C%0A%09%7B+%0A++++++%22206432%22%3A+%22https%3A%2F%2Fuser-images.githubusercontent.com%2F13700%2F127474039-8ba5ac8c-2095-4984-9309-54ff15e95340.png%22%2C%0A%09++%22215800%22%3A+%22https%3A%2F%2Fuser-images.githubusercontent.com%2F13700%2F151881982-04677f3d-e2e1-44ee-a168-258b242b1ef4.svg%22%2C%0A++++++%22snyk%22%3A+%22https%3A%2F%2Fuser-images.githubusercontent.com%2F13700%2F165926338-ae9458ab-89c5-4c97-bc9b-86b5049576bf.png%22%0A++++%7D+%7C+%28.%5B%22%5C%28%24_.MemberId%29%22%5D+%2F%2F+%24_.image%29%0A%3B%0A%0Adef+getUrl%3A%0A%09.+as+%24_+%7C+%09%7B+%0A++++++%22snyk%22%3A+%22https%3A%2F%2Fsnyk.co%2Fnodemon%22%0A++++%7D+%7C+%28.%5B%22%5C%28%24_.MemberId%29%22%5D+%2F%2F+%24_.website%29%0A%3B%0A%0Adef+tohtml%3A%0A%09%22%3Ca+href%3D%27%5C%28getUrl%29%27%3E%3Cimg+src%3D%27%5C%28getImage%29%27+style%3D%27object-fit%3A+contain%3B+float%3A+left%3B+margin%3A12px%27+height%3D%27120%27+width%3D%27120%27%3E%3C%2Fa%3E%22%0A%3B%0A%0A.+%2B+%5B%7B%0A++isActive%3A+true%2C%0A++MemberId%3A+%22snyk%22%2C%0A++image%3A+true%2C%0A++createdAt%3A+%222022-04-29+12%3A00%3A00%22%0A%7D%5D+%7C+%0A%0Asort_by%28.createdAt%29+%7C+map%28select%28.isActive+%3D%3D+true+and+.image%29+%7C+tohtml%29+%7C+join%28%22%22%29&raw=true -->
<a href='https://najlepsibukmacherzy.pl/ranking-legalnych-bukmacherow/'><img src='https://opencollective-production.s3.us-west-1.amazonaws.com/52acecf0-608a-11eb-b17f-5bca7c67fe7b.png' style='object-fit: contain; float: left; margin:12px' height='120' width='120'></a><a href='https://topaussiecasinos.com/'><img src='https://opencollective-production.s3.us-west-1.amazonaws.com/89ea5890-6d1c-11ea-9dd9-330b3b2faf8b.png' style='object-fit: contain; float: left; margin:12px' height='120' width='120'></a><a href='https://netticasinohex.com/'><img src='https://opencollective-production.s3.us-west-1.amazonaws.com/b802aa50-7b1a-11ea-bcaf-0dc68ad9bc17.png' style='object-fit: contain; float: left; margin:12px' height='120' width='120'></a><a href='https://polskiekasynohex.com/'><img src='https://opencollective-production.s3.us-west-1.amazonaws.com/2bb0d6e0-99c8-11ea-9349-199aa0d5d24a.png' style='object-fit: contain; float: left; margin:12px' height='120' width='120'></a><a href='https://www.casinoonlineaams.com'><img src='https://opencollective-production.s3.us-west-1.amazonaws.com/a0694620-b88f-11eb-b3a4-b97529e4b911.png' style='object-fit: contain; float: left; margin:12px' height='120' width='120'></a><a href='https://casinowhizz.com'><img src='https://opencollective-production.s3.us-west-1.amazonaws.com/23256a80-f5c1-11eb-99f7-fbf8e4d6c6be.jpg' style='object-fit: contain; float: left; margin:12px' height='120' width='120'></a><a href='https://aussielowdepositcasino.com/'><img src='https://user-images.githubusercontent.com/13700/151881982-04677f3d-e2e1-44ee-a168-258b242b1ef4.svg' style='object-fit: contain; float: left; margin:12px' height='120' width='120'></a><a href='https://www.casinot.net'><img src='https://opencollective-production.s3.us-west-1.amazonaws.com/73b4fc10-7591-11ea-a1d4-01a20d893b4f.png' style='object-fit: contain; float: left; margin:12px' height='120' width='120'></a><a href='https://www.parhaatkasinot.com'><img src='https://opencollective-production.s3.us-west-1.amazonaws.com/4dfc1820-b6ee-11ea-9fa9-e39f53823609.png' style='object-fit: contain; float: left; margin:12px' height='120' width='120'></a><a href='https://www.cryptosnacks.org/bitcoin-casino/'><img src='https://opencollective-production.s3.us-west-1.amazonaws.com/db217a90-122f-11ec-81e8-594bc2daa9dc.png' style='object-fit: contain; float: left; margin:12px' height='120' width='120'></a><a href='https://www.kasinot.fi'><img src='https://logo.clearbit.com/www.kasinot.fi' style='object-fit: contain; float: left; margin:12px' height='120' width='120'></a><a href='https://betomania.pl/ranking-bukmacherow/'><img src='https://logo.clearbit.com/betomania.pl' style='object-fit: contain; float: left; margin:12px' height='120' width='120'></a><a href='https://www.targetedwebtraffic.com'><img src='https://logo.clearbit.com/targetedwebtraffic.com' style='object-fit: contain; float: left; margin:12px' height='120' width='120'></a><a href='https://casino-wise.com/'><img src='https://opencollective-production.s3.us-west-1.amazonaws.com/734011b0-46ac-11eb-8d3c-79b2cf7dfe51.png' style='object-fit: contain; float: left; margin:12px' height='120' width='120'></a><a href='https://www.paraskasino.fi'><img src='https://logo.clearbit.com/www.paraskasino.fi' style='object-fit: contain; float: left; margin:12px' height='120' width='120'></a><a href='https://freebets.ltd.uk'><img src='https://logo.clearbit.com/freebets.ltd.uk' style='object-fit: contain; float: left; margin:12px' height='120' width='120'></a><a href='https://www.thecasinodb.com'><img src='https://logo.clearbit.com/thecasinodb.com' style='object-fit: contain; float: left; margin:12px' height='120' width='120'></a><a href='https://online-casinos.xyz'><img src='https://opencollective-production.s3.us-west-1.amazonaws.com/bd4ff1f0-279b-11ec-9a5a-0519330cdfea.png' style='object-fit: contain; float: left; margin:12px' height='120' width='120'></a><a href='https://www.aceonlinecasino.co.uk'><img src='https://opencollective-production.s3.us-west-1.amazonaws.com/b3376c80-279f-11ec-9a5a-0519330cdfea.jpg' style='object-fit: contain; float: left; margin:12px' height='120' width='120'></a><a href='https://www.casinoutansvenskalicensen.se/'><img src='https://opencollective-production.s3.us-west-1.amazonaws.com/ed105cb0-b01f-11ec-935f-77c14be20a90.png' style='object-fit: contain; float: left; margin:12px' height='120' width='120'></a><a href='https://snyk.co/nodemon'><img src='https://user-images.githubusercontent.com/13700/165926338-ae9458ab-89c5-4c97-bc9b-86b5049576bf.png' style='object-fit: contain; float: left; margin:12px' height='120' width='120'></a><a href='https://online-casinos-australia.com/'><img src='https://opencollective-production.s3.us-west-1.amazonaws.com/88bb6d20-900a-11ec-8a5a-a92310c15e5b.jpg' style='object-fit: contain; float: left; margin:12px' height='120' width='120'></a>
</div>
# License
MIT [http://rem.mit-license.org](http://rem.mit-license.org)
# tar-fs
filesystem bindings for [tar-stream](https://github.com/mafintosh/tar-stream).
```
npm install tar-fs
```
[](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
# create-hmac
[](https://www.npmjs.org/package/create-hmac)
[](https://travis-ci.org/crypto-browserify/createHmac)
[](https://david-dm.org/crypto-browserify/createHmac#info=dependencies)
[](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
```
# 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 :)
[](https://www.npmjs.com/package/ci-info)
[](https://github.com/watson/ci-info/actions)
[](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)
[](https://www.npmjs.org/package/weak-lru-cache)
[](https://www.npmjs.org/package/weak-lru-cache)
[](LICENSE)
# weak-lru-cache
The weak-lru-cache package provides a powerful cache that works in harmony with the JS garbage collection (GC) and least-recently used (LRU) and least-freqently used (LFU) expiration strategy to help cache data with highly optimized cache retention. It uses LRU/LFU (LRFU) expiration to retain referenced data, and then once data has been inactive, it uses weak references (and finalization registry) to allow GC to remove the cached data as part of the normal GC cycles, but still continue to provide cached access to the data as long as it still resides in memory and hasn't been collected. This provides the best of modern expiration strategies combined with optimal GC interaction.
In a typical GC'ed VM, objects may continue to exist in memory long after they are no longer (strongly) referenced, but using a weak-referencing cached, we allow the GC to collect such data, but the cache can return this data up until the point it is garbaged collected, ensuring much more efficient use of memory.
This can also be used to ensure a single object identity per key. By storing an object in the cache for a given key, we can check the cache whenever we need that object, and before recreating it, thereby giving us the means to ensure we also use the same object for a given key as long as it still exists in memory.
This project is tested and run NodeJS and Deno (requires NodeJS v14.10 or higher or Node v13.0 with --harmony-weak-ref flag).
## Setup
Install with (NPM):
```
npm i weak-lru-cache
```
And `import` or `require` it to access the constructor:
```
import { WeakLRUCache } from 'weak-lru-cache';
let myCache = new WeakLRUCache();
myValue.setValue('key', { greeting: 'hello world' });
myValue.getValue('key') -> return the object above as long as it is still cached
```
Or in Deno, import directly from the [`weakcache` deno.land package](https://deno.land/x/weakcache):
```
import { WeakLRUCache } from 'https://deno.land/x/weakcache/index.js';
...
```
## Basic Usage
The `WeakLRUCache` class extends the native `Map` class and also includes the following methods, which are the primary intended interactions with the cache:
### getValue(key)
Gets the value referenced by the given key and returns it. If the value is no longer cached, will return undefined.
### setValue(key, value, expirationPriority?)
Sets or inserts the value into the cache, with the given key. This will create a new cache entry to reference your provided value. This also returns the cache entry.
The `key` can be any JS value.
If the `value` is an object, it will be stored in the cache, until it expires (as determined by the LRFU expiration policy), *and* is garbage collected. If you provide a primitive value (string, number, boolean, null, etc.), this can not be weakly referenced, so the value will still be stored in the LRFU cache, but once it expires, it will immediately be removed, rather than waiting for GC.
The `expirationPriority` is an optional directive indicating how quickly the cache entry should expire. A higher value will indicate the entry should expire sooner. This can be used to help limit the amount of memory used by cache if you are loading large objects. Using the default cache size, and entries with varied expirationPriority values, the expiration cache will typically hold a sum of about 100,000 of the expirationPriority values. This means that if you wanted to have a cache to stay around or under 100MB, you could provide the size, divided by 1000 (or using `>> 10` is much faster), as the expirationPriority:
```
myCache.setValue('key', bigObject, sizeOfObject >> 10);
```
The `expirationPriority` can also be set to `-1` that the value should be `pinned` in memory and never expire, until the entry has been changed (with a positive `expirationPriority`).
## `WeakLRUCache(options)` Constructor
The `WeakLRUCache` constructor supports an optional `options` object parameter that allows specific configuration and cache tuning. The following properties (all optional) can be defined on the `options` object:
### cacheSize
This indicates the number of entries to allocate in the cache. This defaults to 32,768, and the maximum allowed value is 16,777,216.
### expirer
By default there is a single shared expiration cache, that is a single instance of `LRFUExpirer`. However, you can define your own expiration cache or create separate instances of LRFUExpirer. Generally using a (the default) single instance is preferable since it naturally gives higher priority/recency to more heavily used caches, and allows lesser used caches to expire more of their entries.
You can also set this to `false` to indicate that no LRU/LRFU cache should be used and the cache should rely entirely on weak-references.
### deferRegister
This flag can be set to true to save key and cache information so that it can defer the finalization registration. This tends to be slightly faster for caches that are more heavily dominated by lots of entry replacements (multiple setValue calls to same entries before they expire). However, for (what is generally considered more typical) usage more dominated by setting values and getting them until they expire, the default setting will probably be faster.
## Using Cache Entries
The `WeakLRUCache` class extends the native `Map` class, and consequently, all the standard Map methods are available. As a Map, all the values are cache entries, which are typically `WeakRef` objects that hold a reference to the cached value, along with retention information. This means that the `get(key)` differs from `getValue(key)` in that it returns the cache entry, which references the value, rather than the value itself.
The cache entries also can contain metadata about the entry, including information about the cache entries position in the LRFU cache that informs when it will expire. However, you can also set your own properties on the cache entry to store you own metadata. This will be retained until the entry is removed/collected.
## License
MIT
# babel-plugin-polyfill-corejs3
## Install
Using npm:
```sh
npm install --save-dev babel-plugin-polyfill-corejs3
```
or using yarn:
```sh
yarn add babel-plugin-polyfill-corejs3 --dev
```
## Usage
Add this plugin to your Babel configuration:
```json
{
"plugins": [["polyfill-corejs3", { "method": "usage-global", "version": "3.20" }]]
}
```
This package supports the `usage-pure`, `usage-global`, and `entry-global` methods.
When `entry-global` is used, it replaces imports to `core-js`.
# concordance
Compare, format, diff and serialize any JavaScript value. Built for Node.js 10
and above.
## Behavior
Concordance recursively describes JavaScript values, whether they're booleans or
complex object structures. It recurses through all enumerable properties, list
items (e.g. arrays) and iterator entries.
The same algorithm is used when comparing, formatting or diffing values. This
means Concordance's behavior is consistent, no matter how you use it.
### Comparison details
* [Object wrappers](https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/types%20%26%20grammar/ch3.md#boxing-wrappers)
are compared both as objects and unwrapped values. Thus Concordance always
treats `Object(1)` as different from `1`.
* `-0` is distinct from `0`.
* `NaN` equals `NaN`.
* The `Argument` values can be compared to a regular array.
* `Error` names and messages are always compared, even if these are not
enumerable properties.
* `Function` values are compared by identity only. Names are always formatted
and serialized.
* `Global` objects are considered equal.
* `Map` keys and `Set` items are compared in-order.
* `Object` string properties are compared according to the [traversal order](http://2ality.com/2015/10/property-traversal-order-es6.html).
Symbol properties are compared by identity.
* `Promise` values are compared by identity only.
* `Symbol` values are compared by identity only.
* Recursion stops whenever a circular reference is encountered. If the same
cycle is present in the actual and expected values they're considered equal,
but they're unequal otherwise.
### Formatting details
Concordance strives to format every aspect of a value that is used for
comparisons. Formatting is optimized for human legibility.
Strings enjoy special formatting:
* When used as keys, line break characters are escaped
* Otherwise, multi-line strings are formatted using backticks, and line break
characters are replaced by [control pictures](http://graphemica.com/blocks/control-pictures).
Similarly, line breaks in symbol descriptions are escaped.
### Diffing details
Concordance tries to minimize diff lines. This is difficult with object values,
which may have similar properties but a different constructor. Multi-line
strings are compared line-by-line.
### Serialization details
Concordance can serialize any value for later use. Deserialized values can be
compared to each other or to regular JavaScript values. The deserialized
value should be passed as the **actual** value to the comparison and diffing
methods. Certain value comparisons behave differently when the **actual** value
is deserialized:
* `Argument` values can only be compared to other `Argument` values.
* `Function` values are compared by name.
* `Promise` values are compared by their constructor and additional enumerable
properties, but not by identity.
* `Symbol` values are compared by their string serialization. [Registered](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Shared_symbols_in_the_global_symbol_registry)
and [well-known symbols](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Well-known_symbols)
will never equal symbols with similar descriptions.
# create-hash
[](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')`
# get-caller-file
[](https://travis-ci.org/stefanpenner/get-caller-file)
[](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.
# nth-check [](https://travis-ci.org/fb55/nth-check)
Parses and compiles CSS nth-checks to highly optimized functions.
### 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()`. It can be used to check if a given index matches a given nth-rule, or to generate a sequence of indices matching a given nth-rule.
`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
import nthCheck, { parse, compile } from "nth-check";
```
##### `nthCheck(formula)`
Parses and compiles a formula to a highly optimized function. Combination of `parse` and `compile`.
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 the passed _index_ matches the formula.
**Note**: The nth-rule starts counting at `1`, the returned function at `0`.
**Example:**
```js
const check = nthCheck("2n+3");
check(0); // `false`
check(1); // `false`
check(2); // `true`
check(3); // `false`
check(4); // `true`
check(5); // `false`
check(6); // `true`
```
##### `parse(formula)`
Parses the expression, throws an `Error` if it fails. Otherwise, returns an array containing the integer step size and the integer offset of the nth rule.
**Example:**
```js
parse("2n+3"); // [2, 3]
```
##### `compile([a, b])`
Takes an array with two elements (as returned by `.parse`) and returns a highly optimized function.
**Example:**
```js
const check = compile([2, 3]);
check(0); // `false`
check(1); // `false`
check(2); // `true`
check(3); // `false`
check(4); // `true`
check(5); // `false`
check(6); // `true`
```
##### `generate([a, b])`
Returns a function that produces a monotonously increasing sequence of indices.
If the sequence has an end, the returned function will return `null` after the last index in the sequence.
**Example:** An always increasing sequence
```js
const gen = nthCheck.generate([2, 3]);
gen(); // `1`
gen(); // `3`
gen(); // `5`
gen(); // `8`
gen(); // `11`
```
**Example:** With an end value
```js
const gen = nthCheck.generate([-2, 5]);
gen(); // 0
gen(); // 2
gen(); // 4
gen(); // null
```
##### `sequence(formula)`
Parses and compiles a formula to a generator that produces a sequence of indices. Combination of `parse` and `generate`.
**Example:** An always increasing sequence
```js
const gen = nthCheck.sequence("2n+3");
gen(); // `1`
gen(); // `3`
gen(); // `5`
gen(); // `8`
gen(); // `11`
```
**Example:** With an end value
```js
const gen = nthCheck.sequence("-2n+5");
gen(); // 0
gen(); // 2
gen(); // 4
gen(); // null
```
---
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.
## `nth-check` for enterprise
Available as part of the Tidelift Subscription
The maintainers of `nth-check` 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-nth-check?utm_source=npm-nth-check&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
# cliui

[](https://www.npmjs.com/package/cliui)
[](https://conventionalcommits.org)

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`.
# 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).
<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).
LZ4 - Library Files
================================
The `/lib` directory contains many files, but depending on project's objectives,
not all of them are necessary.
#### Minimal LZ4 build
The minimum required is **`lz4.c`** and **`lz4.h`**,
which provides the fast compression and decompression algorithms.
They generate and decode data using the [LZ4 block format].
#### High Compression variant
For more compression ratio at the cost of compression speed,
the High Compression variant called **lz4hc** is available.
Add files **`lz4hc.c`** and **`lz4hc.h`**.
This variant also compresses data using the [LZ4 block format],
and depends on regular `lib/lz4.*` source files.
#### Frame support, for interoperability
In order to produce compressed data compatible with `lz4` command line utility,
it's necessary to use the [official interoperable frame format].
This format is generated and decoded automatically by the **lz4frame** library.
Its public API is described in `lib/lz4frame.h`.
In order to work properly, lz4frame needs all other modules present in `/lib`,
including, lz4 and lz4hc, and also **xxhash**.
So it's necessary to include all `*.c` and `*.h` files present in `/lib`.
#### Advanced / Experimental API
Definitions which are not guaranteed to remain stable in future versions,
are protected behind macros, such as `LZ4_STATIC_LINKING_ONLY`.
As the name strongly implies, these definitions should only be invoked
in the context of static linking ***only***.
Otherwise, dependent application may fail on API or ABI break in the future.
The associated symbols are also not exposed by the dynamic library by default.
Should they be nonetheless needed, it's possible to force their publication
by using build macros `LZ4_PUBLISH_STATIC_FUNCTIONS`
and `LZ4F_PUBLISH_STATIC_FUNCTIONS`.
#### Build macros
The following build macro can be selected to adjust source code behavior at compilation time :
- `LZ4_FAST_DEC_LOOP` : this triggers a speed optimized decompression loop, more powerful on modern cpus.
This loop works great on `x86`, `x64` and `aarch64` cpus, and is automatically enabled for them.
It's also possible to enable or disable it manually, by passing `LZ4_FAST_DEC_LOOP=1` or `0` to the preprocessor.
For example, with `gcc` : `-DLZ4_FAST_DEC_LOOP=1`,
and with `make` : `CPPFLAGS+=-DLZ4_FAST_DEC_LOOP=1 make lz4`.
- `LZ4_DISTANCE_MAX` : control the maximum offset that the compressor will allow.
Set to 65535 by default, which is the maximum value supported by lz4 format.
Reducing maximum distance will reduce opportunities for LZ4 to find matches,
hence will produce a worse compression ratio.
However, a smaller max distance can allow compatibility with specific decoders using limited memory budget.
This build macro only influences the compressed output of the compressor.
- `LZ4_DISABLE_DEPRECATE_WARNINGS` : invoking a deprecated function will make the compiler generate a warning.
This is meant to invite users to update their source code.
Should this be a problem, it's generally possible to make the compiler ignore these warnings,
for example with `-Wno-deprecated-declarations` on `gcc`,
or `_CRT_SECURE_NO_WARNINGS` for Visual Studio.
This build macro offers another project-specific method
by defining `LZ4_DISABLE_DEPRECATE_WARNINGS` before including the LZ4 header files.
- `LZ4_USER_MEMORY_FUNCTIONS` : replace calls to <stdlib>'s `malloc`, `calloc` and `free`
by user-defined functions, which must be called `LZ4_malloc()`, `LZ4_calloc()` and `LZ4_free()`.
User functions must be available at link time.
- `LZ4_FORCE_SW_BITCOUNT` : by default, the compression algorithm tries to determine lengths
by using bitcount instructions, generally implemented as fast single instructions in many cpus.
In case the target cpus doesn't support it, or compiler intrinsic doesn't work, or feature bad performance,
it's possible to use an optimized software path instead.
This is achieved by setting this build macros .
In most cases, it's not expected to be necessary,
but it can be legitimately considered for less common platforms.
- `LZ4_ALIGN_TEST` : alignment test ensures that the memory area
passed as argument to become a compression state is suitably aligned.
This test can be disabled if it proves flaky, by setting this value to 0.
#### Amalgamation
lz4 source code can be amalgamated into a single file.
One can combine all source code into `lz4_all.c` by using following command:
```
cat lz4.c lz4hc.c lz4frame.c > lz4_all.c
```
(`cat` file order is important) then compile `lz4_all.c`.
All `*.h` files present in `/lib` remain necessary to compile `lz4_all.c`.
#### Windows : using MinGW+MSYS to create DLL
DLL can be created using MinGW+MSYS with the `make liblz4` command.
This command creates `dll\liblz4.dll` and the import library `dll\liblz4.lib`.
To override the `dlltool` command when cross-compiling on Linux, just set the `DLLTOOL` variable. Example of cross compilation on Linux with mingw-w64 64 bits:
```
make BUILD_STATIC=no CC=x86_64-w64-mingw32-gcc DLLTOOL=x86_64-w64-mingw32-dlltool OS=Windows_NT
```
The import library is only required with Visual C++.
The header files `lz4.h`, `lz4hc.h`, `lz4frame.h` and the dynamic library
`dll\liblz4.dll` are required to compile a project using gcc/MinGW.
The dynamic library has to be added to linking options.
It means that if a project that uses LZ4 consists of a single `test-dll.c`
file it should be linked with `dll\liblz4.dll`. For example:
```
$(CC) $(CFLAGS) -Iinclude/ test-dll.c -o test-dll dll\liblz4.dll
```
The compiled executable will require LZ4 DLL which is available at `dll\liblz4.dll`.
#### Miscellaneous
Other files present in the directory are not source code. They are :
- `LICENSE` : contains the BSD license text
- `Makefile` : `make` script to compile and install lz4 library (static and dynamic)
- `liblz4.pc.in` : for `pkg-config` (used in `make install`)
- `README.md` : this file
[official interoperable frame format]: ../doc/lz4_Frame_format.md
[LZ4 block format]: ../doc/lz4_Block_format.md
#### License
All source material within __lib__ directory are BSD 2-Clause licensed.
See [LICENSE](LICENSE) for details.
The license is also reminded at the top of each source file.
# 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 :)
[](https://www.npmjs.com/package/is-ci)
[](https://travis-ci.org/watson/is-ci)
[](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)
# nullthrows
[](https://travis-ci.org/zertosh/nullthrows)
A [flow](https://flowtype.org) typed utility that accepts `value` (e.g. `nullthrows(value)`) and throws if `value` is `null` or `undefined`, otherwise it returns `value`.
Also see [`invariant`](https://github.com/zertosh/invariant).
# 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
```
[](http://travis-ci.org/mafintosh/tar-stream)
[](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
# 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.
# 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
# is-yarn-global
[](https://travis-ci.org/LitoMore/is-yarn-global)
[](https://www.npmjs.com/package/is-yarn-global)
[](https://github.com/LitoMore/is-yarn-global/blob/master/LICENSE)
[](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)
# Arg [](https://circleci.com/gh/zeit/arg)
`arg` is yet another command line option parser.
## Installation
Use Yarn or NPM to install.
```console
$ yarn add arg
```
or
```console
$ npm install arg
```
## Usage
`arg()` takes either 1 or 2 arguments:
1. Command line specification object (see below)
2. Parse options (_Optional_, defaults to `{permissive: false, argv: process.argv.slice(2), stopAtPositional: false}`)
It returns an object with any values present on the command-line (missing options are thus
missing from the resulting object). Arg performs no validation/requirement checking - we
leave that up to the application.
All parameters that aren't consumed by options (commonly referred to as "extra" parameters)
are added to `result._`, which is _always_ an array (even if no extra parameters are passed,
in which case an empty array is returned).
```javascript
const arg = require('arg');
// `options` is an optional parameter
const args = arg(spec, options = {permissive: false, argv: process.argv.slice(2)});
```
For example:
```console
$ node ./hello.js --verbose -vvv --port=1234 -n 'My name' foo bar --tag qux --tag=qix -- --foobar
```
```javascript
// hello.js
const arg = require('arg');
const args = arg({
// Types
'--help': Boolean,
'--version': Boolean,
'--verbose': arg.COUNT, // Counts the number of times --verbose is passed
'--port': Number, // --port <number> or --port=<number>
'--name': String, // --name <string> or --name=<string>
'--tag': [String], // --tag <string> or --tag=<string>
// Aliases
'-v': '--verbose',
'-n': '--name', // -n <string>; result is stored in --name
'--label': '--name' // --label <string> or --label=<string>;
// result is stored in --name
});
console.log(args);
/*
{
_: ["foo", "bar", "--foobar"],
'--port': 1234,
'--verbose': 4,
'--name': "My name",
'--tag': ["qux", "qix"]
}
*/
```
The values for each key=>value pair is either a type (function or [function]) or a string (indicating an alias).
- In the case of a function, the string value of the argument's value is passed to it,
and the return value is used as the ultimate value.
- In the case of an array, the only element _must_ be a type function. Array types indicate
that the argument may be passed multiple times, and as such the resulting value in the returned
object is an array with all of the values that were passed using the specified flag.
- In the case of a string, an alias is established. If a flag is passed that matches the _key_,
then the _value_ is substituted in its place.
Type functions are passed three arguments:
1. The parameter value (always a string)
2. The parameter name (e.g. `--label`)
3. The previous value for the destination (useful for reduce-like operations or for supporting `-v` multiple times, etc.)
This means the built-in `String`, `Number`, and `Boolean` type constructors "just work" as type functions.
Note that `Boolean` and `[Boolean]` have special treatment - an option argument is _not_ consumed or passed, but instead `true` is
returned. These options are called "flags".
For custom handlers that wish to behave as flags, you may pass the function through `arg.flag()`:
```javascript
const arg = require('arg');
const argv = ['--foo', 'bar', '-ff', 'baz', '--foo', '--foo', 'qux', '-fff', 'qix'];
function myHandler(value, argName, previousValue) {
/* `value` is always `true` */
return 'na ' + (previousValue || 'batman!');
}
const args = arg({
'--foo': arg.flag(myHandler),
'-f': '--foo'
}, {
argv
});
console.log(args);
/*
{
_: ['bar', 'baz', 'qux', 'qix'],
'--foo': 'na na na na na na na na batman!'
}
*/
```
As well, `arg` supplies a helper argument handler called `arg.COUNT`, which equivalent to a `[Boolean]` argument's `.length`
property - effectively counting the number of times the boolean flag, denoted by the key, is passed on the command line..
For example, this is how you could implement `ssh`'s multiple levels of verbosity (`-vvvv` being the most verbose).
```javascript
const arg = require('arg');
const argv = ['-AAAA', '-BBBB'];
const args = arg({
'-A': arg.COUNT,
'-B': [Boolean]
}, {
argv
});
console.log(args);
/*
{
_: [],
'-A': 4,
'-B': [true, true, true, true]
}
*/
```
### Options
If a second parameter is specified and is an object, it specifies parsing options to modify the behavior of `arg()`.
#### `argv`
If you have already sliced or generated a number of raw arguments to be parsed (as opposed to letting `arg`
slice them from `process.argv`) you may specify them in the `argv` option.
For example:
```javascript
const args = arg(
{
'--foo': String
}, {
argv: ['hello', '--foo', 'world']
}
);
```
results in:
```javascript
const args = {
_: ['hello'],
'--foo': 'world'
};
```
#### `permissive`
When `permissive` set to `true`, `arg` will push any unknown arguments
onto the "extra" argument array (`result._`) instead of throwing an error about
an unknown flag.
For example:
```javascript
const arg = require('arg');
const argv = ['--foo', 'hello', '--qux', 'qix', '--bar', '12345', 'hello again'];
const args = arg(
{
'--foo': String,
'--bar': Number
}, {
argv,
permissive: true
}
);
```
results in:
```javascript
const args = {
_: ['--qux', 'qix', 'hello again'],
'--foo': 'hello',
'--bar': 12345
}
```
#### `stopAtPositional`
When `stopAtPositional` is set to `true`, `arg` will halt parsing at the first
positional argument.
For example:
```javascript
const arg = require('arg');
const argv = ['--foo', 'hello', '--bar'];
const args = arg(
{
'--foo': Boolean,
'--bar': Boolean
}, {
argv,
stopAtPositional: true
}
);
```
results in:
```javascript
const args = {
_: ['hello', '--bar'],
'--foo': true
};
```
### Errors
Some errors that `arg` throws provide a `.code` property in order to aid in recovering from user error, or to
differentiate between user error and developer error (bug).
##### ARG_UNKNOWN_OPTION
If an unknown option (not defined in the spec object) is passed, an error with code `ARG_UNKNOWN_OPTION` will be thrown:
```js
// cli.js
try {
require('arg')({ '--hi': String });
} catch (err) {
if (err.code === 'ARG_UNKNOWN_OPTION') {
console.log(err.message);
} else {
throw err;
}
}
```
```shell
node cli.js --extraneous true
Unknown or unexpected option: --extraneous
```
# License
Copyright © 2017-2019 by ZEIT, Inc. Released under the [MIT License](LICENSE.md).
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.
# Borsh JS
[](https://opensource.org/licenses/Apache-2.0)
[](https://opensource.org/licenses/MIT)
[](https://discord.gg/Vyp7ETM)
[](https://travis-ci.com/near/borsh-js)
[](https://npmjs.com/borsh)
[](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
# react-refresh
This package implements the wiring necessary to integrate Fast Refresh into bundlers. Fast Refresh is a feature that lets you edit React components in a running application without losing their state. It is similar to an old feature known as "hot reloading", but Fast Refresh is more reliable and officially supported by React.
This package is primarily aimed at developers of bundler plugins. If youโre working on one, here is a [rough guide](https://github.com/facebook/react/issues/16604#issuecomment-528663101) for Fast Refresh integration using this package.
# tslib
This is a runtime library for [TypeScript](http://www.typescriptlang.org/) that contains all of the TypeScript helper functions.
This library is primarily used by the `--importHelpers` flag in TypeScript.
When using `--importHelpers`, a module that uses helper functions like `__extends` and `__assign` in the following emitted file:
```ts
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
exports.x = {};
exports.y = __assign({}, exports.x);
```
will instead be emitted as something like the following:
```ts
var tslib_1 = require("tslib");
exports.x = {};
exports.y = tslib_1.__assign({}, exports.x);
```
Because this can avoid duplicate declarations of things like `__extends`, `__assign`, etc., this means delivering users smaller files on average, as well as less runtime overhead.
For optimized bundles with TypeScript, you should absolutely consider using `tslib` and `--importHelpers`.
# Installing
For the latest stable version, run:
## npm
```sh
# TypeScript 2.3.3 or later
npm install tslib
# TypeScript 2.3.2 or earlier
npm install [email protected]
```
## yarn
```sh
# TypeScript 2.3.3 or later
yarn add tslib
# TypeScript 2.3.2 or earlier
yarn add [email protected]
```
## bower
```sh
# TypeScript 2.3.3 or later
bower install tslib
# TypeScript 2.3.2 or earlier
bower install [email protected]
```
## JSPM
```sh
# TypeScript 2.3.3 or later
jspm install tslib
# TypeScript 2.3.2 or earlier
jspm install [email protected]
```
# Usage
Set the `importHelpers` compiler option on the command line:
```
tsc --importHelpers file.ts
```
or in your tsconfig.json:
```json
{
"compilerOptions": {
"importHelpers": true
}
}
```
#### For bower and JSPM users
You will need to add a `paths` mapping for `tslib`, e.g. For Bower users:
```json
{
"compilerOptions": {
"module": "amd",
"importHelpers": true,
"baseUrl": "./",
"paths": {
"tslib" : ["bower_components/tslib/tslib.d.ts"]
}
}
}
```
For JSPM users:
```json
{
"compilerOptions": {
"module": "system",
"importHelpers": true,
"baseUrl": "./",
"paths": {
"tslib" : ["jspm_packages/npm/tslib@1.[version].0/tslib.d.ts"]
}
}
}
```
# Contribute
There are many ways to [contribute](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md) to TypeScript.
* [Submit bugs](https://github.com/Microsoft/TypeScript/issues) and help us verify fixes as they are checked in.
* Review the [source code changes](https://github.com/Microsoft/TypeScript/pulls).
* Engage with other TypeScript users and developers on [StackOverflow](http://stackoverflow.com/questions/tagged/typescript).
* Join the [#typescript](http://twitter.com/#!/search/realtime/%23typescript) discussion on Twitter.
* [Contribute bug fixes](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md).
# Documentation
* [Quick tutorial](http://www.typescriptlang.org/Tutorial)
* [Programming handbook](http://www.typescriptlang.org/Handbook)
* [Homepage](http://www.typescriptlang.org/)
# set-blocking
[](https://travis-ci.org/yargs/set-blocking)
[](https://www.npmjs.com/package/set-blocking)
[](https://coveralls.io/r/yargs/set-blocking?branch=master)
[](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
# unicode-property-aliases-ecmascript [](https://travis-ci.org/mathiasbynens/unicode-property-aliases-ecmascript) [](https://www.npmjs.com/package/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 Unicodeโs `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'
```
## For maintainers
### How to publish a new release
1. On the `main` branch, bump the version number in `package.json`:
```sh
npm version patch -m 'Release v%s'
```
Instead of `patch`, use `minor` or `major` [as needed](https://semver.org/).
Note that this produces a Git commit + tag.
1. Push the release commit and tag:
```sh
git push && git push --tags
```
Our CI then automatically publishes the new release to npm.
## Author
| [](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.
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`
# 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'));
```
bs58
====
[](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:
[](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
# is-json
<a href="https://nodei.co/npm/is-json/"><img src="https://nodei.co/npm/is-json.png?downloads=true"></a>
[](https://travis-ci.org/joaquimserafim/is-json)
check if a string is a valid JSON string without using Try/Catch and is a JSON object
**V1.2**
isJSON(str*, [passObjects=bool])
*with `passObjects = true` can pass a JSON object in `str`, default to `false`
var isJSON = require('is-json');
var good_json = '{"a":"obja","b":[0,1,2],"c":{"d":"some object"}}';
var bad_json = '{"a":"obja""b":[0,1,2],"c":{"d":"some object"}}';
var str_number = '121212';
console.log(isJSON(good_json)); // true
console.log(isJSON(bad_json)); // false
console.log(isJSON(str_number)); // false
// check is an object
var object = {a: 12, b: [1,2,3]};
console.log(isJSON(object, true)); // true
// can use isJSON.strict (uses try/catch) if wants something more robust
console.log(isJSON.strict('{\n "config": 123,\n "test": "abcde" \n}')); // true
# balanced-match
Match balanced string pairs, like `{` and `}` or `<b>` and `</b>`. Supports regular expressions as well!
[](http://travis-ci.org/juliangruber/balanced-match)
[](https://www.npmjs.org/package/balanced-match)
[](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 <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# 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).
# color-convert
[](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 © 2011-2016, Heather Arthur and Josh Junon. Licensed under the [MIT License](LICENSE).
[](https://www.npmjs.com/package/esprima)
[](https://www.npmjs.com/package/esprima)
[](https://travis-ci.org/jquery/esprima)
[](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).
# Javascript Error Polyfill
[](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
# 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`.
# Node.js releases data
All data is located in `data` directory.
`data/raw` contains raw data `nodejs.json` and `iojs.json`.
`data/processed` contains `envs.js` with both node.js and io.js data preprocessed to be used by [Browserslist](https://github.com/ai/browserslist) and other projects. Each version in this file contains only necessary info: version, release date and optionally LTS flag.
## Installation
```bash
npm install --save node-releases
```
## Updating data
```bash
npm run build
```
This is a build script which fetches data from web, processes it and saves processed data to `data/processed/envs.json`. If you want to run this steps separately you can use commands described below.
### Fetching data
```bash
npm run fetch
```
This npm script will download new data to `data/raw` directory. Also it'll download Node.js release schedule into `release-schedule` folder.
### Processing data
```bash
npm run process
```
This script generates `envs.json` file from raw data files and saves it to `data/processed` directory.
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<[Response](#class-response)></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<Buffer></code>
Consume the body and return a promise that will resolve to a Buffer.
#### body.textConverted()
<small>*(node-fetch extension)*</small>
* Returns: <code>Promise<String></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"`.
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`
# node-supports-preserve-symlinks-flag <sup>[![Version Badge][npm-version-svg]][package-url]</sup>
[![github actions][actions-image]][actions-url]
[![coverage][codecov-image]][codecov-url]
[![dependency status][deps-svg]][deps-url]
[![dev dependency status][dev-deps-svg]][dev-deps-url]
[![License][license-image]][license-url]
[![Downloads][downloads-image]][downloads-url]
[![npm badge][npm-badge-png]][package-url]
Determine if the current node version supports the `--preserve-symlinks` flag.
## Example
```js
var supportsPreserveSymlinks = require('node-supports-preserve-symlinks-flag');
var assert = require('assert');
assert.equal(supportsPreserveSymlinks, null); // in a browser
assert.equal(supportsPreserveSymlinks, false); // in node < v6.2
assert.equal(supportsPreserveSymlinks, true); // in node v6.2+
```
## Tests
Simply clone the repo, `npm install`, and run `npm test`
[package-url]: https://npmjs.org/package/node-supports-preserve-symlinks-flag
[npm-version-svg]: https://versionbadg.es/inspect-js/node-supports-preserve-symlinks-flag.svg
[deps-svg]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag.svg
[deps-url]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag
[dev-deps-svg]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag/dev-status.svg
[dev-deps-url]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag#info=devDependencies
[npm-badge-png]: https://nodei.co/npm/node-supports-preserve-symlinks-flag.png?downloads=true&stars=true
[license-image]: https://img.shields.io/npm/l/node-supports-preserve-symlinks-flag.svg
[license-url]: LICENSE
[downloads-image]: https://img.shields.io/npm/dm/node-supports-preserve-symlinks-flag.svg
[downloads-url]: https://npm-stat.com/charts.html?package=node-supports-preserve-symlinks-flag
[codecov-image]: https://codecov.io/gh/inspect-js/node-supports-preserve-symlinks-flag/branch/main/graphs/badge.svg
[codecov-url]: https://app.codecov.io/gh/inspect-js/node-supports-preserve-symlinks-flag/
[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/node-supports-preserve-symlinks-flag
[actions-url]: https://github.com/inspect-js/node-supports-preserve-symlinks-flag/actions
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.
# htmlnano
[](http://badge.fury.io/js/htmlnano)

Modular HTML minifier, built on top of the [PostHTML](https://github.com/posthtml/posthtml). Inspired by [cssnano](http://cssnano.co/).
## [Benchmark](https://github.com/maltsev/html-minifiers-benchmark/blob/master/README.md)
[[email protected]]: https://www.npmjs.com/package/html-minifier-terser
[[email protected]]: https://www.npmjs.com/package/htmlnano
| Website | Source (KB) | [[email protected]] | [[email protected]] |
|---------|------------:|----------------:|-----------:|
| [stackoverflow.blog](https://stackoverflow.blog/) | 90 | 82 | 76 |
| [github.com](https://github.com/) | 232 | 203 | 173 |
| [en.wikipedia.org](https://en.wikipedia.org/wiki/Main_Page) | 81 | 76 | 75 |
| [npmjs.com](https://www.npmjs.com/features) | 43 | 40 | 38 |
| [tc39.es](https://tc39.es/ecma262/) | 6001 | 5465 | 5459 |
| **Avg. minify rate** | 0% | **9%** | **13%** |
## Documentation
https://htmlnano.netlify.app
# 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.
# unicode-match-property-value-ecmascript [](https://travis-ci.org/mathiasbynens/unicode-match-property-value-ecmascript) [](https://www.npmjs.com/package/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
```
## For maintainers
### How to publish a new release
1. On the `main` branch, bump the version number in `package.json`:
```sh
npm version patch -m 'Release v%s'
```
Instead of `patch`, use `minor` or `major` [as needed](https://semver.org/).
Note that this produces a Git commit + tag.
1. Push the release commit and tag:
```sh
git push && git push --tags
```
Our CI then automatically publishes the new release to npm.
## Author
| [](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.
# 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)
# 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*/
});
```
# 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
# binary-parse-stream
Painless streaming binary protocol parsers using generators.
## Installation
npm install binary-parse-stream
## Synchronous
This module uses the exact same generator interface as [binary-parse-stream](https://github.com/nathan7/binary-parse-stream), which presents a synchronous interface to a generator parser.
## Usage
```js
const BinaryParseStream = require('binary-parse-stream')
const {One} = BinaryParseStream // -1
```
BinaryParseStream is a TransformStream that consumes buffers and outputs objects on the other end.
It expects your subclass to implement a `_parse` method that is a generator.
When your generator yields a number, it'll be fed a buffer of that length from the input.
If it yields -1, it'll be given the value of the first byte instead of a single-byte buffer.
When your generator returns, the return value will be pushed to the output side.
## Example
The following module parses a protocol that consists of a 32-bit unsigned big-endian type parameter, an unsigned 8-bit length parameter, and a buffer of the specified length.
It outputs `{type, buf}` objects.
```js
class SillyProtocolParseStream extends BinaryParseStream {
constructor(options) {
super(options)
this.count = 0
}
*_parse() {
const type = (yield 4).readUInt32BE(0, true)
const length = yield -1
const buf = yield length
this.count++
return {type, buf}
}
}
```
There is also a shorter syntax for when you don't want to explicitly subclass: `BinaryParseStream.extend(function*())`.
# jsesc [](https://travis-ci.org/mathiasbynens/jsesc) [](https://coveralls.io/r/mathiasbynens/jsesc) [](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
| [](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.
<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
# 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
<div align="center">
<img src="./logo/logo-web.svg" width="348.61" height="100" alt="SVGO logo"/>
</div>
## SVGO [](https://npmjs.org/package/svgo) [](https://discord.gg/z8jX8NYxrE)
**SVG O**ptimizer is a Node.js-based tool for optimizing SVG vector graphics files.
## 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.
## Installation
```sh
npm -g install svgo
```
or
```sh
yarn global add svgo
```
## CLI usage
```sh
svgo one.svg two.svg -o one.min.svg two.min.svg
```
Or use the `--folder`/`-f` flag to optimize a whole folder of SVG icons
```sh
svgo -f ./path/to/folder/with/svg/files -o ./path/to/folder/with/svg/output
```
See help for advanced usage
```sh
svgo --help
```
## Configuration
Some options can be configured with CLI though it may be easier to have the configuration in a separate file.
SVGO automatically loads configuration from `svgo.config.js` or module specified with `--config` flag.
```js
module.exports = {
multipass: true, // boolean. false by default
datauri: 'enc', // 'base64', 'enc' or 'unenc'. 'base64' by default
js2svg: {
indent: 2, // string with spaces or number of spaces. 4 by default
pretty: true, // boolean, false by default
},
};
```
SVGO has a plugin-based architecture, so almost every optimization is a separate plugin.
There is a set of [built-in plugins](#built-in-plugins). See how to configure them:
```js
module.exports = {
plugins: [
// enable a built-in plugin by name
'prefixIds',
// or by expanded version
{
name: 'prefixIds',
},
// some plugins allow/require to pass options
{
name: 'prefixIds',
params: {
prefix: 'my-prefix',
},
},
],
};
```
The default preset of plugins is fully overridden if the `plugins` field is specified.
Use `preset-default` plugin to customize plugins options.
```js
module.exports = {
plugins: [
{
name: 'preset-default',
params: {
overrides: {
// customize options for plugins included in preset
inlineStyles: {
onlyMatchedOnce: false,
},
// or disable plugins
removeDoctype: false,
},
},
},
// enable builtin plugin not included in default preset
'prefixIds',
// enable and configure builtin plugin not included in preset
{
name: 'sortAttrs',
params: {
xmlnsOrder: 'alphabetical',
},
},
],
};
```
Default preset includes the following list of plugins:
- removeDoctype
- removeXMLProcInst
- removeComments
- removeMetadata
- removeEditorsNSData
- cleanupAttrs
- mergeStyles
- inlineStyles
- minifyStyles
- cleanupIDs
- removeUselessDefs
- cleanupNumericValues
- convertColors
- removeUnknownsAndDefaults
- removeNonInheritableGroupAttrs
- removeUselessStrokeAndFill
- removeViewBox
- cleanupEnableBackground
- removeHiddenElems
- removeEmptyText
- convertShapeToPath
- convertEllipseToCircle
- moveElemsAttrsToGroup
- moveGroupAttrsToElems
- collapseGroups
- convertPathData
- convertTransform
- removeEmptyAttrs
- removeEmptyContainers
- mergePaths
- removeUnusedNS
- sortDefsChildren
- removeTitle
- removeDesc
It's also possible to specify a custom plugin:
```js
const anotherCustomPlugin = require('./another-custom-plugin.js');
module.exports = {
plugins: [
{
name: 'customPluginName',
type: 'perItem', // 'perItem', 'perItemReverse' or 'full'
params: {
optionName: 'optionValue',
},
fn: (ast, params, info) => {},
},
anotherCustomPlugin,
],
};
```
## API usage
SVGO provides a few low level utilities.
### optimize
The core of SVGO is `optimize` function.
```js
const { optimize } = require('svgo');
const result = optimize(svgString, {
// optional but recommended field
path: 'path-to.svg',
// all config fields are also available here
multipass: true,
});
const optimizedSvgString = result.data;
```
### loadConfig
If you write a tool on top of SVGO you might need a way to load SVGO config.
```js
const { loadConfig } = require('svgo');
const config = await loadConfig();
// you can also specify a relative or absolute path and customize the current working directory
const config = await loadConfig(configFile, cwd);
```
## Built-in plugins
| Plugin | Description | Default |
| ------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- |
| [cleanupAttrs](https://github.com/svg/svgo/blob/master/plugins/cleanupAttrs.js) | cleanup attributes from newlines, trailing, and repeating spaces | `enabled` |
| [mergeStyles](https://github.com/svg/svgo/blob/master/plugins/mergeStyles.js) | merge multiple style elements into one | `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 the `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 | `disabled` |
| [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 attributes 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` attributes | `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` |
## Other Ways to Use SVGO
- as a web app โ [SVGOMG](https://jakearchibald.github.io/svgomg/)
- as a GitHub Action โ [SVGO Action](https://github.com/marketplace/actions/svgo-action)
- 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 a macOS app - [Image Shrinker](https://image-shrinker.com)
- as a Rollup plugin - [rollup-plugin-svgo](https://github.com/porsager/rollup-plugin-svgo)
- as a VS Code plugin - [vscode-svgo](https://github.com/1000ch/vscode-svgo)
- as a Atom plugin - [atom-svgo](https://github.com/1000ch/atom-svgo)
- as a Sublime plugin - [Sublime-svgo](https://github.com/1000ch/Sublime-svgo)
- as a Figma plugin - [Advanced SVG Export](https://www.figma.com/c/plugin/782713260363070260/Advanced-SVG-Export)
- as a Linux app - [Oh My SVG](https://github.com/sonnyp/OhMySVG)
- as a Browser extension - [SVG Gobbler](https://github.com/rossmoody/svg-gobbler)
- as an API - [Vector Express](https://github.com/smidyo/vectorexpress-api#convertor-svgo)
## Donators
| [<img src="https://sheetjs.com/sketch128.png" width="80">](https://sheetjs.com/) | [<img src="https://raw.githubusercontent.com/fontello/fontello/master/fontello-image.svg" width="80">](https://fontello.com/) |
| :------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------------------------: |
| [SheetJS LLC](https://sheetjs.com/) | [Fontello](https://fontello.com/) |
## License and Copyright
This software is released under the terms of the [MIT license](https://github.com/svg/svgo/blob/master/LICENSE).
Logo by [Andrรฉ Castillo](https://github.com/DerianAndre).
# 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.
The `dist-raw` directory contains JS sources that are distributed verbatim, not compiled nor typechecked via TS.
To implement ESM support, we unfortunately must duplicate some of node's built-in functionality that is not
exposed via an API. We have copy-pasted the necessary code from https://github.com/nodejs/node/tree/master/lib
then modified it to suite our needs.
Formatting may be intentionally bad to keep the diff as small as possible, to make it easier to merge
upstream changes and understand our modifications. For example, when we need to wrap node's source code
in a factory function, we will not indent the function body, to avoid whitespace changes in the diff.
One obvious problem with this approach: the code has been pulled from one version of node, whereas users of ts-node
run multiple versions of node.
Users running node 12 may see that ts-node behaves like node 14, for example.
## `raw` directory
Within the `raw` directory, we keep unmodified copies of the node source files. This allows us to use diffing tools to
compare files in `raw` to those in `dist-raw`, which will highlight all of the changes we have made. Hopefully, these
changes are as minimal as possible.
## Naming convention
Not used consistently, but the idea is:
`node-<directory>(...-<directory>)-<filename>.js`
`node-internal-errors.js` -> `github.com/nodejs/node/blob/TAG/lib/internal/errors.js`
So, take the path within node's `lib/` directory, and replace slashes with hyphens.
In the `raw` directory, files are suffixed with the version number or revision from which
they were downloaded.
If they have a `stripped` suffix, this means they have large chunks of code deleted, but no other modifications.
This is useful when diffing. Sometimes our `dist-raw` files only have a small part of a much larger node source file.
It is easier to diff `raw/*-stripped.js` against `dist-raw/*.js`.
# 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.
[](https://www.npmjs.com/package/mdn-data)
[](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.
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')`
# <img src="docs_app/assets/Rx_Logo_S.png" alt="RxJS Logo" width="86" height="86"> RxJS: Reactive Extensions For JavaScript
[](https://circleci.com/gh/ReactiveX/rxjs/tree/6.x)
[](http://badge.fury.io/js/%40reactivex%2Frxjs)
[](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/
# sha.js
[](https://www.npmjs.org/package/sha.js)
[](https://travis-ci.org/crypto-browserify/sha.js)
[](https://david-dm.org/crypto-browserify/sha.js#info=dependencies)
[](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)
|
Jwhiles_rust-cryptic-comment | Cargo.toml
README.md
frontend
README.md
netlify.toml
package.json
public
index.html
manifest.json
robots.txt
rollup.config.js
src
index.css
near
config.ts
index.ts
react-app-env.d.ts
setupTests.ts
todo.md
tsconfig.json
src
lib.rs
main.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)
# RUST CrYPtiC ComMMENT
## WHAT IS IT
A simple comment system, designed to be dropped into a silly website that could use comments. For example, [my website](www.johnwhiles.com). It makes commentors pay to post comments.
### WHy?
I think making people pay to use your website is probably an easy and effective way to avoid spam. Also because I wanted to understand wot a crypto is. Also I wanted to write RUST.
### INSPIRATION
* Smart Parking Meters
* Having seen comments on other websites
## How to Use it
WIP
You need
RUSTUP
NPM
THE NEAR CLI
Then run `make` in your command line and follow the help I guess?
## Hi John
if you are reading this, you've forgotten how this project works.
there are two parts.
* The backend is in rust, and is deployed to near manually, by you. Run make build and then make deploy to publish a new version. Any chances to the data model will require migration
* The frontend is a small react app
|
pienkowb_figment-learn | README.md
SUMMARY.md
figment-learn
all-tutorials.md
contribute.md
pathways.md
guides
datahub-infrastructure.md
datahub-products.md
getting-started-with-datahub.md
rate-limits.md
introduction
what-is-datahub.md
what-is-figment-learn.md
why-build-on-web3.md
network-documentation
avalanche
README.md
avalanche-101.md
rpc-and-rest-api
README.md
avm-api.md
evm-api.md
info-api.md
platform-api.md
tutorials
README.md
create-a-local-test-network.md
create-a-new-blockchain.md
create-a-new-virtual-machine.md
create-a-subnet.md
creating-a-fixed-cap-asset.md
creating-a-variable-cap-asset.md
creating-an-nft-part-1.md
deploy-a-smart-contract-on-avalanche-using-remix-and-metamask.md
transfer-avax-tokens-between-chains.md
celo
README.md
celo-101.md
rpc-and-rest-api
README.md
web3.-.net.md
web3.bzz.md
web3.eth.abi.md
web3.eth.accounts.md
web3.eth.contract.md
web3.eth.ens.md
web3.eth.iban.md
web3.eth.md
web3.eth.personal.md
web3.eth.subscribe.md
web3.md
web3.shh.md
web3.utils.md
tutorial
README.md
hello-celo.md
hello-contracts.md
hello-mobile-dapp.md
cosmos
README.md
cosmos-101.md
enriched-apis
README.md
transaction-search.md
rpc-and-rest-api
README.md
cosmos-lcd.md
tendermint-rpc.md
tutorials
README.md
build-a-polling-app.md
build-a-scavenger-game
README.md
app.md
cli.md
handler.md
keeper.md
messages.md
module.md
play.md
querier.md
run.md
scaffold.md
the-game.md
create-a-blog-app.md
create-a-transaction-search-widget.md
untitled-3
README.md
alias.md
application-goals.md
buyname.md
delete-name.md
errors.md
expected-keepers.md
key.md
msgs-and-handlers.md
queriers.md
setname.md
start-your-application.md
the-keeper.md
types.md
untitled-10.md
untitled-2.md
untitled-3.md
untitled-4.md
untitled-5.md
untitled-7.md
untitled-8.md
untitled-9.md
untitled.md
extra-guides
5xx-retry-logic-best-practices
5xx-retry-logic-best-practices-go.md
5xx-retry-logic-best-practices-nodejs.md
5xx-retry-logic-best-practices-python.md
5xx-retry-logic-best-practices-ruby.md
README.md
README.md
docker-setup-for-windows.md
filecoin
README.md
filecoin-101.md
rpc-and-rest-api
README.md
miner-reputation-system-api.md
near
README.md
near-101.md
near-pathway.md
near-wallet.md
rpc-and-rest-api
README.md
near-rpc.md
tutorials
1.-connecting-to-a-near-node-using-datahub.md
2.-creating-your-first-near-account-using-the-sdk.md
3.-querying-the-near-blockchain.md
4.-submitting-your-first-transactions.md
5.-writing-and-deploying-your-first-near-smart-contract.md
README.md
cross-contract-calls.md
simple-webassembly-script.md
write-nft-contracts-in-rust.md
network-guide.md
oasis
README.md
oasis-101.md
rpc-and-rest-api
README.md
oasis-rest-api.md
secret
README.md
rpc-and-rest-api
README.md
secret-rest-api.md
tendermint-rpc.md
secret-101.md
secret-pathway.md
tutorials
1.-connecting-to-a-secret-node-using-datahub.md
2.-setting-up-your-wallet.md
3.-querying-the-secret-blockchain.md
4.-submit-your-first-transaction.md
5.-writing-and-deploying-your-first-secret-contract.md
README.md
terra
README.md
enriched-apis
README.md
transaction-search.md
rpc-and-rest-api
README.md
tendermint-rpc-1.md
terra-lcd.md
terra-101.md
tutorials
README.md
integrating-transaction-search-in-your-terra-wallet.md
interacting-with-terra-endpoints.md
setting-up-your-first-wallet.md
submit-your-first-transaction.md
write-your-first-smart-contract.md
tezos
README.md
rpc-and-rest-api-1
README.md
protocol-alpha.md
shell.md
tezos-101.md
tutorials
README.md
creating-nfts.md
oracle-contracts.md
token-contracts.md
other
glossary.md
support.md
terms-and-conditions
contributor-terms.md
privacy-policy.md
terms-of-use.md
| ---
description: A collection of guides to support your learning experience
---
# ๐ Extra Guides
## Review our extra guides!
Sometimes tutorials do not cover all the pre-requisites in details, or you might need some help to streamline debugging.
Here's a collection of extra guides to support your learning experience. Let's make sure you can spend most of your time learning and building!
## Docker Setup for Windows
{% page-ref page="docker-setup-for-windows.md" %}
## **5XX Retry Logic Best Practices**
{% page-ref page="5xx-retry-logic-best-practices/" %}
---
description: See all tutorials currently available for Terra
---
# ๐ก Tutorials
## Time to learn
On this page you can find all tutorials currently available for Terra, including all tutorials created by the community.
Don't forget that you can try them out [**via Datahub**](https://datahub.figment.io/sign_up?service=terra)!
#### [Join our community today](https://discord.gg/fszyM7K) if you want to interact with other builders and become a part of this growing ecosystem!
## Connecting to a Terra node with DataHub
{% page-ref page="interacting-with-terra-endpoints.md" %}
## Creating your first Terra account with the Terra SDK
{% page-ref page="submit-your-first-transaction.md" %}
## Querying the Terra blockchain
{% page-ref page="setting-up-your-first-wallet.md" %}
## Submit your first transactions
{% page-ref page="write-your-first-smart-contract.md" %}
## Integrating Transaction Search in your DApp
{% page-ref page="integrating-transaction-search-in-your-terra-wallet.md" %}
---
description: Learn how to interact with NEAR using DataHub
---
# ๐ NEAR
## Welcome to the NEAR documentation!
In this section, you will be able to learn about what makes NEAR special and how you can leverage available tools to build amazing products!
Check out the NEAR 101 section to learn more about the protocol and see how it compares to other networks in terms of speed, cost, and functionalities.
You can then get started with the available RPC & REST APIs we support [**via DataHub**](https://datahub.figment.io/sign_up?service=near).
Last but not least, if you are looking for guidelines or simply some inspiration, check out our list of available tutorials!
Be sure to check out the [**official NEAR documentation**](https://docs.near.org/docs/roles/developer/quickstart) ****and if you need tokens to build on testnet, you can check out the [**link here**](https://wallet.testnet.near.org).
๐ Let's start building the decentralized web ๐
{% page-ref page="near-101.md" %}
{% page-ref page="rpc-and-rest-api/" %}
{% page-ref page="near-pathway.md" %}
{% page-ref page="tutorials/" %}
{% page-ref page="near-wallet.md" %}
---
description: Learn what Celo APIs are available via DataHub and how to use them
---
# ๐ฎ RPC & REST API
## Time to play
Celo uses ContractKit, a library to help developers and validators to interact with the Celo blockchain and is well suited to developers looking for an easy way to integrate Celo Smart Contracts within their applications. Although the[ **Web3 library**](https://web3js.readthedocs.io/) was intended to be used only with Ethereum, due to the nature of Celo, we can still use the majority of its features. The ContractKit, for every interaction with the node, uses a Web3 instance.
Learn about the API available via Celo [**DataHub**](https://datahub.figment.io/sign_up?service=celo) below.
{% page-ref page="web3.md" %}
{% page-ref page="web3.eth.md" %}
{% page-ref page="web3.eth.subscribe.md" %}
{% page-ref page="web3.eth.contract.md" %}
{% page-ref page="web3.eth.accounts.md" %}
{% page-ref page="web3.eth.personal.md" %}
{% page-ref page="web3.eth.ens.md" %}
{% page-ref page="web3.eth.iban.md" %}
{% page-ref page="web3.eth.abi.md" %}
{% page-ref page="web3.-.net.md" %}
{% page-ref page="web3.bzz.md" %}
{% page-ref page="web3.shh.md" %}
{% page-ref page="web3.utils.md" %}
---
description: Learn how to interact with Celo using DataHub
---
# ๐ฐ Celo
## Welcome to the Celo documentation!
In this section, you will be able to learn about what makes Celo special and how you can leverage available tools to build amazing products!
Check out the Celo 101 section to learn more about the protocol and see how it compares to other networks in terms of speed, cost, and functionalities.
You can then get started with the available RPC & REST APIs we support [**via DataHub**](https://datahub.figment.io/sign_up?service=celo).
Last but not least, if you are looking for guidelines or simply some inspiration, check out our list of available tutorials!
Be sure to check out the [**official Celo documentation**](https://docs.celo.org/) and if you need tokens to build on testnet, you can check out the [**link here**](https://celo.org/developers/faucet).
๐ Let's start building the decentralized web ๐
{% page-ref page="celo-101.md" %}
{% page-ref page="rpc-and-rest-api/" %}
{% page-ref page="tutorial/" %}
---
description: Learn how to interact with the Secret Network using DataHub
---
# ๐คซ Secret
## Welcome to the Secret documentation!
In this section, you will be able to learn about what makes Secret special and how you can leverage available tools to build amazing products!
Check out the Secret 101 section to learn more about the protocol and see how it compares to other networks in terms of speed, cost, and functionalities.
You can then get started with the available RPC & REST APIs we support [**via DataHub**](https://datahub.figment.io/sign_up?service=secret).
Last but not least, if you are looking for guidelines or simply some inspiration, check out our list of available tutorials!
Be sure to check out the [**official Secret documentation**](https://build.scrt.network/) ****and if you need tokens to build on testnet, you can check out the [**link here**](https://faucet.secrettestnet.io/).
We also invite you to join the Secret community on their [Discord](http://chat.scrt.network) channel and on the [Secret Forum](http://forum.scrt.network) to go deeper into Secret development.
๐ Let's start building the decentralized web ๐
{% page-ref page="secret-101.md" %}
{% page-ref page="rpc-and-rest-api/" %}
{% page-ref page="secret-pathway.md" %}
{% page-ref page="tutorials/" %}
---
description: Learn about DataHub's Enriched APIs for Cosmos
---
# ๐ Enriched APIs
## Overview
The common network APIs should only be the beginning of the journey for Web 3 developers. Figment is developing Enriched APIs to help developers unlock the unique features and attributes of Web 3 protocols. Our suite of Enriched APIs allows developers to create powerful applications at a fraction of the cost, with the potential to capitalize on blockchain-native use cases.
Enriched APIs complement the common APIs to give its users superpowers in order to create the Web 3's killer apps.
Try them out today with [**DataHub**](https://datahub.figment.io/sign_up?service=cosmos)!
Check out the list of available Enriched APIs on Cosmos below.
## Transaction Search
The first Enriched API available on Cosmos DataHub is the Transaction Search API. It allows users to filter and query by account, transaction type, and date range. Users can also search by memo field and logs. Developers can now manipulate transaction data the way they want to instead of the way the blockchain intended them to. Transaction Search cuts significant indexing and development time as well as maintenance resources.
The Transaction Search API documentation for Cosmos can be found below.
{% page-ref page="transaction-search.md" %}
---
description: Review best practices to deal with 5XX errors
---
# 5XX Retry Logic Best Practices
## Introduction
Since DataHub is a proxy that passes through errors from full node software, our users will need to adopt defensive strategies for interacting with the API.
We are making it easy for our users to do the right thing and providing examples of pseudo-code to copy/paste.
For Example:
```ruby
tries = 3
begin
r = RestClient.get(...)
rescue
tries -= 1
retry if tries > 0
end
```
### **The basics of a retry**
To decide when to retry a request, we need to consider what to look for. There are a handful of HTTP status codes that you can check against. This will let your retry logic differentiate between a failed request that is appropriate to retryโlike a gateway errorโand one that isn'tโlike a 404. In our examples, we will use **408, 500, 502, 503, 504, 522, and 524.**
The next consideration we want is how often to retry. We will start with a delay, then increase it each additional time. This is a concept known as "back-off". The time between requests will grow with each attempt. Finally, we'll also need to decide how many attempts to make before giving up.
**Here's an example of the logic we'll be using in pseudo-code:**
* If total attempts > attempts, continue
* if status code type matches, continue
* if \(now - delay\) > last attempt, try request
* else, return to the start
**Let's explore the best practices for NodeJs, Pyhton, Ruby, and Go:**
{% page-ref page="5xx-retry-logic-best-practices-nodejs.md" %}
{% page-ref page="5xx-retry-logic-best-practices-python.md" %}
{% page-ref page="5xx-retry-logic-best-practices-ruby.md" %}
{% page-ref page="5xx-retry-logic-best-practices-go.md" %}
---
description: Learn what NEAR APIs are available via DataHub and how to use them
---
# ๐ฎ RPC & REST API
## Time to play
NEAR exposes a single RPC to enable the development of applications on the NEAR protocol.
Learn about the APIs available via NEAR [**DataHub**](https://datahub.figment.io/sign_up?service=near) ****below.
## NEAR RPC
{% page-ref page="near-rpc.md" %}
---
description: Learn about DataHub's Enriched APIs for Terra
---
# ๐ Enriched APIs
## Overview
The common network APIs should only be the beginning of the journey for Web 3 developers. Figment is developing Enriched APIs to help developers unlock the unique features and attributes of Web 3 protocols. Our suite of Enriched APIs allows developers to create powerful applications at a fraction of the cost, with the potential to capitalize on blockchain-native use cases.
Enriched APIs complement the common APIs to give its users superpowers in order to create the Web 3's killer apps.
Try them out today with [**DataHub**](https://datahub.figment.io/sign_up?service=terra)!
Check out the list of available Enriched APIs on Terra below.
## Transaction Search
The first Enriched API available on Terra DataHub is the Transaction Search API. It allows users to filter and query by account, transaction type, and date range. Users can also search by memo field and logs. Developers can now manipulate transaction data the way they want to instead of the way the blockchain intended them to. Transaction Search cuts significant indexing and development time as well as maintenance resources.
The Transaction Search API documentation for Terra can be found below.
{% page-ref page="transaction-search.md" %}
---
description: Learn how to interact with Terra using DataHub
---
# ๐ Terra
## Welcome to the Terra documentation!
In this section, you will be able to learn about what makes Terra special and how you can leverage available tools to build amazing products!
Check out the Terra 101 section to learn more about the protocol and see how it compares to other networks in terms of speed, cost, and functionalities.
You can then get started with the available RPC & REST APIs we support [**via DataHub**](https://datahub.figment.io/sign_up?service=terra).
Last but not least, if you are looking for guidelines or simply some inspiration, check out our list of available tutorials!
Be sure to check out the [**official Terra documentation**](https://docs.terra.money/) and if you need tokens to build on testnet, you can check out the [**link here**](https://faucet.terra.money/).
๐ Let's start building the decentralized web ๐
{% page-ref page="terra-101.md" %}
{% page-ref page="rpc-and-rest-api/" %}
{% page-ref page="enriched-apis/" %}
{% page-ref page="tutorials/" %}
---
description: Learn how to interact with Cosmos using DataHub
---
# ๐ Cosmos
## Welcome to the Cosmos documentation!
In this section, you will be able to learn about what makes Cosmos special and how you can leverage available tools to build amazing products!
Check out the Cosmos 101 section to learn more about the protocol and see how it compares to other networks in terms of speed, cost, and functionalities.
You can then get started with the available RPC & REST APIs we support [**via DataHub**](https://datahub.figment.io/sign_up?service=cosmos).
Last but not least, if you are looking for guidelines or simply some inspiration, check out our list of available tutorials!
Be sure to check out the [**official Cosmos documentation**](https://docs.cosmos.network/) ****and if you need tokens to build on testnet, you can check out the [**link here**](https://github.com/cosmos/faucet).
๐ Let's start building the decentralized web ๐
{% page-ref page="cosmos-101.md" %}
{% page-ref page="rpc-and-rest-api/" %}
{% page-ref page="enriched-apis/" %}
{% page-ref page="tutorials/" %}
---
description: See all tutorials currently available for Secret
---
# ๐ก Tutorials
## Time to learn
On this page you can find all tutorials currently available for Secret, including all tutorials created by the community.
Don't forget that you can try them out [**via Datahub**](https://datahub.figment.io/sign_up?service=secret)!
#### [Join our community today](https://discord.gg/fszyM7K) if you want to interact with other builders and become a part of this growing ecosystem!
## Connect to a Secret node with DataHub
{% page-ref page="1.-connecting-to-a-secret-node-using-datahub.md" %}
## Create your first Secret account
{% page-ref page="2.-setting-up-your-wallet.md" %}
## Query the Secret blockchain
{% page-ref page="3.-querying-the-secret-blockchain.md" %}
## Submit your first Secret transaction
{% page-ref page="4.-submit-your-first-transaction.md" %}
## Write & deploy your first Secret smart contract
{% page-ref page="5.-writing-and-deploying-your-first-secret-contract.md" %}
---
description: Learn what makes Web 3 protocols unique and how to use them
---
# ๐ Welcome to Figment Learn
##  The Web 3 Knowledge Base
**Figment has embarked on a mission to introduce more developers to Web 3 by simplifying the experience for its users and shining the light on Web 3โs potential.**
Learn is the education and onboarding platform for developers interested in Web 3 development. With Learn, developers gain access to the most comprehensive developer portal which standardizes documentation across networks and offers in-depth practical tutorials to help you get to the next level.
Tutorials can be completed seamlessly with [**DataHub**](https://datahub.figment.io/sign_up) which provides easy access to the protocols via our highly available full node infrastructure and suite of middleware. To foster its community, Figment is partnering with foundations to reward developers for building on Web 3 protocols and sharing their knowledge with others.
**Figment Learn is the Web 3 Knowledge Base.**
## ๐บ **Learn Pathways**
Learn Pathways are short curriculums that help developers understand which network is right for them and how to interact with Web 3 protocols at every step. As they complete the tutorials, developers earn protocol tokens offered by foundations to help align their interests with the network.
**Ongoing Pathway - NEAR:**
{% page-ref page="network-documentation/near/near-pathway.md" %}
**Ongoing Pathway - Secret:**
{% page-ref page="network-documentation/secret/secret-pathway.md" %}
**See other active and upcoming Pathways:**
{% page-ref page="figment-learn/pathways.md" %}
## ๐ก **Learn Tutorials**
Follow along and build amazing apps on Web 3 protocols with the help of Learn Tutorials created by community experts.
{% page-ref page="figment-learn/all-tutorials.md" %}
## ๐ **Get Started with DataHub**
\*\*\*\*[**DataHub**](https://datahub.figment.io/sign_up) lets developers use the most powerful and unique features of a blockchain without having to become protocol experts. With DataHub, developers now have access to Web 3 protocols through enterprise-grade infrastructure and APIs suite.
## ๐ Network **Documentation**
All your favorite networks' documentation in the same format under the same roof. Find what you are looking for in seconds, compare Web 3 protocols, and get to work.
---
description: Learn how to build a nameservice application with the Cosmos SDK
---
# Build a nameservice application
[**The original tutorial can be found in the Cosmos SDK documentation here**](https://tutorials.cosmos.network/nameservice/tutorial/00-intro.html#).
## Getting Started <a id="getting-started"></a>
In this tutorial, you will build a functional [Cosmos SDK](https://github.com/cosmos/cosmos-sdk/) application and, in the process, learn the basic concepts and structures of the SDK. The example will showcase how quickly and easily you can **build your own blockchain from scratch** on top of the Cosmos SDK.
By the end of this tutorial you will have a functional `nameservice` application, a mapping of strings to other strings \(`map[string]string`\). This is similar to [Namecoin](https://namecoin.org/), [ENS](https://ens.domains/), or [Handshake](https://handshake.org/), which all model the traditional DNS systems \(`map[domain]zonefile`\). Users will be able to buy unused names, or sell/trade their name.
All of the final source code for this tutorial project is in this directory \(and compiles\). However, it is best to follow along manually and try building the project yourself!
## Requirements
* [`golang` >1.13.0](https://golang.org/doc/install) installed
* Github account and either [Github CLI](https://hub.github.com/) or [Github Desktop \(64-bit required\)](https://help.github.com/en/desktop/getting-started-with-github-desktop/installing-github-desktop)
* Desire to create your own blockchain!
* The [scaffold tool](https://github.com/cosmos/scaffold) will be used to go through this tutorial. Clone the repo and install with `git clone [email protected]:cosmos/scaffold.git && cd scaffold && make`. Check out the repo for more detailed instructions.
## Tutorial
Through the course of this tutorial you will create the following files that make up your application:
```javascript
./nameservice
โโโ Makefile
โโโ Makefile.ledger
โโโ app.go
โโโ cmd
โ โโโ nscli
โ โ โโโ main.go
โ โโโ nsd
โ โโโ main.go
โโโ go.mod
โโโ go.sum
โโโ x
โโโ nameservice
โโโ alias.go
โโโ client
โ โโโ cli
โ โ โโโ query.go
โ โ โโโ tx.go
โ โโโ rest
โ โโโ query.go
โ โโโ rest.go
โ โโโ tx.go
โโโ genesis.go
โโโ handler.go
โโโ keeper
โ โโโ keeper.go
โ โโโ querier.go
โโโ types
โ โโโ codec.go
โ โโโ errors.go
โ โโโ expected_keepers.go
โ โโโ key.go
โ โโโ msgs.go
โ โโโ querier.go
โ โโโ types.go
โโโ module.go
```
Follow along! The first step describes the design of your application.
---
description: Learn what Tezos APIs are available via DataHub and how to use them
---
# ๐ฎ RPC & REST API
## Time to play
Tezos exposes a single RPC from which we have whitelisted all methods under [**/chains**](https://tezos.gitlab.io/api/rpc.html#protocol-alpha), including every method under โ[**Protocol Alpha**](https://tezos.gitlab.io/api/rpc.html#protocol-alpha)โ. More methods can be whitelisted based on your needs, feel free to reach out to [**[email protected]**](mailto:[email protected]) to notify us.
Learn about the API available via Tezos [**DataHub**](https://datahub.figment.io/sign_up?service=tezos) below.
{% page-ref page="shell.md" %}
{% page-ref page="protocol-alpha.md" %}
---
description: Learn what Filecoin APIs are available via DataHub and how to use them
---
# ๐ฎ RPC & REST API
## Time to play
Figment has created a Reputation System API to track miner performance on the Filecoin network.
Learn about the APIs available via Filecoin [**DataHub**](https://datahub.figment.io/) ****below.
## Filecoin Reputation System API by Figment
{% page-ref page="miner-reputation-system-api.md" %}
---
description: Learn what Secret APIs are available via DataHub and how to use them
---
# ๐ฎ RPC & REST API
## Time to play
Secret exposes both the Tendermint RPC and the Secret REST API which are both necessary for the development of applications on the Secret network.
Learn about the APIs available via Secret [**DataHub**](https://datahub.figment.io/sign_up?service=secret) below.
{% page-ref page="tendermint-rpc.md" %}
{% page-ref page="secret-rest-api.md" %}
---
description: Learn what Avalanche APIs are available via DataHub and how to use them
---
# ๐ฎ RPC & REST API
## Time to play
Avalancheโs Primary Network contains three blockchains with unique APIs and methods.
****Learn about the APIs available via Avalanche [**DataHub**](https://datahub.figment.io/sign_up?service=avalanche) below.
{% page-ref page="platform-api.md" %}
{% page-ref page="evm-api.md" %}
{% page-ref page="avm-api.md" %}
{% page-ref page="info-api.md" %}
---
description: Learn how to interact with Oasis using DataHub
---
# ๐ Oasis
## Welcome to the Oasis documentation!
In this section, you will be able to learn about what makes Oasis special and how you can leverage available tools to build amazing products!
Check out the Oasis 101 section to learn more about the protocol and see how it compares to other networks in terms of speed, cost, and functionalities.
You can then get started with the available RPC & REST APIs we support [**via DataHub**](https://datahub.figment.io/sign_up?service=oasis).
Last but not least, if you are looking for guidelines or simply some inspiration, check out our list of available tutorials!
Be sure to check out the[ **official Oasis documentation**](https://docs.oasis.dev/general/) ****and if you need tokens to build on testnet, please log in to the Oasis Dashboard at [dashboard.oasiscloud.io](https://dashboard.oasiscloud.io/).
๐ Let's start building the decentralized web ๐
{% page-ref page="oasis-101.md" %}
{% page-ref page="rpc-and-rest-api/" %}
---
description: See all tutorials currently available for NEAR
---
# ๐ก Tutorials
## Time to learn
On this page you can find all tutorials currently available for NEAR, including all tutorials created by the community.
Don't forget that you can try them out [**via Datahub**](https://datahub.figment.io/sign_up?service=near)!
#### [Join our community today](https://discord.gg/fszyM7K) if you want to interact with other builders and become a part of this growing ecosystem!
## Connect to a NEAR node using DataHub
{% page-ref page="1.-connecting-to-a-near-node-using-datahub.md" %}
## Create your first NEAR account using the NEAR Javascript API
{% page-ref page="2.-creating-your-first-near-account-using-the-sdk.md" %}
## Query the NEAR blockchain
{% page-ref page="3.-querying-the-near-blockchain.md" %}
## Submit your first transactions
{% page-ref page="4.-submitting-your-first-transactions.md" %}
## Write & deploy your first NEAR smart contract
{% page-ref page="5.-writing-and-deploying-your-first-near-smart-contract.md" %}
## Cross-contract calls
{% page-ref page="cross-contract-calls.md" %}
## Simple WebAssembly Script
{% page-ref page="simple-webassembly-script.md" %}
## Write an NFT contract & mint your NFT
{% page-ref page="write-nft-contracts-in-rust.md" %}
---
description: Learn how to build a scavenger game using the Cosmos SDK
---
# Build a scavenger game
[**The original tutorial can be found in the Cosmos SDK documentation here**](https://tutorials.cosmos.network/scavenge/tutorial/01-background.html).
## Background
The goal of this session is to get you thinking about what is possible when developing applications that have access to **digital scarcity as a primitive**. The easiest way to think of scarcity is as money; If money grew on trees it would stop being _scarce_ and stop having value. We have a long history of software which deals with money, but it's never been a first class citizen in the programming environment. Instead, money has always been represented as a number or a float, and it has been up to a third party merchant service or some other process of exchange where the _representation_ of money is swapped for actual cash. If money were a primitive in a software environment, it would allow for **real economies to exist within games and applications**, taking one step further in erasing the line between games, life and play.
We will be working today with a Golang framework called the [Cosmos SDK](https://github.com/cosmos/cosmos-sdk). This framework makes it easy to build **deterministic state machines**. A state machine is simply an application that has a state and explicit functions for updating that state. You can think of a light bulb and a light switch as a kind of state machine: the state of the "application" is either `light on` or `light off`. There is one function in this state machine: `flip switch`. Every time you trigger `flip switch` the state of the application goes from `light on` to `light off` or vice versa. Simple, right?
A **deterministic** state machine is just a state machine in which an accumulation of actions, taken together and replayed, will have the same outcome. So if we were to take all the `switch on` and `switch off` actions of the entire month of January for some room and replay then in August, we should have the same final state of `light on` or `light off`. There's should be nothing about January or August that changes the outcome \(of course a _real_ room might not be deterministic if there were things like power shortages or maintenance that took place during those periods\).
What is nice about deterministic state machines is that you can track changes with **cryptographic hashes** of the state, just like version control systems like `git`. If there is agreement about the hash of a certain state, it is unnecessary to replay every action from genesis to ensure that two repos are in sync with each other. These properties are useful when dealing with software that is run by many different people in many different situations, just like git.
Another nice property of cryptographically hashing state is that it creates a system of **reliable dependencies**. I can build software that uses your library and reference a specific state in your software. That way if you change your code in a way that breaks my code, I don't have to use your new version but can continue to use the version that I reference. This same property of knowing exactly what the state of a system \(as well as all the ways that state can update\) makes it possible to have the necessary assurances that allow for digital scarcity within an application. _If I say there is only one of some thing within a state machine and you know that there is no way for that state machine to create more than one, you can rely on there always being only one._
You might have guessed by now that what I'm really talking about are **Blockchains**. These are deterministic state machines which have very specific rules about how state is updated. They checkpoint state with cryptographic hashes and use asymmetric cryptography to handle **access control**. There are different ways that different Blockchains decide who can make a checkpoint of state. These entities can be called **Validators**. Some of them are chosen by an electricity intensive game called **proof-of-work** in tandem with something called the longest chain rule or **Nakamoto Consensus** on Blockchains like Bitcoin or Ethereum.
The state machine we are building will use an implementation of **proof-of-stake** called **Tendermint**, which is energy efficient and can consist of one or many validators, either trusted or byzantine. When building a system that handles _real_ scarcity, the integrity of that system becomes very important. One way to ensure that integrity is by sharing the responsibility of maintaining it with a large group of independently motivated participants as validators.
So, now that we know a little more about **why** we might build an app like this, let's dive into the game itself.
---
description: Learn what Oasis APIs are available via DataHub and how to use them
---
# ๐ฎ RPC & REST API
## Time to play
Oasis exposes a single RPC to enable the development of applications on the Oasis network.
Learn about the APIs available via Oasis [**DataHub**](https://datahub.figment.io/sign_up?service=oasis) ****below.
## Oasis REST API by Figment
{% page-ref page="oasis-rest-api.md" %}
---
description: Learn how to interact with Avalanche using DataHub
---
# ๐ Avalanche
## Welcome to the Avalanche documentation!
In this section, you will be able to learn about what makes Avalanche special and how you can leverage available tools to build amazing products!
Check out the Avalanche 101 section to learn more about the protocol and see how it compares to other networks in terms of speed, cost, and functionalities.
You can then get started with the available RPC & REST APIs we support [**via DataHub**](https://datahub.figment.io/sign_up?service=avalanche).
Last but not least, if you are looking for guidelines or simply some inspiration, check out our list of available tutorials!
Be sure to check out the [**official Avalanche documentation**](https://docs.avax.network/) and if you need tokens to build on testnet, you can check out the [**link here**](https://faucet.avax-test.network/).
๐ Let's start building the decentralized web ๐
{% page-ref page="avalanche-101.md" %}
{% page-ref page="rpc-and-rest-api/" %}
{% page-ref page="tutorials/" %}
---
description: Learn what Cosmos APIs are available via DataHub and how to use them
---
# ๐ฎ RPC & REST API
## Time to play
Cosmos exposes both the Tendermint RPC and the Cosmos LCD which are both necessary for the development of applications on the Cosmos network.
Learn about the APIs available via Cosmos [**DataHub**](https://datahub.figment.io/sign_up?service=cosmos) below.
{% page-ref page="tendermint-rpc.md" %}
{% page-ref page="cosmos-lcd.md" %}
---
description: Learn how to interact with Tezos using DataHub
---
# โ Tezos
## Welcome to the Tezos documentation!
In this section, you will be able to learn about what makes Tezos special and how you can leverage available tools to build amazing products!
Check out the Tezos 101 section to learn more about the protocol and see how it compares to other networks in terms of speed, cost, and functionalities.
You can then get started with the available RPC & REST APIs we support [**via DataHub**](https://datahub.figment.io/sign_up?service=tezos).
Last but not least, if you are looking for guidelines or simply some inspiration, check out our list of available tutorials!
Be sure to check out the [**official Tezos documentation**](https://tezos.gitlab.io/) and its [**developer portal**](https://developers.tezos.com/)**,** and if you need tokens to build on testnet, you can check out the [**link here**](https://faucet.tzalpha.net/).
๐ Let's start building the decentralized web ๐
{% page-ref page="rpc-and-rest-api-1/" %}
{% page-ref page="tezos-101.md" %}
{% page-ref page="tutorials/" %}
---
description: See all tutorials currently available on Tezos
---
# ๐ก Tutorials
## Time to learn
On this page you can find all tutorials currently available for Tezos, including all tutorials created by the community.
Don't forget that you can try them out [**via Datahub**](https://datahub.figment.io/sign_up?service=tezos)!
#### [Join our community today](https://discord.gg/fszyM7K) if you want to interact with other builders and become a part of this growing ecosystem!
## Token contracts
{% page-ref page="token-contracts.md" %}
## Oracle contracts
{% page-ref page="oracle-contracts.md" %}
## Creating NFTs
{% page-ref page="creating-nfts.md" %}
---
description: See all tutorials currently available for Celo
---
# ๐ก Tutorials
## Time to learn
On this page you can find all tutorials currently available for Celo, including all tutorials created by the community.
Don't forget that you can try them out [**via Datahub**](https://datahub.figment.io/sign_up?service=celo)!
#### [Join our community today ](https://discord.gg/fszyM7K)if you want to interact with other builders and become a part of this growing ecosystem!
## Hello Celo
{% page-ref page="hello-celo.md" %}
## Hello Contracts
{% page-ref page="hello-contracts.md" %}
## Hello Mobile DApp
{% page-ref page="hello-mobile-dapp.md" %}
---
description: Learn how to interact with Filecoin using DataHub
---
# ๐พ Filecoin
## Welcome to the Filecoin documentation!
In this section, you will be able to learn about what makes Filecoin special and how you can leverage available tools to build amazing products!
Check out the Filecoin 101 section to learn more about the protocol and see how it compares to other networks in terms of speed, cost, and functionalities.
You can then get started with the available RPC & REST APIs we support [**via DataHub**](https://datahub.figment.io/).
Be sure to check out the [**official Filecoin documentation**](https://docs.filecoin.io/) ****for additional information. ****
๐ Let's start building the decentralized web ๐
{% page-ref page="filecoin-101.md" %}
{% page-ref page="rpc-and-rest-api/" %}
---
description: See all tutorials currently available for Avalanche
---
# ๐ก Tutorials
## Time to learn
On this page you can find all tutorials currently available for Avalanche, including all tutorials created by the community.
Don't forget that you can try them out [**via Datahub**](https://datahub.figment.io/sign_up?service=avalanche)!
#### [Join our community today](https://discord.gg/fszyM7K) if you want to interact with other builders and become a part of this growing ecosystem!
## Deploy a Smart Contract on Avalanche using Remix and MetaMask <a id="deploy-a-smart-contract-on-avalanche-using-remix-and-metamask"></a>
{% page-ref page="deploy-a-smart-contract-on-avalanche-using-remix-and-metamask.md" %}
## Creating A Fixed-Cap Asset <a id="creating-a-fixed-cap-asset"></a>
{% page-ref page="creating-a-fixed-cap-asset.md" %}
## Creating An NFTโPart 1 <a id="creating-an-nftpart-1"></a>
{% page-ref page="creating-an-nft-part-1.md" %}
## Creating A Variable-Cap Asset <a id="creating-a-variable-cap-asset"></a>
{% page-ref page="creating-a-variable-cap-asset.md" %}
## Create a Subnet <a id="create-a-subnet"></a>
{% page-ref page="create-a-subnet.md" %}
## Create a New Blockchain <a id="create-a-new-blockchain"></a>
{% page-ref page="create-a-new-blockchain.md" %}
## Create a New Virtual Machine <a id="create-a-new-virtual-machine"></a>
{% page-ref page="create-a-new-virtual-machine.md" %}
## Transfer AVAX tokens between Chains <a id="transfer-avax-tokens-between-chains"></a>
{% page-ref page="transfer-avax-tokens-between-chains.md" %}
## Create a Local Test Network <a id="create-a-local-test-network"></a>
{% page-ref page="create-a-local-test-network.md" %}
---
description: Learn what Terra APIs are available via DataHub and how to use them
---
# ๐ฎ RPC & REST API
## Time to play
Terra exposes both the Tendermint RPC and the Terra LCD which are both necessary for the development of applications on the Terra network.
Learn about the APIs available via Terra [**DataHub**](https://datahub.figment.io/sign_up?service=terra) ****below.
{% page-ref page="terra-lcd.md" %}
---
description: See all tutorials currently available on Cosmos
---
# ๐ก Tutorials
## Time to learn
On this page you can find all tutorials currently available for Cosmos, including all tutorials created by the community.
Don't forget that you can try them out [**via Datahub**](https://datahub.figment.io/sign_up?service=cosmos)!
#### [Join our community today ](https://discord.gg/fszyM7K)if you want to interact with other builders and become a part of this growing ecosystem!
## Build a polling app
{% page-ref page="build-a-polling-app.md" %}
## Create a blog app
{% page-ref page="create-a-blog-app.md" %}
## Build a scavenger game
{% page-ref page="build-a-scavenger-game/" %}
## Build a nameservice application
{% page-ref page="untitled-3/" %}
####
|
NEAR-P2P_NearP2P-NearPricesFiat | .vscode
settings.json
README.md
api.py
bd.sql
dboperations.py
exchanges.py
fiat_aurora.py
fiat_btc.py
fiat_eth.py
fiat_from_ref_finance.py
fiat_near.py
fiat_usdt.py
fiat_wbtc.py
fiat_weth.py
fiat_wnear.py
requirements.txt
| # P2PBd
Python program, update in database crypto price from coinmarketcap near against fiat
Get ticker information from exchanges into postgres database, last price
|
jilt_varda-vault | .vs
ProjectSettings.json
VSWorkspaceState.json
README.md
assets
global.css
logo-black.svg
logo-white.svg
contract
README.md
babel.config.json
build.sh
deploy.sh
neardev
dev-account.env
package-lock.json
package.json
src
contract.ts
tsconfig.json
docs
index.a2cc9e2a.css
index.a2cc9e2a.css.1405.c
index.bc0daea6.css
index.html
logo-black.4514ed42.svg
logo-white.a7716062.svg
frontend
assets
global.css
logo-black.svg
logo-white.svg
index.html
index.js
near-interface.js
near-wallet.js
package-lock.json
package.json
start.sh
index.html
index.js
integration-tests
package-lock.json
package.json
src
main.ava.ts
near-interface.js
near-wallet.js
package-lock.json
package.json
start.sh
| ## varda-vault secret content locker for NEAR nft
This repo is built to connect all NEAR NFTs to unlockable content. The contract is quite simple. It returns all the owned NFTs along with unlockable content related to them. The interface allows to lock new content to the owned NFTs.
**Lock secret content** <br />
We suggest to upload the unlockable content to IPFS using web3.storage (1T free immutable upload) Once the content is uploaded copy the CID file number from your files page, login to the Varda Vault and select the "lock" button in line with the NFT you created/own in your wallet. You can link both IPFS CID and normal links to your NFTs, in order to be able to let people access to web apps using the Varda interface, an API for Exclusive access to your custom URL will be soon available.
A discord Bot for locking immutable content to your NFTs directly from the Varda server will be built soon.
Please remember the locked content is immutable, so you can't change it after locking.
**Unlock secret content** <br />
Secret content is available only to the NFT token owner. Access the Varda Vault and click the button "unlock" corresponding to the NFT you own.
Kindly brought you by the Varda Team
# 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>`.
|
NEARFoundation_sc.whitelist-payouts | Cargo.toml
README.md
scripts
build.sh
src
lib.rs
tests
sim
main.rs
utils.rs
| # sc.whitelist-payouts
Whitelist payouts contract

|
halremawa_dono-contract | asconfig.json
assembly
as_types.d.ts
index.ts
models.ts
tsconfig.json
package.json
| |
orkun51_Web3.0-Practice-1 | README.md
as-pect.config.js
asconfig.json
neardev
dev-account.env
package.json
scripts
1.dev-deploy.sh
2.use-contract.sh
3.cleanup.sh
README.md
src
as_types.d.ts
simple
__tests__
as-pect.d.ts
index.unit.spec.ts
asconfig.json
assembly
index.ts
singleton
__tests__
as-pect.d.ts
index.unit.spec.ts
asconfig.json
assembly
index.ts
tsconfig.json
utils.ts
| ## 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.
[](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.
[](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
```
[](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
```
|
johnedvard_Kurve-Space | CHANGELOG.md
README.md
client
BulletState.js
bullet.js
deadFeedback.js
engineParticleEffect.js
game.js
gameEvent.js
gameUtils.js
iGameobject.js
index.html
index.js
key.js
menu.js
monetizeEvent.js
myLib.js
near
config.js
nearConnection.js
nearLogin.js
player.js
playerState.js
serverConnection.js
sound.js
spaceShip.js
spaceShipRenderers.js
style.css
trails.js
zzfx.js
common
commonUtils.ts
serverEvent.ts
contract
as-pect.config.js
asconfig.json
assembly
as_types.d.ts
index.ts
tsconfig.json
compile.js
package-lock.json
package.json
entry
bundle.js
index.html
style.css
neardev
dev-account.env
package-lock.json
package.json
server
arena.config.ts
arena.env
development.env
index.ts
package-lock.json
package.json
rooms
battleRoom.ts
game.ts
playerSchema.ts
tsconfig.json
tsconfig.json
webpack.config.js
| ## Description
This game is inspired by Achtung, die Kurve!
It's a 4 player local multiplayer game. You control a spaceship and need to stay alive as long as possible before there's no space to navigate. You die if you hit a player's trail or any of the walls. Each player has one bullet they can fire to clear some space.
### Controls
Click "space" to start the round. When a round is over, click "space" to play again.
player controls:
- p1: left arrow, right arrow, up arrow (shoot)
- p2: q, w, e
- p3: v, b, n
- p4: i, o, p
- mute sound: m
### Monetization
You can select additional space ship skins for your ship.
### NEAR
You can write your name, and it will be stored on the smart contract. The name also determines the color of p1's space ship when you are logged in to NEAR.
### Protocol labs
The three other ships' color are chosen based on Drand.
|
metashwat_NCD-starter | 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.
[](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.
[](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
```
[](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
```
|
NEARWEEK_sputnik-dao-2-ui-reference-testnet | .eslintrc.js
.github
ISSUE_TEMPLATE
BOUNTY.yml
.vscode
settings.json
README.md
babel.config.js
package.json
src
__mocks__
fileMock.js
assets
logo-black.svg
logo-white.svg
near-social.svg
roketo-logo.svg
components
dao
dao.css
shared
dao-search.css
config.js
constants
index.js
contexts
DaosContext.js
global.css
hooks
useChangeDao.js
useDaoCount.js
useDaoList.js
useDaoSearchFilters.js
useNumberProposals.js
useOuterClick.js
usePagination.js
useQuery.js
index.html
index.js
jest.init.js
main.test.js
utils
Loading.js
funcs.js
store.js
utils.js
wallet
login
index.html
| # sputnik-dao-2-ui-reference
> UI for the Reference implementation [Sputnik-DAO-2 smart contract](https://github.com/near-daos/sputnik-dao-contract)
## Guide
### Setup
```
yarn install
```
### Develop
```
yarn start
```
|
esaminu_test-rs-boilerplate-106l | .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
| # 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>`.
<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 />
[](https://github.com/near/boilerplate-template-rs/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22)
[](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)._
|
hiba-machfej_todo--near-smart-contract | 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
models.ts
tsconfig.json
utils.ts
| # `near-sdk-as` Starter Kit
This is a good project to use as a starting point for your AssemblyScript project.
## Samples
This repository includes a complete project structure for AssemblyScript contracts targeting the NEAR platform.
The example here is very basic. It's a simple contract demonstrating the following concepts:
- a single contract
- the difference between `view` vs. `change` methods
- basic contract storage
There are 2 AssemblyScript contracts in this project, each in their own folder:
- **simple** in the `src/simple` folder
- **singleton** in the `src/singleton` folder
### Simple
We say that an AssemblyScript contract is written in the "simple style" when the `index.ts` file (the contract entry point) includes a series of exported functions.
In this case, all exported functions become public contract methods.
```ts
// return the string 'hello world'
export function helloWorld(): string {}
// read the given key from account (contract) storage
export function read(key: string): string {}
// write the given value at the given key to account (contract) storage
export function write(key: string, value: string): string {}
// private helper method used by read() and write() above
private storageReport(): string {}
```
### Singleton
We say that an AssemblyScript contract is written in the "singleton style" when the `index.ts` file (the contract entry point) has a single exported class (the name of the class doesn't matter) that is decorated with `@nearBindgen`.
In this case, all methods on the class become public contract methods unless marked `private`. Also, all instance variables are stored as a serialized instance of the class under a special storage key named `STATE`. AssemblyScript uses JSON for storage serialization (as opposed to Rust contracts which use a custom binary serialization format called borsh).
```ts
@nearBindgen
export class Contract {
// return the string 'hello world'
helloWorld(): string {}
// read the given key from account (contract) storage
read(key: string): string {}
// write the given value at the given key to account (contract) storage
@mutateState()
write(key: string, value: string): string {}
// private helper method used by read() and write() above
private storageReport(): string {}
}
```
## Usage
### Getting started
(see below for video recordings of each of the following steps)
INSTALL `NEAR CLI` first like this: `npm i -g near-cli`
1. clone this repo to a local folder
2. run `yarn`
3. run `./scripts/1.dev-deploy.sh`
3. run `./scripts/2.use-contract.sh`
4. run `./scripts/2.use-contract.sh` (yes, run it to see changes)
5. run `./scripts/3.cleanup.sh`
### Videos
**`1.dev-deploy.sh`**
This video shows the build and deployment of the contract.
[](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.
[](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
```
[](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)
|
kuutamolabs_nixpkgs | .github
ISSUE_TEMPLATE.md
ISSUE_TEMPLATE
bug_report.md
out_of_date_package_report.md
packaging_request.md
PULL_REQUEST_TEMPLATE.md
STALE-BOT.md
labeler.yml
stale.yml
workflows
backport.yml
basic-eval.yml
direct-push.yml
editorconfig.yml
labels.yml
manual-nixos.yml
manual-nixpkgs.yml
nixos-manual.yml
no-channel.yml
pending-clear.yml
pending-set.yml
periodic-merge-24h.yml
periodic-merge-6h.yml
update-terraform-providers.yml
CONTRIBUTING.md
README.md
doc
README.md
build-aux
pandoc-filters
docbook-reader
citerefentry-to-rst-role.lua
docbook-writer
labelless-link-is-xref.lua
rst-roles.lua
link-unix-man-references.lua
myst-reader
roles.lua
myst-writer
roles.lua
builders
fetchers.chapter.md
images.xml
images
appimagetools.section.md
dockertools.section.md
ocitools.section.md
snaptools.section.md
packages
cataclysm-dda.section.md
citrix.section.md
dlib.section.md
eclipse.section.md
elm.section.md
emacs.section.md
etc-files.section.md
firefox.section.md
fish.section.md
fuse.section.md
ibus.section.md
index.xml
kakoune.section.md
linux.section.md
locales.section.md
nginx.section.md
opengl.section.md
shell-helpers.section.md
steam.section.md
unfree.xml
urxvt.section.md
weechat.section.md
xorg.section.md
special.xml
special
fhs-environments.section.md
invalidateFetcherByDrvHash.section.md
mkshell.section.md
trivial-builders.chapter.md
contributing
coding-conventions.chapter.md
contributing-to-documentation.chapter.md
quick-start.chapter.md
reviewing-contributions.chapter.md
submitting-changes.chapter.md
vulnerability-roundup.chapter.md
doc-support
parameters.xml
functions.xml
functions
debug.section.md
generators.section.md
library.xml
library
asserts.xml
attrsets.xml
nix-gitignore.section.md
prefer-remote-fetch.section.md
hooks
index.xml
postgresql-test-hook.section.md
languages-frameworks
agda.section.md
android.section.md
beam.section.md
bower.section.md
coq.section.md
crystal.section.md
cuda.section.md
dhall.section.md
dotnet.section.md
emscripten.section.md
gnome.section.md
go.section.md
haskell.section.md
hy.section.md
idris.section.md
index.xml
ios.section.md
java.section.md
javascript.section.md
lua.section.md
maven.section.md
nim.section.md
ocaml.section.md
octave.section.md
perl.section.md
php.section.md
python.section.md
qt.section.md
r.section.md
ruby.section.md
rust.section.md
texlive.section.md
titanium.section.md
vim.section.md
manual.xml
old
cross.txt
overrides.css
preface.chapter.md
release-notes.xml
stdenv
cross-compilation.chapter.md
meta.chapter.md
multiple-output.chapter.md
platform-notes.chapter.md
stdenv.chapter.md
style.css
using
configuration.chapter.md
overlays.chapter.md
overrides.chapter.md
|
lib
tests
modules.sh
sources.sh
maintainers
scripts
check-maintainer-github-handles.sh
copy-tarballs.pl
db-to-md.sh
debian-patches.sh
dep-licenses.sh
doc
escape-code-markup.py
replace-xrefs-by-empty-links.py
unknown-code-language.lua
eval-release.sh
feature-freeze-teams.pl
fetch-kde-qt.sh
haskell
mark-broken.sh
merge-and-open-pr.sh
regenerate-hackage-packages.sh
regenerate-transitive-broken-packages.sh
update-cabal2nix-unstable.sh
update-hackage.sh
update-stackage.sh
upload-nixos-package-list-to-hackage.sh
hydra-eval-failures.py
luarocks-config.lua
nix-diff.sh
nix-generate-from-cpan.pl
nixpkgs-lint.pl
patchelf-hints.sh
pluginupdate.py
rebuild-amount.sh
remove-old-aliases.py
update-channel-branches.sh
update-redirected-urls.sh
update.py
vanity-manual-equalities.txt
vanity.sh
SHOWING ERROR LOG FOR {package['name']}
nixos
doc
manual
README.md
administration
boot-problems.section.md
cleaning-store.chapter.md
container-networking.section.md
containers.chapter.md
control-groups.chapter.md
declarative-containers.section.md
imperative-containers.section.md
logging.chapter.md
maintenance-mode.section.md
network-problems.section.md
rebooting.chapter.md
rollback.section.md
running.xml
service-mgmt.chapter.md
store-corruption.section.md
troubleshooting.chapter.md
user-sessions.chapter.md
configuration
abstractions.section.md
ad-hoc-network-config.section.md
ad-hoc-packages.section.md
adding-custom-packages.section.md
config-file.section.md
config-syntax.chapter.md
configuration.xml
customizing-packages.section.md
declarative-packages.section.md
file-systems.chapter.md
firewall.section.md
gpu-accel.chapter.md
ipv4-config.section.md
ipv6-config.section.md
kubernetes.chapter.md
linux-kernel.chapter.md
luks-file-systems.section.md
modularity.section.md
network-manager.section.md
networking.chapter.md
package-mgmt.chapter.md
profiles.chapter.md
profiles
all-hardware.section.md
base.section.md
clone-config.section.md
demo.section.md
docker-container.section.md
graphical.section.md
hardened.section.md
headless.section.md
installation-device.section.md
minimal.section.md
qemu-guest.section.md
renaming-interfaces.section.md
ssh.section.md
sshfs-file-systems.section.md
subversion.chapter.md
summary.section.md
user-mgmt.chapter.md
wayland.chapter.md
wireless.section.md
x-windows.chapter.md
xfce.chapter.md
contributing-to-this-manual.chapter.md
development
activation-script.section.md
assertions.section.md
building-parts.chapter.md
development.xml
freeform-modules.section.md
importing-modules.section.md
linking-nixos-tests-to-packages.section.md
meta-attributes.section.md
nixos-tests.chapter.md
option-declarations.section.md
option-def.section.md
option-types.section.md
replace-modules.section.md
running-nixos-tests-interactively.section.md
running-nixos-tests.section.md
settings-options.section.md
sources.chapter.md
testing-installer.chapter.md
unit-handling.section.md
what-happens-during-a-system-switch.chapter.md
writing-documentation.chapter.md
writing-modules.chapter.md
writing-nixos-tests.section.md
from_md
README.md
administration
boot-problems.section.xml
cleaning-store.chapter.xml
container-networking.section.xml
containers.chapter.xml
control-groups.chapter.xml
declarative-containers.section.xml
imperative-containers.section.xml
logging.chapter.xml
maintenance-mode.section.xml
network-problems.section.xml
rebooting.chapter.xml
rollback.section.xml
service-mgmt.chapter.xml
store-corruption.section.xml
troubleshooting.chapter.xml
user-sessions.chapter.xml
configuration
abstractions.section.xml
ad-hoc-network-config.section.xml
ad-hoc-packages.section.xml
adding-custom-packages.section.xml
config-file.section.xml
config-syntax.chapter.xml
customizing-packages.section.xml
declarative-packages.section.xml
file-systems.chapter.xml
firewall.section.xml
gpu-accel.chapter.xml
ipv4-config.section.xml
ipv6-config.section.xml
kubernetes.chapter.xml
linux-kernel.chapter.xml
luks-file-systems.section.xml
modularity.section.xml
network-manager.section.xml
networking.chapter.xml
package-mgmt.chapter.xml
profiles.chapter.xml
profiles
all-hardware.section.xml
base.section.xml
clone-config.section.xml
demo.section.xml
docker-container.section.xml
graphical.section.xml
hardened.section.xml
headless.section.xml
installation-device.section.xml
minimal.section.xml
qemu-guest.section.xml
renaming-interfaces.section.xml
ssh.section.xml
sshfs-file-systems.section.xml
subversion.chapter.xml
summary.section.xml
user-mgmt.chapter.xml
wayland.chapter.xml
wireless.section.xml
x-windows.chapter.xml
xfce.chapter.xml
contributing-to-this-manual.chapter.xml
development
activation-script.section.xml
assertions.section.xml
building-parts.chapter.xml
freeform-modules.section.xml
importing-modules.section.xml
linking-nixos-tests-to-packages.section.xml
meta-attributes.section.xml
nixos-tests.chapter.xml
option-declarations.section.xml
option-def.section.xml
option-types.section.xml
replace-modules.section.xml
running-nixos-tests-interactively.section.xml
running-nixos-tests.section.xml
settings-options.section.xml
sources.chapter.xml
testing-installer.chapter.xml
unit-handling.section.xml
what-happens-during-a-system-switch.chapter.xml
writing-documentation.chapter.xml
writing-modules.chapter.xml
writing-nixos-tests.section.xml
installation
building-nixos.chapter.xml
changing-config.chapter.xml
installing-behind-a-proxy.section.xml
installing-from-other-distro.section.xml
installing-pxe.section.xml
installing-usb.section.xml
installing-virtualbox-guest.section.xml
installing.chapter.xml
obtaining.chapter.xml
upgrading.chapter.xml
release-notes
rl-1310.section.xml
rl-1404.section.xml
rl-1412.section.xml
rl-1509.section.xml
rl-1603.section.xml
rl-1609.section.xml
rl-1703.section.xml
rl-1709.section.xml
rl-1803.section.xml
rl-1809.section.xml
rl-1903.section.xml
rl-1909.section.xml
rl-2003.section.xml
rl-2009.section.xml
rl-2105.section.xml
rl-2111.section.xml
rl-2205.section.xml
installation
building-nixos.chapter.md
changing-config.chapter.md
installation.xml
installing-behind-a-proxy.section.md
installing-from-other-distro.section.md
installing-pxe.section.md
installing-usb.section.md
installing-virtualbox-guest.section.md
installing.chapter.md
obtaining.chapter.md
upgrading.chapter.md
man-configuration.xml
man-nixos-build-vms.xml
man-nixos-enter.xml
man-nixos-generate-config.xml
man-nixos-install.xml
man-nixos-option.xml
man-nixos-rebuild.xml
man-nixos-version.xml
man-pages.xml
manual.xml
md-to-db.sh
preface.xml
release-notes
release-notes.xml
rl-1310.section.md
rl-1404.section.md
rl-1412.section.md
rl-1509.section.md
rl-1603.section.md
rl-1609.section.md
rl-1703.section.md
rl-1709.section.md
rl-1803.section.md
rl-1809.section.md
rl-1903.section.md
rl-1909.section.md
rl-2003.section.md
rl-2009.section.md
rl-2105.section.md
rl-2111.section.md
rl-2205.section.md
varlistentry-fixer.rb
lib
make-iso9660-image.sh
make-options-doc
generateAsciiDoc.py
generateCommonMark.py
mergeJSON.py
options-to-docbook.xsl
postprocess-option-descriptions.xsl
sortXML.py
make-system-tarball.sh
test-driver
setup.py
test_driver
__init__.py
driver.py
logger.py
machine.py
polling_condition.py
vlan.py
maintainers
scripts
azure-new
README.md
boot-vm.sh
common.sh
upload-image.sh
azure
create-azure.sh
upload-azure.sh
ec2
create-amis.sh
gce
create-gce.sh
modules
config
update-users-groups.pl
i18n
input-method
default.xml
installer
cd-dvd
system-tarball-pc-readme.txt
tools
nixos-build-vms
nixos-build-vms.sh
nixos-enter.sh
nixos-generate-config.pl
nixos-install.sh
nixos-version.sh
programs
command-not-found
command-not-found.pl
digitalbitbox
doc.xml
plotinus.xml
zsh
oh-my-zsh.xml
security
acme
doc.xml
wrappers
wrapper.c
services
amqp
activemq
ActiveMQBroker.java
backup
borgbackup.xml
databases
foundationdb.xml
postgresql.xml
desktops
flatpak.xml
pipewire
daemon
client-rt.conf.json
client.conf.json
jack.conf.json
minimal.conf.json
pipewire-pulse.conf.json
pipewire.conf.json
media-session
alsa-monitor.conf.json
bluez-monitor.conf.json
media-session.conf.json
v4l2-monitor.conf.json
development
blackfire.xml
editors
emacs.xml
hardware
trezord.xml
mail
mailman.xml
matrix
matrix-synapse.xml
mjolnir.xml
misc
gitlab.xml
sourcehut
sourcehut.xml
taskserver
doc.xml
helper-tool.py
weechat.xml
monitoring
parsedmarc.md
parsedmarc.xml
prometheus
exporters.xml
network-filesystems
litestream
litestream.xml
networking
hylafax
faxq-wait.sh
spool.sh
ircd-hybrid
builder.sh
mosquitto.md
mosquitto.xml
onedrive.xml
pleroma.xml
prosody.xml
yggdrasil.xml
search
meilisearch.md
meilisearch.xml
security
vaultwarden
backup.sh
video
epgstation
streaming.json
web-apps
discourse.xml
grocy.xml
jitsi-meet.xml
keycloak.xml
lemmy.md
lemmy.xml
matomo-doc.xml
nextcloud.xml
pict-rs.md
pict-rs.xml
plausible.xml
web-servers
jboss
builder.sh
trafficserver
ip_allow.json
logging.json
x11
desktop-managers
gnome.xml
pantheon.xml
display-managers
set-session.py
system
activation
switch-to-configuration.pl
boot
loader
generations-dir
generations-dir-builder.sh
generic-extlinux-compatible
extlinux-conf-builder.sh
grub
install-grub.pl
init-script
init-script-builder.sh
raspberrypi
raspberrypi-builder.sh
uboot-builder.sh
systemd-boot
systemd-boot-builder.py
pbkdf2-sha512.c
stage-1-init.sh
stage-2-init.sh
etc
setup-etc.pl
tasks
tty-backgrounds-combine.sh
tests
common
acme
server
README.md
webroot
news-rss.xml
google-oslogin
server.py
hitch
example
index.txt
hydra
create-trivial-project.sh
ihatemoney
rates.json
lorri
builder.sh
mpich-example.c
mysql
testdb.sql
pam
test_chfn.py
spark
spark_sample.py
pkgs
applications
audio
netease-cloud-music-gtk
update-cargo-lock.sh
netease-music-tui
update-cargo-lock.sh
plexamp
update-plexamp.sh
spotify
update.sh
vgmstream
update.sh
blockchains
bisq-desktop
update.sh
btcpayserver
update.sh
electrs
update.sh
nbxplorer
update.sh
util
create-deps.sh
update-common.sh
editors
aseprite
skia-make-deps.sh
cudatext
deps.json
update.sh
jetbrains
update.py
versions.json
jupyter-kernels
clojupyter
update.sh
kakoune
plugins
deprecated.json
update.py
neovim
neovide
skia-externals.json
qxmledit
qxmledit.json
rstudio
package.json
uivonim
package.json
vim
plugins
deprecated.json
markdown-preview-nvim
package.json
readme.md
update.py
vim-gen-doc-hook.sh
vim2nix
README.txt
addon-info.json
vscode
extensions
_maintainers
update-bin-srcs-lib.sh
cpptools
missing_elf_deps.sh
package-activation-events.json
update_helper.sh
ms-dotnettools-csharp
rt-deps-bin-srcs.json
ms-vsliveshare-vsliveshare
noop-syslog.c
rust-analyzer
build-deps
package.json
update.sh
update_installed_exts.sh
vscode-lldb
build-deps
package.json
update.sh
update-vscode.sh
update-vscodium.sh
emulators
retroarch
hashes.json
update_cores.py
rpcs3
update.sh
ryujinx
updater.sh
wine
builder-wow.sh
setup-hook-darwin.sh
graphics
antimony
mimetype.xml
sane
backends
brscan4
preload.c
kde
fetch.sh
misc
1password-gui
update.sh
ArchiSteamFarm
updater.sh
web-ui
update.sh
adobe-reader
builder.sh
bottles
update.py
jekyll
update.sh
keepass
extractWinRscIconsToStdFreeDesktopDir.sh
logseq
update.sh
mkgmap
update.sh
networking
browsers
brave
update.sh
chromium
README.md
get-commit-message.py
ungoogled-flags.toml
update.py
upstream-info.json
firefox
librewolf
src.json
microsoft-edge
update.sh
vieb
package.json
vivaldi
update.sh
cluster
fluxcd
update.sh
k3s
update.sh
linkerd
update-edge.sh
update-stable.sh
nixops
pyproject.toml
octant
update-desktop.sh
update.sh
spacegun
generate-dependencies.sh
terraform-providers
providers.json
instant-messengers
bluejeans
localtime64_stub.c
update.sh
deltachat-desktop
package.json
update.sh
element
element-desktop-package.json
keytar
pin.json
update.sh
pin.json
seshat
pin.json
update.sh
update.sh
jami
update.sh
matrix-recorder
package.json
mikutter
test_plugin.rb
update.sh
schildichat
pin.json
update.sh
slack
update.sh
telegram
tdesktop
update.py
zoom-us
update.sh
misc
zammad
package.json
source.json
update.sh
n8n
generate-dependencies.sh
package.json
nym
update.sh
powerdns-admin
package.json
update-asset-deps.sh
remote
vmware-horizon-client
update.sh
office
atlassian-cli
wrapper.sh
libreoffice
README.md
download-list-builder.sh
generate-libreoffice-srcs.py
libreoffice-srcs-additions.json
wrapper.sh
micropad
package.json
onlyoffice-bin
update.sh
zotero
zotero.sh
plasma-mobile
fetch.sh
science
electronics
eagle
eagle7_fixer.c
kicad
update.sh
picoscope
sources.json
update.py
math
R
setup-hook.sh
sage
README.md
misc
openmodelica
omlibrary
update-src-libs.sh
root
setup-hook.sh
version-management
cz-cli
generate-dependencies.sh
package.json
git-and-tools
git
update.sh
gitlab
data.json
update.py
sourcehut
update.sh
video
epgstation
client
package.json
package.json
mirakurun
package.json
mpv
scripts
update-sponsorblock.sh
plex-media-player
update.sh
virtualization
crosvm
generate-cargo.sh
update.py
upstream-info.json
nvidia-docker
config.toml
nvidia-podman
config.toml
qemu
binfmt-p-wrapper.c
virtualbox
update.sh
build-support
add-opengl-runpath
setup-hook.sh
appimage
appimage-exec.sh
bintools-wrapper
add-darwin-ldflags-before.sh
add-flags.sh
add-hardening.sh
darwin-install_name_tool-wrapper.sh
darwin-strip-wrapper.sh
gnu-binutils-strip-wrapper.sh
ld-solaris-wrapper.sh
ld-wrapper.sh
setup-hook.sh
build-fhs-userenv
chrootenv
src
chrootenv.c
buildenv
builder.pl
cc-wrapper
add-flags.sh
add-hardening.sh
cc-wrapper.sh
fortran-hook.sh
gnat-wrapper.sh
setup-hook.sh
docker
detjson.py
stream_layered_image.py
tarsum.go
test-dummy
hello.txt
dotnet
build-dotnet-module
hooks
dotnet-build-hook.sh
dotnet-check-hook.sh
dotnet-configure-hook.sh
dotnet-fixup-hook.sh
dotnet-install-hook.sh
dotnetbuildhelpers
create-pkg-config-for-dll.sh
patch-fsharp-targets.sh
placate-nuget.sh
placate-paket.sh
remove-duplicated-dlls.sh
dotnetenv
Wrapper
Wrapper.sln
Wrapper
Properties
AssemblyInfo.cs
nuget-to-nix
nuget-to-nix.sh
emacs
emacs-funcs.sh
wrapper.sh
expand-response-params
expand-response-params.c
fetchbzr
builder.sh
fetchcvs
builder.sh
fetchdarcs
builder.sh
fetchdocker
fetchdocker-builder.sh
fetchfossil
builder.sh
fetchgit
builder.sh
fetchhg
builder.sh
fetchipfs
builder.sh
fetchmtn
builder.sh
fetchsvn
builder.sh
fetchsvnssh
builder.sh
fetchurl
builder.sh
write-mirror-list.sh
icon-conv-tools
bin
extractWinRscIconsToStdFreeDesktopDir.sh
java
canonicalize-jar.sh
kernel
make-initrd-ng
Cargo.toml
README.md
src
main.rs
make-initrd.sh
modules-closure.sh
paths-from-graph.pl
libredirect
libredirect.c
test.c
make-symlinks
builder.sh
mono-dll-fixer
dll-fixer.pl
node
fetch-yarn-deps
index.js
nuke-references
darwin-sign-fixup.sh
nuke-refs.sh
pkg-config-wrapper
add-flags.sh
pkg-config-wrapper.sh
setup-hook.sh
references-by-popularity
closure-graph.py
release
functions.sh
remove-references-to
darwin-sign-fixup.sh
remove-references-to.sh
replace-secret
replace-secret.py
rust
build-rust-crate
lib.sh
fetch-cargo-tarball
cargo-vendor-normalise.py
fetchcargo-default-config.toml
hooks
cargo-build-hook.sh
cargo-check-hook.sh
cargo-install-hook.sh
cargo-setup-hook.sh
maturin-build-hook.sh
rust-bindgen-hook.sh
sysroot
cargo.py
update-lockfile.sh
test
import-cargo-lock
basic-dynamic
Cargo.toml
src
main.rs
basic
Cargo.toml
src
main.rs
git-dependency-branch
Cargo.toml
src
main.rs
git-dependency-rev-non-workspace-nested-crate
Cargo.toml
src
main.rs
git-dependency-rev
Cargo.toml
src
main.rs
git-dependency-tag
Cargo.toml
src
main.rs
git-dependency
Cargo.toml
src
main.rs
setup-hooks
audit-blas.sh
audit-tmpdir.sh
auto-patchelf.py
auto-patchelf.sh
autoreconf.sh
breakpoint-hook.sh
canonicalize-jars.sh
compress-man-pages.sh
copy-desktop-items.sh
desktop-to-darwin-bundle.sh
die.sh
enable-coverage-instrumentation.sh
find-xml-catalogs.sh
fix-darwin-dylib-names.sh
gog-unpack.sh
install-shell-files.sh
keep-build-tree.sh
ld-is-cc-hook.sh
make-binary-wrapper.sh
make-coverage-analysis-report.sh
make-symlinks-relative.sh
make-wrapper.sh
move-docs.sh
move-lib64.sh
move-sbin.sh
move-systemd-user-units.sh
multiple-outputs.sh
patch-shebangs.sh
postgresql-test-hook
postgresql-test-hook.sh
prune-libtool-files.sh
reproducible-builds.sh
separate-debug-info.sh
set-java-classpath.sh
set-source-date-epoch-to-latest.sh
setup-debug-info-dirs.sh
shorten-perl-shebang.sh
strip.sh
update-autotools-gnu-config-scripts.sh
use-old-cxx-abi.sh
validate-pkg-config.sh
win-dll-link.sh
wrap-gapps-hook
wrap-gapps-hook.sh
substitute
substitute-all.sh
substitute.sh
templaterpm
nix-template-rpm.py
trivial-builders
test
references-test.sh
vm
deb
deb-closure.pl
rpm
rpm-closure.pl
data
documentation
rnrs
builder.sh
fonts
iosevka
update-bin.sh
update-default.sh
league-of-moveable-type
update.sh
nerdfonts
update.sh
icons
hicolor-icon-theme
setup-hook.sh
misc
cacert
setup-hook.sh
update.sh
dns-root-data
update-root-key.sh
hackage
pin.json
rime-data
generateFetchSchema.sh
tzdata
tzdata-setup-hook.sh
v2ray-geoip
update.sh
desktops
gnome
extensions
README.md
collisions.json
update-extensions.py
find-latest-version.py
gnustep
make
builder.sh
setup-hook.sh
wrapper.sh
lxqt
lxqt-build-tools
setup-hook.sh
plasma-5
fetch.sh
xfce
automakeAddFlags.sh
core
xfce4-dev-tools
setup-hook.sh
development
beam-modules
elixir-ls
pin.json
update.sh
mix-configure-hook.sh
compilers
adoptopenjdk-bin
generate-sources.py
sources.json
aspectj
builder.sh
ats2
setup-contrib-hook.sh
setup-hook.sh
chez-racket
setup-hook.sh
chez
setup-hook.sh
chicken
4
eggs.scm
fetchegg
builder.sh
setup-hook.sh
5
eggs.scm
fetchegg
builder.sh
setup-hook.sh
cudatoolkit
auto-add-opengl-runpath-hook.sh
redist
manifests
redistrib_11.4.4.json
redistrib_11.5.2.json
redistrib_11.6.2.json
versions.toml
dotnet
print-hashes.sh
elm
README.md
packages
README.md
generate-node-packages.sh
node-packages.json
update.sh
emscripten
package.json
fpc
binary-builder.sh
gcc
builder.sh
update-mcfgthread-patches.sh
ghc
gcc-clang-wrapper.sh
ghcjs
8.10
git.json
ghdl
expected-output.txt
go
print-hashes.sh
graalvm
community-edition
graalvm11-ce-sources.json
graalvm17-ce-sources.json
haxe
setup-hook.sh
ios-cross-compile
9.2_builder.sh
alt_wrapper.c
julia
README.md
llvm
update-git.py
update.sh
ocaml
builder.sh
openjdk
generate-cacerts.pl
oraclejdk
dlj-bundle-builder.sh
purescript
purescript
test-minimal-module
Main.js
update.sh
roslyn
create-deps.sh
rust
print-hashes.sh
setup-hook.sh
tinygo
main.go
vala
setup-hook.sh
yosys
setup-hook.sh
dotnet-modules
python-language-server
updater.sh
embedded
blackmagic
helper.sh
bossa
bin2c.c
go-modules
tools
setup-hook.sh
go-packages
tools
setup-hook.sh
haskell-modules
HACKING.md
hoogle-local-wrapper.sh
stack-hook.sh
idris-modules
README.md
TODO.md
interpreters
clojurescript
lumo
package.json
guile
setup-hook-1.8.sh
setup-hook-2.0.sh
setup-hook-2.2.sh
setup-hook-3.0.sh
lua-5
hooks
setup-hook.sh
lua-dso.make
wrap.sh
octave
hooks
octave-write-required-octave-packages-hook.sh
write-required-octave-packages-hook.sh
wrap.sh
perl
setup-hook-cross.sh
setup-hook.sh
python
catch_conflicts
README.md
catch_conflicts.py
cpython
docs
generate.sh
hooks
conda-install-hook.sh
conda-unpack-hook.sh
egg-build-hook.sh
egg-install-hook.sh
egg-unpack-hook.sh
flit-build-hook.sh
pip-build-hook.sh
pip-install-hook.sh
pytest-check-hook.sh
python-catch-conflicts-hook.sh
python-imports-check-hook.sh
python-namespaces-hook.sh
python-recompile-bytecode-hook.sh
python-remove-bin-bytecode-hook.sh
python-remove-tests-dir-hook.sh
setuptools-build-hook.sh
setuptools-check-hook.sh
venv-shell-hook.sh
wheel-unpack-hook.sh
run_setup.py
setup-hook.sh
sitecustomize.py
tests
test_environments
test_python.py
test_nix_pythonprefix
typeddep
setup.py
typeddep
__init__.py
util.py
update-python-libraries
update-python-libraries.py
wrap.sh
ruby
rbconfig.rb
tcl
tcl-package-hook.sh
libraries
SDL
setup-hook.sh
SDL2
setup-hook.sh
audio
libopenmpt
update.sh
aws-c-common
setup-hook.sh
dbus
make-session-conf.xsl
make-system-conf.xsl
dleyna-core
setup-hook.sh
elementary-cmake-modules
setup-hook.sh
fontconfig
make-fonts-conf.xsl
gamin
debian-patches.txt
gdk-pixbuf
setup-hook.sh
gettext
gettext-setup-hook.sh
glib
setup-hook.sh
glibc
locales-builder.sh
gobject-introspection
setup-hook.sh
google-cloud-cpp
skipped_tests.toml
grantlee
5
setup-hook.sh
grilo
setup-hook.sh
gstreamer
core
setup-hook.sh
gtk-sharp
builder.sh
gtk
hooks
clean-immodules-cache.sh
drop-icon-theme-cache.sh
ilbc
CMakeLists.txt
kde-frameworks
extra-cmake-modules
setup-hook.sh
fetch.sh
kdelibs4support
setup-hook.sh
kdoctools
setup-hook.sh
languagemachines
release-info
LanguageMachines-frog.json
LanguageMachines-frogdata.json
LanguageMachines-libfolia.json
LanguageMachines-mbt.json
LanguageMachines-ticcutils.json
LanguageMachines-timbl.json
LanguageMachines-timblserver.json
LanguageMachines-ucto.json
LanguageMachines-uctodata.json
libcef
update.sh
libhsts
update.sh
libiconv
setup-hook.sh
lisp-modules
README.txt
clwrapper
build-with-lisp.sh
cl-wrapper.sh
common-lisp.sh
setup-hook.sh
from-quicklisp
asdf-description.sh
barebones-quicklisp-expression.sh
quicklisp-beta-env.sh
quicklisp-dependencies.sh
urls-from-page.sh
quicklisp-to-nix-systems.txt
quicklisp.sh
misc
haskell
hasura
update.sh
resholve
README.md
mobile
androidenv
fetchrepo.sh
generate.sh
mkrepo.rb
mkrepo.sh
querypackages.sh
repo.json
webos
cmake-setup-hook.sh
nim-packages
fetch-nimble
builder.sh
node-packages
README.md
generate.sh
node-packages.json
ocaml-modules
eliom
setup-hook.sh
ocamlmake
setup-hook.sh
perl-modules
expression-generator
filtered-requirements.sh
full-requirements.sh
grab-url.sh
lib-cache.sh
make-clean-dir.sh
requirements.sh
retrieve-file-link.sh
retrieve-meta-yaml.sh
retrieve-modulepage.sh
source-download-link.sh
usage.txt
write-nix-expression.sh
generic
builder.sh
perl-opengl-gl-extensions.txt
pharo
wrapper
pharo-vm.sh
python-modules
apache-airflow
package.json
bpycv
bpycv-test.py
buildbot
update.sh
r-modules
README.md
ruby-modules
bundled-common
gen-bin-stubs.rb
gem
gem-post-build.rb
nix-bundle-install.rb
runtests.sh
with-packages
test.rb
tools
build-managers
apache-maven
builder.sh
bazel
README.md
bazel_0_29
src-deps.json
bazel_1
src-deps.json
bazel_3
src-deps.json
bazel_4
src-deps.json
update-srcDeps.py
bazel_5
src-deps.json
update-srcDeps.py
update-srcDeps.py
bmake
setup-hook.sh
boot
builder.sh
build2
setup-hook.sh
cmake
setup-hook.sh
gn
setup-hook.sh
gprbuild
gpr-project-path-hook.sh
nixpkgs-gnat.xml
gradle
update.sh
meson
setup-hook.sh
msbuild
create-deps.sh
ninja
setup-hook.sh
scons
setup-hook.sh
tup
setup-hook.sh
wafHook
setup-hook.sh
electron
print-hashes.sh
haskell
dconf2nix
update.sh
misc
automake
builder.sh
setup-hook.sh
coreboot-toolchain
update.sh
luarocks
setup-hook.sh
patchelf
setup-hook.sh
premake
setup-hook.sh
saleae-logic
preload.c
ocaml
opam
opam.nix.pl
omnisharp-roslyn
create-deps.sh
parsing
antlr
builder.sh
tree-sitter
grammars
tree-sitter-agda.json
tree-sitter-bash.json
tree-sitter-beancount.json
tree-sitter-bibtex.json
tree-sitter-c-sharp.json
tree-sitter-c.json
tree-sitter-clojure.json
tree-sitter-cmake.json
tree-sitter-comment.json
tree-sitter-commonlisp.json
tree-sitter-cpp.json
tree-sitter-css.json
tree-sitter-cuda.json
tree-sitter-dart.json
tree-sitter-devicetree.json
tree-sitter-dockerfile.json
tree-sitter-dot.json
tree-sitter-elisp.json
tree-sitter-elixir.json
tree-sitter-elm.json
tree-sitter-embedded-template.json
tree-sitter-erlang.json
tree-sitter-fennel.json
tree-sitter-fish.json
tree-sitter-fluent.json
tree-sitter-fortran.json
tree-sitter-gdscript.json
tree-sitter-glimmer.json
tree-sitter-glsl.json
tree-sitter-go.json
tree-sitter-godot-resource.json
tree-sitter-gomod.json
tree-sitter-graphql.json
tree-sitter-haskell.json
tree-sitter-hcl.json
tree-sitter-heex.json
tree-sitter-hjson.json
tree-sitter-html.json
tree-sitter-http.json
tree-sitter-java.json
tree-sitter-javascript.json
tree-sitter-jsdoc.json
tree-sitter-json.json
tree-sitter-json5.json
tree-sitter-julia.json
tree-sitter-kotlin.json
tree-sitter-latex.json
tree-sitter-ledger.json
tree-sitter-llvm.json
tree-sitter-lua.json
tree-sitter-make.json
tree-sitter-markdown.json
tree-sitter-nix.json
tree-sitter-norg.json
tree-sitter-ocaml.json
tree-sitter-org-nvim.json
tree-sitter-perl.json
tree-sitter-php.json
tree-sitter-pioasm.json
tree-sitter-prisma.json
tree-sitter-pug.json
tree-sitter-python.json
tree-sitter-ql.json
tree-sitter-query.json
tree-sitter-r.json
tree-sitter-razor.json
tree-sitter-regex.json
tree-sitter-rst.json
tree-sitter-ruby.json
tree-sitter-rust.json
tree-sitter-scala.json
tree-sitter-scss.json
tree-sitter-sparql.json
tree-sitter-supercollider.json
tree-sitter-surface.json
tree-sitter-svelte.json
tree-sitter-swift.json
tree-sitter-tlaplus.json
tree-sitter-toml.json
tree-sitter-tsq.json
tree-sitter-turtle.json
tree-sitter-typescript.json
tree-sitter-verilog.json
tree-sitter-vim.json
tree-sitter-vue.json
tree-sitter-yaml.json
tree-sitter-yang.json
tree-sitter-zig.json
poetry2nix
poetry2nix
README.md
extensions.json
fetch-from-pypi.sh
fetch_from_legacy.py
hooks
fixup-hook.sh
pip-build-hook.sh
pyproject-without-special-deps.py
remove-special-dependencies.sh
wheel-unpack-hook.sh
overrides
build-systems.json
pkgs
poetry
pyproject.toml
src.json
purescript
spago
update.sh
rover
update.sh
rust
bindgen
wrapper.sh
rust-analyzer
update.sh
unity3d
unity-nosuid.c
xcbuild
setup-hook.sh
yarn2nix-moretea
yarn2nix
LICENSE.txt
bin
yarn2nix.js
internal
fixup_bin.js
fixup_yarn_lock.js
lib
fixPkgAddMissingSha1.js
generateNix.js
mapObjIndexedReturnArray.js
urlToName.js
nix
expectShFunctions.sh
package.json
web
cypress
cypress-example-kitchensink
README.md
update.sh
deno
update
common.ts
librusty_v8.ts
src.ts
update.ts
netlify-cli
generate.sh
netlify-cli.json
update.sh
newman
generate-dependencies.sh
package.json
nodejs
setup-hook.sh
remarkjs
generate.sh
pkgs.json
games
abuse
abuse.sh
blobby
blobby.sh
dwarf-fortress
game.json
themes
themes.json
update.sh
update.sh
factorio
update.py
versions.json
freeorion
fix-paths.sh
gargoyle
darwin.sh
gimx
custom
Dualshock4.xml
minecraft-servers
update.py
versions.json
minecraft
update.sh
openra
mkdirp.sh
mod-launch-game.sh
mod-update.sh
osu-lazer
osu.runtimeconfig.json
update.sh
sdlpop
prince.sh
steam
build-wrapped.sh
steamcmd.sh
ue4
generate-expr-from-cdn.sh
vessel
isatty.c
misc
base16-builder
generate.sh
node-packages.json
supplement.json
cups
drivers
samsung
4.00.39
builder.sh
documentation-highlighter
README.md
highlight.pack.js
loader.js
mono-blue.css
update.sh
jitsi-meet-prosody
update.sh
my-env
loadenv.sh
os-specific
bsd
netbsd
compat-setup-hook.sh
fts-setup-hook.sh
install-setup-hook.sh
setup-hook.sh
setup-hook.sh
darwin
apple-sdk-11.0
cf-setup-hook.sh
apple-sdk
cf-setup-hook.sh
framework-setup-hook.sh
private-frameworks-setup-hook.sh
security-setup-hook.sh
apple-source-releases
Libc
CrashReporterClient.h
headers.txt
Libsystem
headers.txt
generate-sdk-packages.sh
libauto
auto_dtrace.h
objc4
objc-probes.h
xnu
headers.txt
print-reexports
main.c
setup-hook.sh
signing-utils
auto-sign-hook.sh
utils.sh
linux
apparmor
fix-rc.apparmor.functions.sh
hdapsd
postInstall.sh
kernel
cpu-cgroup-v2-patches
README.md
generate-config.pl
hardened
patches.json
update.py
update-libre.sh
update-rt.sh
update-zen.sh
update.sh
lsb-release
lsb_release.sh
net-tools
config.h
nixos-rebuild
nixos-rebuild.sh
numworks-udev-rules
update.sh
nvidia-x11
builder.sh
opengl
xorg-sys
builder.sh
paxctl
setup-hook.sh
rfkill
rfkill-hook.sh
sdnotify-wrapper
sdnotify-wrapper.c
service-wrapper
service-wrapper.sh
pkgs-lib
formats
java-properties
test
Main.java
servers
adguardhome
update.sh
asterisk
update.py
versions.json
dict
wiktionary
latest_version.py
update.sh
wiktionary2dict.py
wordnet_structures.py
foundationdb
test-list.txt
gotify
package.json
update.sh
haste-server
update.sh
home-assistant
parse-requirements.py
update.sh
http
tomcat
axis2
builder.sh
hylafaxplus
post-install-check.sh
post-install.sh
post-patch.sh
invidious
update.sh
versions.json
videojs.sh
isso
package.json
jackett
updater.sh
jellyfin
update.sh
web-update.sh
jibri
update.sh
jicofo
update.sh
jitsi-videobridge
update.sh
mastodon
update.sh
matrix-appservice-discord
generate.sh
package.json
matrix-synapse
matrix-appservice-irc
generate-dependencies.sh
package.json
src.json
update.sh
matrix-appservice-slack
generate-dependencies.sh
mjolnir
update.sh
monitoring
grafana-image-renderer
package.json
grafana
plugins
update-grafana-plugin.sh
update.sh
matrix-alertmanager
package.json
prometheus
dmarc-exporter
pyproject.toml
webui
codemirror-promql
package-lock.json
package.json
update-web-deps.sh
webui
package.json
uchiwa
update.sh
mx-puppet-discord
generate.sh
nitter
update.sh
nosql
cassandra
2.1.json
2.2.json
3.0.json
3.11.json
eventstore
create-deps.sh
ombi
update.sh
prowlarr
update.sh
psitransfer
generate.sh
node-packages.json
radarr
update.sh
sonarr
update.sh
web-apps
baget
updater.sh
bookstack
update.sh
cryptpad
generate.sh
node-packages.json
discourse
update.py
ethercalc
generate.sh
node-packages.json
hedgedoc
package.json
pin.json
update.sh
jitsi-meet
update.sh
lemmy
package.json
pin.json
update.sh
matomo
bootstrap.php
plausible
package.json
update.sh
whitebophir
generate.sh
node-packages.json
wiki-js
update.sh
x11
xorg
builder.sh
darwin
dri
GL
internal
dri_interface.h
generate-expr-from-tarballs.pl
imake-setup-hook.sh
imake.sh
xquartz
patch_plist.rb
zigbee2mqtt
update.sh
shells
bash
update-patch-set.sh
stdenv
cygwin
all-buildinputs-as-runtimedep.sh
rebase-i686.sh
rebase-x86_64.sh
wrap-exes-to-find-dlls.sh
darwin
portable-libsystem.sh
unpack-bootstrap-tools-aarch64.sh
unpack-bootstrap-tools.sh
freebsd
trivial-bootstrap.sh
trivial-builder.sh
generic
builder.sh
default-builder.sh
setup.sh
linux
bootstrap-tools-musl
scripts
unpack-bootstrap-tools.sh
bootstrap-tools
scripts
unpack-bootstrap-tools.sh
test
cc-wrapper
cc-main.c
cflags-main.c
core-foundation-main.c
foo.c
ldflags-main.c
nostdinc-main.c
sanitizers.c
stdio.h
make-binary-wrapper
add-flags.c
add-flags.env
argv0.c
argv0.env
basic.c
basic.env
chdir.c
chdir.env
combination.c
combination.env
env.c
env.env
envcheck.c
inherit-argv0.c
inherit-argv0.env
invalid-env.c
prefix.c
prefix.env
suffix.c
suffix.env
simple
builder.sh
stdenv-inputs
bar.c
cc-main.c
foo.c
include-main.c
lib-main.c
tools
X11
opentabletdriver
update.sh
xkbvalidate
xkbvalidate.c
xkeysnail
browser-emacs-bindings.py
xpra
update.sh
admin
cjdns-tools
wrapper.sh
google-cloud-sdk
alpha__init__.py
beta__init__.py
update.sh
meshcentral
package.json
update.sh
pgadmin
package.json
pulumi
update.sh
archivers
7zz
update.sh
p7zip
setup-hook.sh
update.sh
rpmextract
rpmextract.sh
undmg
setup-hook.sh
unrar-wrapper
setup-hook.sh
unrar
setup-hook.sh
unzip
setup-hook.sh
audio
botamusique
src.json
backup
discordchatexporter-cli
updater.sh
compression
lzip
lzip-setup-hook.sh
filesystems
rmfuse
pyproject.toml
graphics
gnuplot
set-gdfontpath-from-fontconfig.sh
ldgallery
compiler
generate.sh
viewer
generate.sh
netpbm
update.sh
plotutils
debian-patches.txt
puppeteer-cli
package.json
zxing
java-zxing.sh
zxing-cmdline-encoder.sh
zxing-cmdline-runner.sh
zxing.sh
inputmethods
fcitx5
update.py
misc
btdu
update.py
depotdownloader
fetch-deps.sh
desktop-file-utils
setup-hook.sh
diffoscope
list-missing-tools.sh
execline
execlineb-wrapper.c
fx_cast
package-lock.json
package.json
grub
grub1.patches.sh
sharedown
update.sh
xvfb-run
update.sh
networking
airfield
deps.json
deps.sh
boundary
update.sh
ngrok-2
update.sh
versions.json
v2ray
update.sh
wireguard-go
update.sh
wireguard-tools
update.sh
nix
info
info.sh
nix-output-monitor
update.sh
nixos-option
CMakeLists.txt
package-management
nixops
python-env
pyproject.toml
nixui
generate.sh
pkg.json
security
afl
README.md
enpass
data.json
update_script.py
firefox_decrypt
update.sh
metasploit
update.sh
oath-toolkit
update.sh
onlykey
generate.sh
package.json
vault
update-bin.sh
wpscan
update.sh
system
plan9port
builder.sh
text
chroma
src.json
gawk
setup-hook.sh
sgml
opensp
setup-hook.sh
xml
basex
basex.svg
typesetting
lout
builder.sh
tex
nix
animatedot.sh
copy-includes.pl
dot2pdf.sh
dot2ps.sh
find-includes.pl
find-lhs2tex-includes.sh
lhs2tex.sh
run-latex.sh
tetex
setup-hook.sh
texlive
UPGRADING.md
setup-hook.sh
virtualization
linode-cli
update.sh
nixos-container
nixos-container-completion.sh
nixos-container.pl
wayland
swaytools
update.py
Downloading extension
Unpacking extension
Unpacked extension
Runtime dependencies
Runtime deps missing elf deps
Runtime dep mono
Runtime dep clang
Nix mono
| # To update Elm:
Modify revision in ./update.sh and run it
# Notes about the build process:
The elm binary embeds a piece of pre-compiled elm code, used by 'elm
reactor'. This means that the build process for 'elm' effectively
executes 'elm make'. that in turn expects to retrieve the elm
dependencies of that code (elm/core, etc.) from
package.elm-lang.org, as well as a cached bit of metadata
(versions.dat).
The makeDotElm function lets us retrieve these dependencies in the
standard nix way. we have to copy them in (rather than symlink) and
make them writable because the elm compiler writes other .dat files
alongside the source code. versions.dat was produced during an
impure build of this same code; the build complains that it can't
update this cache, but continues past that warning.
Finally, we set ELM_HOME to point to these pre-fetched artifacts so
that the default of ~/.elm isn't used.
More: https://blog.hercules-ci.com/elm/2019/01/03/elm2nix-0.1/
# `cypress-example-kitchensink`
This directory 'packages' [cypress-example-kitchensink](https://github.com/cypress-io/cypress-example-kitchensink),
which is used in `cypress.passthru.tests`.
The app is not really intended for deployment, so I didn't bother with actual packaging, just testing.
If your real-world app looks like `cypress-example-kitchensink`, you'll want to use Nix multiple outputs so you don't deploy your test videos along with your app.
Alternatively, you can set it up so that one derivation builds your server exe and another derivation takes that server exe and runs it with the cypress e2e tests.
## Peculiarities
**cypress and Cypress** are distinct names.
- `cypress` is the npm module, containing the executable `cypress`
- whereas the executable `Cypress` comes from `pkgs.cypress`, a binary distribution (as of writing) by cypress.io.
**updateScript** is not provided for this example project. This seems preferable,
because updates to it aren't particularly valuable and have a significant overhead.
The goal is to smoke test `cypress`; not run the latest test suite (which it isn't anyway).
## Updating
- update the hash in `src.nix`
- run `regen-nix`
This directory is temporarily needed while we transition the manual to CommonMark. It stores the output of the ../md-to-db.sh script that converts CommonMark files back to DocBook.
We are choosing to convert the Markdown to DocBook at authoring time instead of manual building time, because we do not want the pandoc toolchain to become part of the NixOS closure.
Do not edit the DocBook files inside this directory or its subdirectories. Instead, edit the corresponding .md file in the normal manual directories, and run ../md-to-db.sh to update the file here.
# Fake Certificate Authority for ACME testing
This will set up a test node running [pebble](https://github.com/letsencrypt/pebble)
to serve ACME certificate requests.
## "Snake oil" certs
The snake oil certs are hard coded into the repo for reasons explained [here](https://github.com/NixOS/nixpkgs/pull/91121#discussion_r505410235).
The root of the issue is that Nix will hash the derivation based on the arguments
to mkDerivation, not the output. [Minica](https://github.com/jsha/minica) will
always generate a random certificate even if the arguments are unchanged. As a
result, it's possible to end up in a situation where the cached and local
generated certs mismatch and cause issues with testing.
To generate new certificates, run the following commands:
```bash
nix-build generate-certs.nix
cp result/* .
rm result
```
Updating the QEMU patches
=========================
When updating to the latest American Fuzzy Lop, make sure to check for
any new patches to qemu for binary fuzzing support:
https://github.com/google/AFL/tree/master/qemu_mode
Be sure to check the build script and make sure it's also using the
right QEMU version and options in `qemu.nix`:
https://github.com/google/AFL/blob/master/qemu_mode/build_qemu_support.sh
`afl-config.h`, `afl-types.h`, and `afl-qemu-cpu-inl.h` are part of
the afl source code, and copied from `config.h`, `types.h` and
`afl-qemu-cpu-inl.h` appropriately. These files and the QEMU patches
need to be slightly adjusted to fix their `#include`s (the patches
try to otherwise include files like `../../config.h` which causes the
build to fail).
# Using resholve's Nix API
resholve replaces bare references (subject to a PATH search at runtime) to external commands and scripts with absolute paths.
This small super-power helps ensure script dependencies are declared, present, and don't unexpectedly shift when the PATH changes.
resholve is developed to enable the Nix package manager to package and integrate Shell projects, but its features are not Nix-specific and inevitably have other applications.
<!-- generated from resholve's repo; best to suggest edits there (or at least notify me) -->
This will hopefully make its way into the Nixpkgs manual soon, but
until then I'll outline how to use the functions:
- `resholve.mkDerivation` (formerly `resholvePackage`)
- `resholve.writeScript` (formerly `resholveScript`)
- `resholve.writeScriptBin` (formerly `resholveScriptBin`)
- `resholve.phraseSolution` (new in resholve 0.8.0)
> Fair warning: resholve does *not* aspire to resolving all valid Shell
> scripts. It depends on the OSH/Oil parser, which aims to support most (but
> not all) Bash. resholve aims to be a ~90% sort of solution.
## API Concepts
The main difference between `resholve.mkDerivation` and other builder functions
is the `solutions` attrset, which describes which scripts to resolve and how.
Each "solution" (k=v pair) in this attrset describes one resholve invocation.
> NOTE: For most shell packages, one invocation will probably be enough:
> - Packages with a single script will only need one solution.
> - Packages with multiple scripts can still use one solution if the scripts
> don't require conflicting directives.
> - Packages with scripts that require conflicting directives can use multiple
> solutions to resolve the scripts separately, but produce a single package.
`resholve.writeScript` and `resholve.writeScriptBin` support a _single_
`solution` attrset. This is basically the same as any single solution in `resholve.mkDerivation`, except that it doesn't need a `scripts` attr (it is automatically added). `resholve.phraseSolution` also only accepts a single solution--but it _does_ still require the `scripts` attr.
## Basic `resholve.mkDerivation` Example
Here's a simple example of how `resholve.mkDerivation` is already used in nixpkgs:
<!-- TODO: figure out how to pull this externally? -->
```nix
{ lib
, fetchFromGitHub
, resholve
, substituteAll
, bash
, coreutils
, goss
, which
}:
resholve.mkDerivation rec {
pname = "dgoss";
version = "0.3.16";
src = fetchFromGitHub {
owner = "aelsabbahy";
repo = "goss";
rev = "v${version}";
sha256 = "1m5w5vwmc9knvaihk61848rlq7qgdyylzpcwi64z84rkw8qdnj6p";
};
dontConfigure = true;
dontBuild = true;
installPhase = ''
sed -i '2i GOSS_PATH=${goss}/bin/goss' extras/dgoss/dgoss
install -D extras/dgoss/dgoss $out/bin/dgoss
'';
solutions = {
default = {
scripts = [ "bin/dgoss" ];
interpreter = "${bash}/bin/bash";
inputs = [ coreutils which ];
fake = {
external = [ "docker" ];
};
};
};
meta = with lib; {
homepage = "https://github.com/aelsabbahy/goss/blob/v${version}/extras/dgoss/README.md";
description = "Convenience wrapper around goss that aims to bring the simplicity of goss to docker containers";
license = licenses.asl20;
platforms = platforms.linux;
maintainers = with maintainers; [ hyzual ];
};
}
```
## Basic `resholve.writeScript` and `resholve.writeScriptBin` examples
Both of these functions have the same basic API. This example is a little
trivial for now. If you have a real usage that you find helpful, please PR it.
```nix
resholvedScript = resholve.writeScript "name" {
inputs = [ file ];
interpreter = "${bash}/bin/bash";
} ''
echo "Hello"
file .
'';
resholvedScriptBin = resholve.writeScriptBin "name" {
inputs = [ file ];
interpreter = "${bash}/bin/bash";
} ''
echo "Hello"
file .
'';
```
## Basic `resholve.phraseSolution` example
This function has a similar API to `writeScript` and `writeScriptBin`, except it does require a `scripts` attr. It is intended to make resholve a little easier to mix into more types of build. This example is a little
trivial for now. If you have a real usage that you find helpful, please PR it.
```nix
{ stdenv, resholve, module1 }:
stdenv.mkDerivation {
# pname = "testmod3";
# version = "unreleased";
# src = ...;
installPhase = ''
mkdir -p $out/bin
install conjure.sh $out/bin/conjure.sh
${resholve.phraseSolution "conjure" {
scripts = [ "bin/conjure.sh" ];
interpreter = "${bash}/bin/bash";
inputs = [ module1 ];
fake = {
external = [ "jq" "openssl" ];
};
}}
'';
}
```
## Options
`resholve.mkDerivation` maps Nix types/idioms into the flags and environment variables
that the `resholve` CLI expects. Here's an overview:
| Option | Type | Containing |
|--------|------|------------|
| scripts | `<list>` | scripts to resolve (`$out`-relative paths) |
| interpreter | `"none"` `<path>` | The absolute interpreter `<path>` for the script's shebang. The special value `none` ensures there is no shebang. |
| inputs | `<packages>` | Packages to resolve external dependencies from. |
| fake | `<directives>` | pretend some commands exist |
| fix | `<directives>` | fix things we can't auto-fix/ignore |
| keep | `<directives>` | keep things we can't auto-fix/ignore |
| lore | `<directory>` | control nested resolution |
| execer | `<statements>` | modify nested resolution |
| wrapper | `<statements>` | modify nested resolution |
| prologue | `<file>` | insert file before resolved script |
| epilogue | `<file>` | insert file after resolved script |
<!-- TODO: section below is largely custom for nixpkgs, but I would LIKE to wurst it. -->
## Controlling resolution with directives
In order to resolve a script, resholve will make you disambiguate how it should
handle any potential problems it encounters with directives. There are currently
3 types:
1. `fake` directives tell resholve to pretend it knows about an identifier
such as a function, builtin, external command, etc. if there's a good reason
it doesn't already know about it. Common examples:
- builtins for a non-bash shell
- loadable builtins
- platform-specific external commands in cross-platform conditionals
2. `fix` directives give resholve permission to fix something that it can't
safely fix automatically. Common examples:
- resolving commands in aliases (this is appropriate for standalone scripts
that use aliases non-interactively--but it would prevent profile/rc
scripts from using the latest current-system symlinks.)
- resolve commands in a variable definition
- resolve an absolute command path from inputs as if it were a bare reference
3. `keep` directives tell resholve not to raise an error (i.e., ignore)
something it would usually object to. Common examples:
- variables used as/within the first word of a command
- pre-existing absolute or user-relative (~) command paths
- dynamic (variable) arguments to commands known to accept/run other commands
> NOTE: resholve has a (growing) number of directives detailed in `man resholve`
> via `nixpkgs.resholve`.
Each of these 3 types is represented by its own attrset, where you can think
of the key as a scope. The value should be:
- `true` for any directives that the resholve CLI accepts as a single word
- a list of strings for all other options
<!--
TODO: these should be fully-documented here, but I'm already maintaining
more copies of their specification/behavior than I like, and continuing to
add more at this early date will only ensure that I spend more time updating
docs and less time filling in feature gaps.
Full documentation may be greatly accellerated if someone can help me sort out
single-sourcing. See: https://github.com/abathur/resholve/issues/19
-->
This will hopefully make more sense when you see it. Here are CLI examples
from the manpage, and the Nix equivalents:
```nix
# --fake 'f:setUp;tearDown builtin:setopt source:/etc/bashrc'
fake = {
# fake accepts the initial of valid identifier types as a CLI convenience.
# Use full names in the Nix API.
function = [ "setUp" "tearDown" ];
builtin = [ "setopt" ];
source = [ "/etc/bashrc" ];
};
# --fix 'aliases $GIT:gix /bin/bash'
fix = {
# all single-word directives use `true` as value
aliases = true;
"$GIT" = [ "gix" ];
"/bin/bash";
};
# --keep 'source:$HOME /etc/bashrc ~/.bashrc'
keep = {
source = [ "$HOME" ];
"/etc/bashrc" = true;
"~/.bashrc" = true;
};
```
> **Note:** For now, at least, you'll need to reference the manpage to completely understand these examples.
## Controlling nested resolution with lore
Initially, resolution of commands in the arguments to command-executing
commands was limited to one level for a hard-coded list of builtins and
external commands. resholve can now resolve these recursively.
This feature combines information (_lore_) that the resholve Nix API
obtains via binlore ([nixpkgs](../../tools/analysis/binlore), [repo](https://github.com/abathur/resholve)),
with some rules (internal to resholve) for locating sub-executions in
some of the more common commands.
- "execer" lore identifies whether an executable can, cannot,
or might execute its arguments. Every "can" or "might" verdict requires
either built-in rules for finding the executable, or human triage.
- "wrapper" lore maps shell exec wrappers to the programs they exec so
that resholve can substitute an executable's verdict for its wrapper's.
> **Caution:** At least when it comes to common utilities, it's best to treat
> overrides as a stopgap until they can be properly handled in resholve and/or
> binlore. Please report things you have to override and, if possible, help
> get them sorted.
There will be more mechanisms for controlling this process in the future
(and your reports/experiences will play a role in shaping them...) For now,
the main lever is the ability to substitute your own lore. This is how you'd
do it piecemeal:
```nix
# --execer 'cannot:${openssl.bin}/bin/openssl can:${openssl.bin}/bin/c_rehash'
execer = [
/*
This is the same verdict binlore will
come up with. It's a no-op just to demo
how to fiddle lore via the Nix API.
*/
"cannot:${openssl.bin}/bin/openssl"
# different verdict, but not used
"can:${openssl.bin}/bin/c_rehash"
];
# --wrapper '${gnugrep}/bin/egrep:${gnugrep}/bin/grep'
execer = [
/*
This is the same verdict binlore will
come up with. It's a no-op just to demo
how to fiddle lore via the Nix API.
*/
"${gnugrep}/bin/egrep:${gnugrep}/bin/grep"
];
```
The format is fairly simple to generate--you can script your own generator if
you need to modify the lore.
# Maintainers
- Note: We could always use more contributors, testers, etc. E.g.:
- A dedicated maintainer for the NixOS stable channel
- PRs with cleanups, improvements, fixes, etc. (but please try to make reviews
as easy as possible)
- People who handle stale issues/PRs
- Primary maintainer (responsible for all updates): @primeos
- Testers (test all stable channel updates)
- `nixos-unstable`:
- `x86_64`: @danielfullmer
- `aarch64`: @thefloweringash
- Stable channel:
- `x86_64`: @Frostman
- Other relevant packages:
- `chromiumBeta` and `chromiumDev`: For testing purposes only (not build on
Hydra). We use these channels for testing and to fix build errors in advance
so that `chromium` updates are trivial and can be merged fast.
- `google-chrome`, `google-chrome-beta`, `google-chrome-dev`: Updated via
Chromium's `upstream-info.json`
- `ungoogled-chromium`: @squalus
- `chromedriver`: Updated via Chromium's `upstream-info.json` and not built
from source.
# Upstream links
- Source code: https://source.chromium.org/chromium/chromium/src
- Bugs: https://bugs.chromium.org/p/chromium/issues/list
- Release updates: https://chromereleases.googleblog.com/
- Available as Atom or RSS feed (filter for
"Stable Channel Update for Desktop")
- Channel overview: https://omahaproxy.appspot.com/
- Release schedule: https://chromiumdash.appspot.com/schedule
# Updating Chromium
Simply run `./pkgs/applications/networking/browsers/chromium/update.py` to
update `upstream-info.json`. After updates it is important to test at least
`nixosTests.chromium` (or basic manual testing) and `google-chrome` (which
reuses `upstream-info.json`).
Note: The source tarball is often only available a few hours after the release
was announced. The CI/CD status can be tracked here:
- https://ci.chromium.org/p/infra/builders/cron/publish_tarball
- https://ci.chromium.org/p/infra/builders/cron/publish_tarball_dispatcher
To run all automated NixOS VM tests for Chromium, ungoogled-chromium,
and Google Chrome (not recommended, currently 6x tests!):
```
nix-build nixos/tests/chromium.nix
```
A single test can be selected, e.g. to test `ungoogled-chromium` (see
`channelMap` in `nixos/tests/chromium.nix` for all available options):
```
nix-build nixos/tests/chromium.nix -A ungoogled
```
(Note: Testing Google Chrome requires `export NIXPKGS_ALLOW_UNFREE=1`.)
For custom builds it's possible to "override" `channelMap`.
## Backports
All updates are considered security critical and should be ported to the stable
channel ASAP. When there is a new stable release the old one should receive
security updates for roughly one month. After that it is important to mark
Chromium as insecure (see 69e4ae56c4b for an example; it is important that the
tested job still succeeds and that all browsers that use `upstream-info.json`
are marked as insecure).
## Major version updates
Unfortunately, Chromium regularly breaks on major updates and might need
various patches. Either due to issues with the Nix build sandbox (e.g. we cannot
fetch dependencies via the network and do not use standard FHS paths) or due to
missing upstream fixes that need to be backported.
Good sources for such patches and other hints:
- https://github.com/archlinux/svntogit-packages/tree/packages/chromium/trunk
- https://gitweb.gentoo.org/repo/gentoo.git/tree/www-client/chromium
- https://src.fedoraproject.org/rpms/chromium/tree/master
If the build fails immediately due to unknown compiler flags this usually means
that a new major release of LLVM is required.
## Beta and Dev channels
Those channels are only used to test and fix builds in advance. They may be
broken at times and must not delay stable channel updates.
# Testing
Useful tests:
- Version: chrome://version/
- GPU acceleration: chrome://gpu/
- Essential functionality: Browsing, extensions, video+audio, JS, ...
- WebGL: https://get.webgl.org/
- VA-API: https://wiki.archlinux.org/index.php/chromium#Hardware_video_acceleration
- Optional: Widevine CDM (proprietary), Benchmarks, Ozone, etc.
<p align="center">
<a href="https://nixos.org#gh-light-mode-only">
<img src="https://raw.githubusercontent.com/NixOS/nixos-homepage/master/logo/nixos-hires.png" width="500px" alt="NixOS logo"/>
</a>
<a href="https://nixos.org#gh-dark-mode-only">
<img src="https://raw.githubusercontent.com/NixOS/nixos-artwork/master/logo/nixos-white.png" width="500px" alt="NixOS logo"/>
</a>
</p>
<p align="center">
<a href="https://github.com/NixOS/nixpkgs/blob/master/CONTRIBUTING.md"><img src="https://img.shields.io/github/contributors-anon/NixOS/nixpkgs" alt="Contributors badge" /></a>
<a href="https://opencollective.com/nixos"><img src="https://opencollective.com/nixos/tiers/supporter/badge.svg?label=supporters&color=brightgreen" alt="Open Collective supporters" /></a>
</p>
[Nixpkgs](https://github.com/nixos/nixpkgs) is a collection of over
80,000 software packages that can be installed with the
[Nix](https://nixos.org/nix/) package manager. It also implements
[NixOS](https://nixos.org/nixos/), a purely-functional Linux distribution.
# Manuals
* [NixOS Manual](https://nixos.org/nixos/manual) - how to install, configure, and maintain a purely-functional Linux distribution
* [Nixpkgs Manual](https://nixos.org/nixpkgs/manual/) - contributing to Nixpkgs and using programming-language-specific Nix expressions
* [Nix Package Manager Manual](https://nixos.org/nix/manual) - how to write Nix expressions (programs), and how to use Nix command line tools
# Community
* [Discourse Forum](https://discourse.nixos.org/)
* [Matrix Chat](https://matrix.to/#/#community:nixos.org)
* [NixOS Weekly](https://weekly.nixos.org/)
* [Community-maintained wiki](https://nixos.wiki/)
* [Community-maintained list of ways to get in touch](https://nixos.wiki/wiki/Get_In_Touch#Chat) (Discord, Telegram, IRC, etc.)
# Other Project Repositories
The sources of all official Nix-related projects are in the [NixOS
organization on GitHub](https://github.com/NixOS/). Here are some of
the main ones:
* [Nix](https://github.com/NixOS/nix) - the purely functional package manager
* [NixOps](https://github.com/NixOS/nixops) - the tool to remotely deploy NixOS machines
* [nixos-hardware](https://github.com/NixOS/nixos-hardware) - NixOS profiles to optimize settings for different hardware
* [Nix RFCs](https://github.com/NixOS/rfcs) - the formal process for making substantial changes to the community
* [NixOS homepage](https://github.com/NixOS/nixos-homepage) - the [NixOS.org](https://nixos.org) website
* [hydra](https://github.com/NixOS/hydra) - our continuous integration system
* [NixOS Artwork](https://github.com/NixOS/nixos-artwork) - NixOS artwork
# Continuous Integration and Distribution
Nixpkgs and NixOS are built and tested by our continuous integration
system, [Hydra](https://hydra.nixos.org/).
* [Continuous package builds for unstable/master](https://hydra.nixos.org/jobset/nixos/trunk-combined)
* [Continuous package builds for the NixOS 21.11 release](https://hydra.nixos.org/jobset/nixos/release-21.11)
* [Tests for unstable/master](https://hydra.nixos.org/job/nixos/trunk-combined/tested#tabs-constituents)
* [Tests for the NixOS 21.11 release](https://hydra.nixos.org/job/nixos/release-21.11/tested#tabs-constituents)
Artifacts successfully built with Hydra are published to cache at
https://cache.nixos.org/. When successful build and test criteria are
met, the Nixpkgs expressions are distributed via [Nix
channels](https://nixos.org/manual/nix/stable/package-management/channels.html).
# Contributing
Nixpkgs is among the most active projects on GitHub. While thousands
of open issues and pull requests might seem a lot at first, it helps
consider it in the context of the scope of the project. Nixpkgs
describes how to build tens of thousands of pieces of software and implements a
Linux distribution. The [GitHub Insights](https://github.com/NixOS/nixpkgs/pulse)
page gives a sense of the project activity.
Community contributions are always welcome through GitHub Issues and
Pull Requests. When pull requests are made, our tooling automation bot,
[OfBorg](https://github.com/NixOS/ofborg) will perform various checks
to help ensure expression quality.
The *Nixpkgs maintainers* are people who have assigned themselves to
maintain specific individual packages. We encourage people who care
about a package to assign themselves as a maintainer. When a pull
request is made against a package, OfBorg will notify the appropriate
maintainer(s). The *Nixpkgs committers* are people who have been given
permission to merge.
Most contributions are based on and merged into these branches:
* `master` is the main branch where all small contributions go
* `staging` is branched from master, changes that have a big impact on
Hydra builds go to this branch
* `staging-next` is branched from staging and only fixes to stabilize
and security fixes with a big impact on Hydra builds should be
contributed to this branch. This branch is merged into master when
deemed of sufficiently high quality
For more information about contributing to the project, please visit
the [contributing page](https://github.com/NixOS/nixpkgs/blob/master/CONTRIBUTING.md).
# Donations
The infrastructure for NixOS and related projects is maintained by a
nonprofit organization, the [NixOS
Foundation](https://nixos.org/nixos/foundation.html). To ensure the
continuity and expansion of the NixOS infrastructure, we are looking
for donations to our organization.
You can donate to the NixOS foundation through [SEPA bank
transfers](https://nixos.org/donate.html) or by using Open Collective:
<a href="https://opencollective.com/nixos#support"><img src="https://opencollective.com/nixos/tiers/supporter.svg?width=890" /></a>
# License
Nixpkgs is licensed under the [MIT License](COPYING).
Note: MIT license does not apply to the packages built by Nixpkgs,
merely to the files in this repository (the Nix expressions, build
scripts, NixOS modules, etc.). It also might not apply to patches
included in Nixpkgs, which may be derivative works of the packages to
which they apply. The aforementioned artifacts are all covered by the
licenses of the respective packages.
Moved to [/doc/languages-frameworks/r.section.md](/doc/languages-frameworks/r.section.md)
# Nixpkgs/doc
This directory houses the sources files for the Nixpkgs manual.
You can find the [rendered documentation for Nixpkgs `unstable` on nixos.org](https://nixos.org/manual/nixpkgs/unstable/).
[Docs for Nixpkgs stable](https://nixos.org/manual/nixpkgs/stable/) are also available.
If you want to contribute to the documentation, [here's how to do it](https://nixos.org/manual/nixpkgs/unstable/#chap-contributing).
If you're only getting started with Nix, go to [nixos.org/learn](https://nixos.org/learn).
# GNOME Shell extensions
All extensions are packaged automatically. They can be found in the `pkgs.gnomeXYExtensions` for XY being a GNOME version. The package names are the extensionโs UUID, which can be a bit unwieldy to use. `pkgs.gnomeExtensions` is a set of manually curated extensions that match the current `gnome.gnome-shell` versions. Their name is human-friendly, compared to the other extensions sets. Some of its extensions are manually packaged.
## Automatically packaged extensions
The actual packages are created by `buildGnomeExtension.nix`, provided the correct arguments are fed into it. The important extension data is stored in `extensions.json`, one line/item per extension. That file is generated by running `update-extensions.py`. Furthermore, the automatic generated names are dumped in `collisions.json` for manual inspection. `extensionRenames.nix` contains new names for all extensions that collide.
### Extensions updates
For everyday updates,
1. Run `update-extensions.py`.
2. Update `extensionRenames.nix` according to the comment at the top.
For GNOME updates,
1. Add a new `gnomeXYExtensions` set
2. Remove old ones for GNOME versions we donโt want to support any more
3. Update `supported_versions` in `./update-extensions.py` and re-run it
4. Change `gnomeExtensions` to the new version
5. Update `./extensionsRenames.nix` accordingly
6. Update `all-packages.nix` accordingly (grep for `gnomeExtensions`)
## Manually packaged extensions
Manually packaged extensions overwrite some of the automatically packaged ones in `pkgs.gnomeExtensions`. They are listed in `manuallyPackaged.nix`, every extension has its own sub-folder.
This file was generated with pkgs/misc/documentation-highlighter/update.sh
# Highlight.js
[](https://travis-ci.org/isagalaev/highlight.js)
Highlight.js is a syntax highlighter written in JavaScript. It works in
the browser as well as on the server. It works with pretty much any
markup, doesnโt depend on any framework and has automatic language
detection.
## Getting Started
The bare minimum for using highlight.js on a web page is linking to the
library along with one of the styles and calling
[`initHighlightingOnLoad`][1]:
```html
<link rel="stylesheet" href="/path/to/styles/default.css">
<script src="/path/to/highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
```
This will find and highlight code inside of `<pre><code>` tags; it tries
to detect the language automatically. If automatic detection doesnโt
work for you, you can specify the language in the `class` attribute:
```html
<pre><code class="html">...</code></pre>
```
The list of supported language classes is available in the [class
reference][2]. Classes can also be prefixed with either `language-` or
`lang-`.
To disable highlighting altogether use the `nohighlight` class:
```html
<pre><code class="nohighlight">...</code></pre>
```
## Custom Initialization
When you need a bit more control over the initialization of
highlight.js, you can use the [`highlightBlock`][3] and [`configure`][4]
functions. This allows you to control *what* to highlight and *when*.
Hereโs an equivalent way to calling [`initHighlightingOnLoad`][1] using
jQuery:
```javascript
$(document).ready(function() {
$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
});
```
You can use any tags instead of `<pre><code>` to mark up your code. If
you don't use a container that preserve line breaks you will need to
configure highlight.js to use the `<br>` tag:
```javascript
hljs.configure({useBR: true});
$('div.code').each(function(i, block) {
hljs.highlightBlock(block);
});
```
For other options refer to the documentation for [`configure`][4].
## Web Workers
You can run highlighting inside a web worker to avoid freezing the browser
window while dealing with very big chunks of code.
In your main script:
```javascript
addEventListener('load', function() {
var code = document.querySelector('#code');
var worker = new Worker('worker.js');
worker.onmessage = function(event) { code.innerHTML = event.data; }
worker.postMessage(code.textContent);
})
```
In worker.js:
```javascript
onmessage = function(event) {
importScripts('<path>/highlight.pack.js');
var result = self.hljs.highlightAuto(event.data);
postMessage(result.value);
}
```
## Getting the Library
You can get highlight.js as a hosted, or custom-build, browser script or
as a server module. Right out of the box the browser script supports
both AMD and CommonJS, so if you wish you can use RequireJS or
Browserify without having to build from source. The server module also
works perfectly fine with Browserify, but there is the option to use a
build specific to browsers rather than something meant for a server.
Head over to the [download page][5] for all the options.
**Don't link to GitHub directly.** The library is not supposed to work straight
from the source, it requires building. If none of the pre-packaged options
work for you refer to the [building documentation][6].
**The CDN-hosted package doesn't have all the languages.** Otherwise it'd be
too big. If you don't see the language you need in the ["Common" section][5],
it can be added manually:
```html
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.4.0/languages/go.min.js"></script>
```
**On Almond.** You need to use the optimizer to give the module a name. For
example:
```
r.js -o name=hljs paths.hljs=/path/to/highlight out=highlight.js
```
## License
Highlight.js is released under the BSD License. See [LICENSE][7] file
for details.
## Links
The official site for the library is at <https://highlightjs.org/>.
Further in-depth documentation for the API and other topics is at
<http://highlightjs.readthedocs.io/>.
Authors and contributors are listed in the [AUTHORS.en.txt][8] file.
[1]: http://highlightjs.readthedocs.io/en/latest/api.html#inithighlightingonload
[2]: http://highlightjs.readthedocs.io/en/latest/css-classes-reference.html
[3]: http://highlightjs.readthedocs.io/en/latest/api.html#highlightblock-block
[4]: http://highlightjs.readthedocs.io/en/latest/api.html#configure-options
[5]: https://highlightjs.org/download/
[6]: http://highlightjs.readthedocs.io/en/latest/building-testing.html
[7]: https://github.com/isagalaev/highlight.js/blob/master/LICENSE
[8]: https://github.com/isagalaev/highlight.js/blob/master/AUTHORS.en.txt
# The Bazel build tool
https://bazel.build/
The bazel tool requires regular maintenance, especially under darwin, so we created a maintainers team.
Please ping @NixOS/bazel in your github PR/issue to increase your chance of a quick turnaround, thanks!
# Elm packages
Mixtures of useful Elm lang tooling containing both Haskell and Node.js based utilities.
## Upgrades
Haskell parts of the ecosystem are using [cabal2nix](https://github.com/NixOS/cabal2nix).
Please refer to [nix documentation](https://nixos.org/nixpkgs/manual/#how-to-create-nix-builds-for-your-own-private-haskell-packages)
and [cabal2nix readme](https://github.com/NixOS/cabal2nix#readme) for more information. Elm-format [update scripts](https://github.com/avh4/elm-format/tree/master/package/nix)
is part of its repository.
Node dependencies are defined in [node-packages.json](node-packages.json).
[Node2nix](https://github.com/svanderburg/node2nix) is used for generating nix expression
from this file. Use [generate-node-packages.sh](generate-node-packages.sh) for updates of nix expressions.
## Binwrap Patch
Some node packages might use [binwrap](https://github.com/avh4/binwrap) typically for installing
[elmi-to-json](https://github.com/stoeffel/elmi-to-json). Binwrap is not compatible with nix.
To overcome issues with those packages apply [patch-binwrap.nix](patch-binwrap.nix) which essentially does 2 things.
1. It replaces binwrap scripts with noop shell scripts
2. It uses nix for installing the binaries to expected location in `node_modules`
Example usage be found in `elm/default.nix`.
LibreOffice
===========
To generate `src-$VARIANT/download.nix`, i.e. list of additional sources that
the libreoffice build process needs to download:
nix-shell gen-shell.nix --argstr variant VARIANT --run generate
Where VARIANT is either `still` or `fresh`.
catch_conflicts.py
==================
The file catch_conflicts.py is in a subdirectory because, if it isn't, the
/nix/store/ directory is added to sys.path causing a delay when building.
Pointers:
- https://docs.python.org/3/library/sys.html#sys.path
- https://github.com/NixOS/nixpkgs/pull/23600
[Moved to ./contributing-to-this-manual.chapter.md](./contributing-to-this-manual.chapter.md). Link:
https://nixos.org/manual/nixos/unstable/#chap-contributing
Moved to [/doc/languages-frameworks/idris.section.md](/doc/languages-frameworks/idris.section.md)
Moved to [/doc/languages-frameworks/javascript.section.md](/doc/languages-frameworks/javascript.section.md)
Dont change these files here, they are maintained at https://github.com/nix-community/poetry2nix
The update procedure is as-follows:
1. Send your change to the upstream poetry2nix repository
2. Get it approved with tests passing
3. Run the update script in pkgs/development/tools/poetry2nix
Patches for CPU Controller on Control Group v2
===============================================
See Tejun Heo's [explanation][1] for why these patches are currently
out-of-tree.
Generating the patches
-----------------------
In a linux checkout, with remote tc-cgroup pointing to
git://git.kernel.org/pub/scm/linux/kernel/git/tj/cgroup.git, your
nixpkgs checkout in the same directory as your linux checkout (or
modify the command accordingly), and setting `ver` to the appropriate
version:
```shell
$ ver=4.7
$ git log --reverse --patch v$ver..remotes/tc-cgroup/cgroup-v2-cpu-v$ver > ../nixpkgs/pkgs/os-specific/linux/kernel/cpu-cgroup-v2-patches/$ver.patch
```
[1]: https://git.kernel.org/cgit/linux/kernel/git/tj/cgroup.git/tree/Documentation/cgroup-v2-cpu.txt?h=cgroup-v2-cpu
# What is this for?
NixOS's traditional initrd is generated by listing the paths that
should be included in initrd and copying the full runtime closure of
those paths into the archive. For most things, like almost any
executable, this involves copying the entirety of huge packages like
glibc, when only things like the shared library files are needed. To
solve this, NixOS does a variety of patchwork to edit the files being
copied in so they only refer to small, patched up paths. For instance,
executables and their shared library dependencies are copied into an
`extraUtils` derivation, and every ELF file is patched to refer to
files in that output.
The problem with this is that it is often difficult to correctly patch
some things. For instance, systemd bakes the path to the `mount`
command into the binary, so patchelf is no help. Instead, it's very
often easier to simply copy the desired files to their original store
locations in initrd and not copy their entire runtime closure. This
does mean that it is the burden of the developer to ensure that all
necessary dependencies are copied in, as closures won't be
consulted. However, it is rare that full closures are actually
desirable, so in the traditional initrd, the developer was likely to
do manual work on patching the dependencies explicitly anyway.
# How it works
This program is similar to its inspiration (`find-libs` from the
traditional initrd), except that it also handles symlinks and
directories according to certain rules. As input, it receives a
sequence of pairs of paths. The first path is an object to copy into
initrd. The second path (if not empty) is the path to a symlink that
should be placed in the initrd, pointing to that object. How that
object is copied depends on its type.
1. A regular file is copied directly to the same absolute path in the
initrd.
- If it is *also* an ELF file, then all of its direct shared
library dependencies are also listed as objects to be copied.
2. A directory's direct children are listed as objects to be copied,
and a directory at the same absolute path in the initrd is created.
3. A symlink's target is listed as an object to be copied.
There are a couple of quirks to mention here. First, the term "object"
refers to the final file path that the developer intends to have
copied into initrd. This means any parent directory is not considered
an object just because its child was listed as an object in the
program input; instead those intermediate directories are simply
created in support of the target object. Second, shared libraries,
directory children, and symlink targets aren't immediately recursed,
because they simply get listed as objects themselves, and are
therefore traversed when they themselves are processed. Finally,
symlinks in the intermediate directories leading to an object are
preserved, meaning an input object `/a/symlink/b` will just result in
initrd containing `/a/symlink -> /target/b` and `/target/b`, even if
`/target` has other children. Preserving symlinks in this manner is
important for things like systemd.
These rules automate the most important and obviously necessary
copying that needs to be done in most cases, allowing programs and
configuration files to go unpatched, while keeping the content of the
initrd to a minimum.
# Why Rust?
- A prototype of this logic was written in Bash, in an attempt to keep
with its `find-libs` ancestor, but that program was difficult to
write, and ended up taking several minutes to run. This program runs
in less than a second, and the code is substantially easier to work
with.
- This will not require end users to install a rust toolchain to use
NixOS, as long as this tool is cached by Hydra. And if you're
bootstrapping NixOS from source, rustc is already required anyway.
- Rust was favored over Python for its type system, and because if you
want to go fast, why not go *really fast*?
# azure
## Demo
Here's a demo of this being used: https://asciinema.org/a/euXb9dIeUybE3VkstLWLbvhmp
## Usage
This is meant to be an example image that you can copy into your own
project and modify to your own needs. Notice that the example image
includes a built-in test user account, which by default uses your
`~/.ssh/id_ed25519.pub` as an `authorized_key`.
Build and upload the image
```shell
$ ./upload-image.sh ./examples/basic/image.nix
...
+ attr=azbasic
+ nix-build ./examples/basic/image.nix --out-link azure
/nix/store/qdpzknpskzw30vba92mb24xzll1dqsmd-azure-image
...
95.5 %, 0 Done, 0 Failed, 1 Pending, 0 Skipped, 1 Total, 2-sec Throughput (Mb/s): 932.9565
...
/subscriptions/aff271ee-e9be-4441-b9bb-42f5af4cbaeb/resourceGroups/nixos-images/providers/Microsoft.Compute/images/azure-image-todo-makethisbetter
```
Take the output, boot an Azure VM:
```
img="/subscriptions/.../..." # use output from last command
./boot-vm.sh "${img}"
...
=> booted
```
## Future Work
1. If the user specifies a hard-coded user, then the agent could be removed.
Probably has security benefits; definitely has closure-size benefits.
(It's likely the VM will need to be booted with a special flag. See:
https://github.com/Azure/azure-cli/issues/12775 for details.)
Julia
=====
[Julia][julia], as a full-fledged programming language with an extensive
standard library that covers numerical computing, can be somewhat challenging to
package. This file aims to provide pointers which could not easily be included
as comments in the expressions themselves.
[julia]: https://julialang.org
For Nixpkgs, the manual is as always your primary reference, and for the Julia
side of things you probably want to familiarise yourself with the [README
][readme], [build instructions][build], and [release process][release_process].
Remember that these can change between Julia releases, especially if the LTS and
release branches have deviated greatly. A lot of the build process is
underdocumented and thus there is no substitute for digging into the code that
controls the build process. You are very likely to need to use the test suite to
locate and address issues and in the end passing it, while only disabling a
minimal set of broken or incompatible tests you think you have a good reason to
disable, is your best bet at arriving at a solid derivation.
[readme]: https://github.com/JuliaLang/julia/blob/master/README.md
[build]: https://github.com/JuliaLang/julia/blob/master/doc/build/build.md
[release_process]: https://julialang.org/blog/2019/08/release-process
# Sage on nixos
Sage is a pretty complex package that depends on many other complex packages and patches some of those. As a result, the sage nix package is also quite complex.
Don't feel discouraged to fix, simplify or improve things though. The individual files have comments explaining their purpose. The most importent ones are `default.nix` linking everything together, `sage-src.nix` adding patches and `sagelib.nix` building the actual sage package.
## The sage build is broken
First you should find out which change to nixpkgs is at fault (if you don't already know). You can use `git-bisect` for that (see the manpage).
If the build broke as a result of a package update, try those solutions in order:
- search the [sage trac](https://trac.sagemath.org/) for keywords like "Upgrade <package>". Maybe somebody has already proposed a patch that fixes the issue. You can then add a `fetchpatch` to `sage-src.nix`.
- check if [gentoo](https://github.com/cschwan/sage-on-gentoo/tree/master/sci-mathematics/sage), [debian](https://salsa.debian.org/science-team/sagemath/tree/master/debian) or [arch linux](https://git.archlinux.org/svntogit/community.git/tree/trunk?h=packages/sagemath) already solved the problem. You can then again add a `fetchpatch` to `sage-src.nix`. If applicable you should also [propose the patch upstream](#proposing-a-sage-patch).
- fix the problem yourself. First clone the sagemath source and then check out the sage version you want to patch:
```
[user@localhost ~]$ git clone https://github.com/sagemath/sage.git
[user@localhost ~]$ cd sage
[user@localhost sage]$ git checkout 8.2 # substitute the relevant version here
```
Then make the needed changes and generate a patch with `git diff`:
```
[user@localhost ~]$ <make changes>
[user@localhost ~]$ git diff -u > /path/to/nixpkgs/pkgs/applications/science/math/sage/patches/name-of-patch.patch
```
Now just add the patch to `sage-src.nix` and test your changes. If they fix the problem, [propose them upstream](#proposing-a-sage-patch) and add a link to the trac ticket.
- pin the package version in `default.nix` and add a note that explains why that is necessary.
## Proposing a sage patch
You can [login the sage trac using GitHub](https://trac.sagemath.org/login). Your username will then be `gh-<your-github-name>`. The only other way is to request a trac account via email. After that refer to [git the hard way](http://doc.sagemath.org/html/en/developer/manual_git.html#chapter-manual-git) in the sage documentation. The "easy way" requires a non-GitHub account (requested via email) and a special tool. The "hard way" is really not all that hard if you're a bit familiar with git.
Here's the gist, assuming you want to use ssh key authentication. First, [add your public ssh key](https://trac.sagemath.org/prefs/sshkeys). Then:
```
[user@localhost ~]$ git clone https://github.com/sagemath/sage.git
[user@localhost ~]$ cd sage
[user@localhost sage]$ git remote add trac [email protected]:sage.git -t master
[user@localhost sage]$ git checkout -b u/gh-<your-github-username>/<your-branch-name> develop
[user@localhost sage]$ <make changes>
[user@localhost sage]$ git add .
[user@localhost sage]$ git commit
[user@localhost sage]$ git show # review your changes
[user@localhost sage]$ git push --set-upstream trac u/gh-<your-github-username>/<your-branch-name>
```
You now created a branch on the trac server (you *must* follow the naming scheme as you only have push access to branches with the `u/gh-<your-github-username>/` prefix).
Now you can [create a new trac ticket](https://trac.sagemath.org/newticket).
- Write a description of the change
- set the type and component as appropriate
- write your real name in the "Authors" field
- write `u/gh-<your-github-username>/<your-branch-name>` in the "Branch" field
- click "Create ticket"
- click "Modify" on the top right of your ticket (for some reason you can only change the ticket status after you have created it)
- set the ticket status from `new` to `needs_review`
- click "Save changes"
Refer to sages [Developer's Guide](http://doc.sagemath.org/html/en/developer/index.html) for further details.
## I want to update sage
You'll need to change the `version` field in `sage-src.nix`. Afterwards just try to build and let nix tell you which patches no longer apply (hopefully because they were adopted upstream). Remove those.
Hopefully the build will succeed now. If it doesn't and the problem is obvious, fix it as described in [The sage build is broken](#the-sage-build-is-broken).
If the problem is not obvious, you can try to first update sage to an intermediate version (remember that you can also set the `version` field to any git revision of sage) and locate the sage commit that introduced the issue. You can even use `git-bisect` for that (it will only be a bit tricky to keep track of which patches to apply). Hopefully after that the issue will be obvious.
## Well, that didn't help!
If you couldn't fix the problem, create a GitHub issue on the nixpkgs repo and ping @timokau (or whoever is listed in the `maintainers` list of the sage package).
Describe what you did and why it didn't work. Afterwards it would be great if you help the next guy out and improve this documentation!
|
metanear_metanear-web | README.md
package.json
public
index.html
manifest.json
robots.txt
src
Auth.js
Home.js
Router.js
apps
Chat
Channel.js
Chat.css
ChatApp.js
ChatMessage.js
KeysApp.js
MailApp.js
ProfileApp.js
assets
gray_near_logo.svg
logo.svg
near.svg
components
PowFaucet.js
css
App.css
index.js
| # [Meta NEAR Website](https://metanear.com)
Live: [metanear.com](https://metanear.com)
## Setup
```bash
yarn
```
## Run locally
```bash
yarn start
```
## Build and Deploy
```bash
yarn deploy
```
|
Peersyst_ckb-peersyst-sdk | README.md
examples
create-wallet.ts
deposit-in-dao.ts
get-dao-statistics.ts
get-dao-unlockable-amounts.ts
get-transactions.ts
import-wallet-error.ts
import-wallet.ts
issue-tokens.ts
send-transaction.ts
transfer-tokens.ts
unlock-from-dao.ts
wallet-balance.ts
package.json
src
core
assets
ckb.service.ts
nft.service.ts
nft.types.ts
token.service.ts
connection.service.ts
dao
dao.service.ts
transaction.service.ts
wallet.service.ts
index.ts
utils
logger.ts
parser.ts
tsconfig.build.json
tsconfig.json
| # Description
Peersyst typescrypt sdk to connect with nervos network
## Examples
In the folder example you can find examples on how to use the sdk.
To run any example use:
```
npm run example --name=wallet-balance
```
Where _wallet-balance_ can be any other example file name (import-wallet, create-wallet, get-transactions...)
## Installation
- To install the package with yarn use:
```
yarn add git+https://github.com/Peersyst/ckb-peersyst-sdk#1.0.0
```
- To install the package with npm use:
```
npm install --save git+https://github.com/Peersyst/ckb-peersyst-sdk#1.0.0
```
You can change the version changing what comes after #
## Usage
1. Instantiate connection service:
```typescrypt
import { ConnectionService, Environments, WalletService, Logger } from "@peersyst/ckb-peersyst-sdk";
const ckbUrl = "YourMainNodeRpcUrl";
const indexerUrl = "YourMainNodeIndexerUrl";
const connectionService = new ConnectionService(ckbUrl, indexerUrl, Environments.Mainnet);
```
2. Instantiate wallet service:
```typescrypt
// To create mnemonic if you do not have one:
const mnemonic = WalletService.createNewMnemonic();
const wallet = new WalletService(connectionService, mnemonic);
```
3. Refresh wallet data:
```typescrypt
await wallet.synchronize();
```
4. Make any call from the wallet:
```typescrypt
const totalBalance = await wallet.getBalance();
Logger.info(totalBalance);
const amount = BigInt(500 * 10 ** 8);
const txHash = await wallet.depositInDAO(amount, mnemonic);
```
|
noemk2_NEARspring-challeng4 | .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
components
Message.css
config.js
index.html
index.js
tests
integration
App-integration.test.js
ui
App-ui.test.js
| Guest Book
==========
[](https://travis-ci.com/near-examples/guest-book)
[](https://gitpod.io/#https://github.com/near-examples/guest-book)
<!-- MAGIC COMMENT: DO NOT DELETE! Everything above this line is hidden on NEAR Examples page -->
Sign in with [NEAR] and add a message to the guest book! A starter app built with an [AssemblyScript] backend and a [React] frontend.
Quick Start
===========
To run this project locally:
1. Prerequisites: Make sure you have Node.js โฅ 12 installed (https://nodejs.org), then use it to install [yarn]: `npm install --global yarn` (or just `npm i -g yarn`)
2. Run the local development server: `yarn && yarn dev` (see `package.json` for a
full list of `scripts` you can run with `yarn`)
Now you'll have a local development environment backed by the NEAR TestNet! Running `yarn dev` will tell you the URL you can visit in your browser to see the app.
Exploring The Code
==================
1. The backend code lives in the `/assembly` folder. This code gets deployed to
the NEAR blockchain when you run `yarn deploy:contract`. This sort of
code-that-runs-on-a-blockchain is called a "smart contract" โ [learn more
about NEAR smart contracts][smart contract docs].
2. The frontend code lives in the `/src` folder.
[/src/index.html](/src/index.html) is a great place to start exploring. Note
that it loads in `/src/index.js`, where you can learn how the frontend
connects to the NEAR blockchain.
3. Tests: there are different kinds of tests for the frontend and backend. The
backend code gets tested with the [asp] command for running the backend
AssemblyScript tests, and [jest] for running frontend tests. You can run
both of these at once with `yarn test`.
Both contract and client-side code will auto-reload as you change source files.
Deploy
======
Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `yarn dev`, your smart contracts get deployed to the live NEAR TestNet with a throwaway account. When you're ready to make it permanent, here's how.
Step 0: Install near-cli
--------------------------
You need near-cli installed globally. Here's how:
npm install --global near-cli
This will give you the `near` [CLI] tool. Ensure that it's installed with:
near --version
Step 1: Create an account for the contract
------------------------------------------
Visit [NEAR Wallet] and make a new account. You'll be deploying these smart contracts to this new account.
Now authorize NEAR CLI for this new account, and follow the instructions it gives you:
near login
Step 2: set contract name in code
---------------------------------
Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above.
const CONTRACT_NAME = process.env.CONTRACT_NAME || 'your-account-here!'
Step 3: change remote URL if you cloned this repo
-------------------------
Unless you forked this repository you will need to change the remote URL to a repo that you have commit access to. This will allow auto deployment to GitHub Pages from the command line.
1) go to GitHub and create a new repository for this project
2) open your terminal and in the root of this project enter the following:
$ `git remote set-url origin https://github.com/YOUR_USERNAME/YOUR_REPOSITORY.git`
Step 4: deploy!
---------------
One command:
yarn deploy
As you can see in `package.json`, this does two things:
1. builds & deploys smart contracts to NEAR TestNet
2. builds & deploys frontend code to GitHub using [gh-pages]. This will only work if the project already has a repository set up on GitHub. Feel free to modify the `deploy` script in `package.json` to deploy elsewhere.
[NEAR]: https://near.org/
[yarn]: https://yarnpkg.com/
[AssemblyScript]: https://www.assemblyscript.org/introduction.html
[React]: https://reactjs.org
[smart contract docs]: https://docs.near.org/docs/develop/contracts/overview
[asp]: https://www.npmjs.com/package/@as-pect/cli
[jest]: https://jestjs.io/
[NEAR accounts]: https://docs.near.org/docs/concepts/account
[NEAR Wallet]: https://wallet.near.org
[near-cli]: https://github.com/near/near-cli
[CLI]: https://www.w3schools.com/whatis/whatis_cli.asp
[create-near-app]: https://github.com/near/create-near-app
[gh-pages]: https://github.com/tschaub/gh-pages
|
htafolla_validator-tools | .gitpod.yml
Grafana-Near-Dashboard-v1.json
README.md
as-pect.config.js
asconfig.js
assembly
__tests__
as-pect.d.ts
main.spec.ts
as_types.d.ts
main.ts
model.ts
tsconfig.json
babel.config.js
package.json
report.20200531.164234.2624.0.001.json
src
App.css
App.js
App.test.js
AppBar.js
Grafana-Dashboard.json
Search.js
Signup.js
__mocks__
fileMock.js
assets
gray_near_logo.svg
logo.svg
near.svg
near_logo_wht.svg
config.js
index.html
index.js
jest.init.js
main.test.js
theme.js
types.ts
wallet
login
index.html
tsconfig.json
| <br />
<br />
<p>
<img src="https://nearprotocol.com/wp-content/themes/near-19/assets/img/logo.svg?t=1553011311" width="240">
</p>
<br />
<br />
## Validator Toools Dapp
### 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
```
3. (optional) yarn
```
npm i -g yarn
```
### To run on NEAR betanet
```bash
npm install && npm dev
```
with yarn:
```bash
yarn && yarn dev
```
The server that starts is for static assets and by default serves them to http://localhost:1234. Navigate there in your browser to see the app running!
NOTE: Both contract and client-side code will auto-reload once you change source files.
### To run tests
```bash
npm test
```
with yarn:
```bash
yarn test
```
### Deploy
#### Step 1: Create account for the contract
You'll now want to authorize NEAR shell on your NEAR account, which will allow NEAR Shell to deploy contracts on your NEAR account's behalf \(and spend your NEAR account balance to do so\).
Type the command `near login` which opens a webpage at NEAR Wallet. Follow the instructions there and it will create a key for you, stored in the `/neardev` directory.
#### Step 2:
Modify `src/config.js` line that sets the account name of the contract. Set it to the account id from step 1.
NOTE: When you use [create-near-app](https://github.com/nearprotocol/create-near-app) to create the project it'll infer and pre-populate name of contract based on project folder name.
```javascript
const CONTRACT_NAME = 'react-template'; /* TODO: Change this to your contract's name! */
const DEFAULT_ENV = 'development';
...
```
#### Step 3:
Check the scripts in the package.json, for frontend and backend both, run the command:
```bash
npm run deploy
```
with yarn:
```bash
yarn deploy
```
NOTE: This uses [gh-pages](https://github.com/tschaub/gh-pages) to publish resulting website on GitHub pages. It'll only work if project already has repository set up on GitHub. Feel free to modify `deploy:pages` script in `package.json` to deploy elsewhere.
### To Explore
- `assembly/main.ts` for the contract code
- `src/index.html` for the front-end HTML
- `src/index.js` for the JavaScript front-end code and how to integrate contracts
- `src/App.js` for the main React component
- `src/main.test.js` for the JavaScript integration tests of smart contract
- `src/App.test.js` for the main React component tests
|
oserk_Student-Reward | README.md
as-pect.config.js
asconfig.json
package.json
scripts
1.dev-deploy.sh
2.use-contract.sh
README.md
src
as_types.d.ts
simple
__tests__
as-pect.d.ts
index.unit.spec.ts
asconfig.json
assembly
index.ts
model.ts
singleton
__tests__
as-pect.d.ts
index.unit.spec.ts
asconfig.json
assembly
index.ts
tsconfig.json
utils.ts
| #  Student-Reward
Introductory Video Link: https://www.loom.com/share/ffb96f63e353436ba3d327bf3ef08408
Rewarding Successful Student: Start voting for students who are successful in the "Near Developer" course. Support students as they vote and help them get the computer equipment they need.
## Usage Steps of Smart Contract
- First step
```
yarn
```
- Second step: Deploy to testnet account
```
yarn build:release
near dev-deploy ./build/release/simple.wasm
export CONTRACT=dev-YOUR-ID
```
## Access Smart Contract
```
near call $CONTRACT start '{}' --accountId $CONTRACT
```
- Create Student Profile
```
near call $CONTRACT createStudent '{ "name": "Your Name", "yearOfbirth": 1997, "country": "YourCountry", "computerEquipment": "Mouse", "pocketMoney": 1, "neededVote": 5 }' --accountId $CONTRACT
```
- Get All Student Profile
```
near view $CONTRACT ListOfStudent '{}'
```
- Vote and Sending Pocket Money
```
near call $CONTRACT timeToVote '{ "id": EnterStudentID }' --accountId $CONTRACT --deposit EnterPocketMoneyAmount
```
- Get Student with Specific ID
```
near view $CONTRACT getStudentById '{ "id": EnterStudentID }'
```
- Get Transfer History
```
near view $CONTRACT transferHistory '{}'
```
- Delete Student Profile with Specific ID
```
near call $CONTRACT deleteStudent '{ "id": EnterStudentID }' --accountId $CONTRACT
```
## 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:
|
nearvndev_counter-tutorial-rs | Cargo.toml
README.md
build.sh
neardev
dev-account.env
src
lib.rs
tests
sim
main.rs
| Counter Contract Tutorial
===================
This repository include a example implementaion of Rust contract with NEAR-SDK, a contract which use basic contract, versioned and upgradeable contract
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.
Building this contract
======================
Run the following, and we'll build our rust project up via cargo. This will generate our WASM binaries into our `out/` directory. This is the smart contract we'll be deploying onto the NEAR blockchain later.
```bash
./build.sh
```
Testing this contract
=====================
We have some tests that you can run. For example, the following will run our simple tests to verify that our contract code is working.
```bash
cargo test -- --nocapture
```
The more complex simulation tests aren't run with this command, but we can find them in `tests/sim`.
Using this contract
===================
### Quickest deploy
You can build and deploy this smart contract to a development account. [Dev Accounts](https://docs.near.org/docs/concepts/account#dev-accounts) are auto-generated accounts to assist in developing and testing smart contracts. Please see the [Standard deploy](#standard-deploy) section for creating a more personalized account to deploy to.
```bash
near dev-deploy --wasmFile out/counter-tutorial.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 --accountId $ACCOUNT_NAME
```
To view the number in contract:
```bash
near view $CONTRACT_NAME get_num
```
To increment number
```bash
near call $CONTRACT_NAME increment --accountId $ACCOUNT_NAME
```
|
HaiDang309_near-hackathon | README.md
contract
Cargo.toml
src
lib.rs
fe
CHANGELOG.md
LICENSE.md
jsconfig.json
package.json
public
index.html
manifest.json
static
icons
ic_flag_de.svg
ic_flag_en.svg
ic_flag_fr.svg
ic_notification_chat.svg
ic_notification_mail.svg
ic_notification_package.svg
ic_notification_shipping.svg
shape-avatar.svg
illustrations
illustration_404.svg
logo.svg
src
App.js
_mock
account.js
blog.js
products.js
user.js
components
EmptyContent.js
Iconify.js
Image.js
Label.js
Logo.js
MenuPopover.js
Page.js
ScrollToTop.js
Scrollbar.js
SearchNotFound.js
SvgIconStyle.js
chart
BaseOptionChart.js
index.js
color-utils
ColorManyPicker.js
ColorPreview.js
index.js
hook-form
FormProvider.js
RHFCheckbox.js
RHFTextField.js
index.js
nav-section
NavItem.js
NavList.js
index.js
style.js
table
TableEmptyRows.js
TableHeadCustom.js
TableMoreMenu.js
TableNoData.js
TableSelectedActions.js
TableSkeleton.js
index.js
hooks
useResponsive.js
useTable.js
useTabs.js
index.js
layouts
LogoOnlyLayout.js
dashboard
AccountPopover.js
DashboardNavbar.js
DashboardSidebar.js
LanguagePopover.js
NavConfig.js
NotificationsPopover.js
Searchbar.js
index.js
pages
Blog.js
DashboardApp.js
Home.js
Login.js
Page404.js
Products.js
Register.js
reportWebVitals.js
routes.js
sections
@dashboard
app
AppConversionRates.js
AppCurrentSubject.js
AppCurrentVisits.js
AppNewsUpdate.js
AppOrderTimeline.js
AppTasks.js
AppTrafficBySite.js
AppWebsiteVisits.js
AppWidgetSummary.js
index.js
blog
BlogPostCard.js
BlogPostsSearch.js
BlogPostsSort.js
index.js
products
ProductCard.js
ProductCartWidget.js
ProductFilterSidebar.js
ProductList.js
ProductSort.js
index.js
user
UserListHead.js
UserMoreMenu.js
UserTableRow.js
UserTableToolbar.js
index.js
auth
AuthSocial.js
login
LoginForm.js
index.js
register
RegisterForm.js
index.js
serviceWorker.js
setupTests.js
theme
index.js
overrides
Autocomplete.js
Backdrop.js
Button.js
Card.js
CssBaseline.js
IconButton.js
Input.js
Lists.js
Paper.js
Tooltip.js
Typography.js
index.js
palette.js
shadows.js
typography.js
utils
formatNumber.js
formatTime.js
| |
near-examples_factory-rust | .github
workflows
tests.yml
Cargo.toml
README.md
rust-toolchain.toml
src
deploy.rs
lib.rs
manager.rs
tests
sandbox.rs
| # Factory Contract Example
A factory is a smart contract that stores a compiled contract on itself, and
automatizes deploying it into sub-accounts.
This particular example presents a factory of donation contracts, and enables
to:
1. Create a sub-account of the factory and deploy the stored contract on it
(create_factory_subaccount_and_deploy).
2. Change the stored contract using the update_stored_contract method.
```rust
#[payable]
pub fn create_factory_subaccount_and_deploy(
&mut self,
name: String,
beneficiary: AccountId,
public_key: Option<PublicKey>,
) -> Promise {
// Assert the sub-account is valid
let current_account = env::current_account_id().to_string();
let subaccount: AccountId = format!("{name}.{current_account}").parse().unwrap();
assert!(
env::is_valid_account_id(subaccount.as_bytes()),
"Invalid subaccount"
);
// Assert enough tokens are attached to create the account and deploy the contract
let attached = env::attached_deposit();
let code = self.code.clone().unwrap();
let contract_bytes = code.len() as u128;
let minimum_needed = NEAR_PER_STORAGE.saturating_mul(contract_bytes);
assert!(
attached >= minimum_needed,
"Attach at least {minimum_needed} yโ"
);
let init_args = near_sdk::serde_json::to_vec(&DonationInitArgs { beneficiary }).unwrap();
let mut promise = Promise::new(subaccount.clone())
.create_account()
.transfer(attached)
.deploy_contract(code)
.function_call(
"init".to_owned(),
init_args,
NO_DEPOSIT,
TGAS.saturating_mul(5),
);
// Add full access key is the user passes one
if let Some(pk) = public_key {
promise = promise.add_full_access_key(pk);
}
// Add callback
promise.then(
Self::ext(env::current_account_id()).create_factory_subaccount_and_deploy_callback(
subaccount,
env::predecessor_account_id(),
attached,
),
)
}
```
## How to Build Locally?
Install [`cargo-near`](https://github.com/near/cargo-near) and run:
```bash
cargo near build
```
## How to Test Locally?
```bash
cargo test
```
## How to Deploy?
Deployment is automated with GitHub Actions CI/CD pipeline. To deploy manually,
install [`cargo-near`](https://github.com/near/cargo-near) and run:
```bash
cargo near deploy <account-id>
```
## How to Interact?
_In this example we will be using [NEAR CLI](https://github.com/near/near-cli)
to intract with the NEAR blockchain and the smart contract_
_If you want full control over of your interactions we recommend using the
[near-cli-rs](https://near.cli.rs)._
### Deploy the Stored Contract Into a Sub-Account
`create_factory_subaccount_and_deploy` will create a sub-account of the factory
and deploy the stored contract on it.
```bash
near call <factory-account> create_factory_subaccount_and_deploy '{ "name": "sub", "beneficiary": "<account-to-be-beneficiary>"}' --deposit 1.24 --accountId <account-id> --gas 300000000000000
```
This will create the `sub.<factory-account>`, which will have a `donation`
contract deployed on it:
```bash
near view sub.<factory-account> get_beneficiary
# expected response is: <account-to-be-beneficiary>
```
### Update the Stored Contract
`update_stored_contract` enables to change the compiled contract that the
factory stores.
The method is interesting because it has no declared parameters, and yet it
takes an input: the new contract to store as a stream of bytes.
To use it, we need to transform the contract we want to store into its `base64`
representation, and pass the result as input to the method:
```bash
# Use near-cli to update stored contract
export BYTES=`cat ./src/to/new-contract/contract.wasm | base64`
near call <factory-account> update_stored_contract "$BYTES" --base64 --accountId <factory-account> --gas 30000000000000
```
> This works because the arguments of a call can be either a `JSON` object or a
> `String Buffer`
## Factories - Explanations & Limitations
Factories are an interesting concept, here we further explain some of their
implementation aspects, as well as their limitations.
<br>
### Automatically Creating Accounts
NEAR accounts can only create sub-accounts of themselves, therefore, the
`factory` can only create and deploy contracts on its own sub-accounts.
This means that the factory:
1. **Can** create `sub.factory.testnet` and deploy a contract on it.
2. **Cannot** create sub-accounts of the `predecessor`.
3. **Can** create new accounts (e.g. `account.testnet`), but **cannot** deploy
contracts on them.
It is important to remember that, while `factory.testnet` can create
`sub.factory.testnet`, it has no control over it after its creation.
### The Update Method
The `update_stored_contracts` has a very short implementation:
```rust
#[private]
pub fn update_stored_contract(&mut self) {
self.code.set(env::input());
}
```
On first sight it looks like the method takes no input parameters, but we can
see that its only line of code reads from `env::input()`. What is happening here
is that `update_stored_contract` **bypasses** the step of **deserializing the
input**.
You could implement `update_stored_contract(&mut self, new_code: Vec<u8>)`,
which takes the compiled code to store as a `Vec<u8>`, but that would trigger
the contract to:
1. Deserialize the `new_code` variable from the input.
2. Sanitize it, making sure it is correctly built.
When dealing with big streams of input data (as is the compiled `wasm` file to
be stored), this process of deserializing/checking the input ends up **consuming
the whole GAS** for the transaction.
## Useful Links
- [cargo-near](https://github.com/near/cargo-near) - NEAR smart contract
development toolkit for Rust
- [near CLI-rs](https://near.cli.rs) - Iteract with NEAR blockchain from command
line
- [NEAR Rust SDK Documentation](https://docs.near.org/sdk/rust/introduction)
- [NEAR Documentation](https://docs.near.org)
- [NEAR StackOverflow](https://stackoverflow.com/questions/tagged/nearprotocol)
- [NEAR Discord](https://near.chat)
- [NEAR Telegram Developers Community Group](https://t.me/neardev)
- NEAR DevHub: [Telegram](https://t.me/neardevhub),
[Twitter](https://twitter.com/neardevhub)
|
ketyung_tm_collections_models | Cargo.toml
LICENSE.md
readme.md
src
lib.rs
models.rs
| |
Maar-io_near-learn | README.md
asconfig.json
assembly
index.ts
connect.js
create_account.js
deploy_contract.txt
execute.js
package-lock.json
package.json
query.js
transfer.js
transfer_advanced.js
| # near-learn
https://learn.figment.io/network-documentation/near/near-pathway
|
near_email-auth | .github
ISSUE_TEMPLATE
BOUNTY.yml
README.md
control-delegator
Cargo.toml
build.sh
deploy.sh
src
lib.rs
dkim-controller
Cargo.toml
build.sh
deploy.sh
src
lib.rs
dkim
Cargo.toml
src
bytes.rs
canonicalization.rs
dns.rs
errors.rs
hash.rs
header.rs
lib.rs
parser.rs
public_key.rs
result.rs
roundtrip_test.rs
sign.rs
test
keys
2022.txt
email-relayer
Cargo.toml
src
main.rs
| # Proof-of-Concept for email-based authentication for NEAR
The goal of this repo is to show the Proof of concept of using the DKIM signatures (added by default to emails) as a way to authenticate transactions.
This would allow users to control their NEAR account via email - by setting the command that they would like to execute in the subject, and then sending the email to one of the recipients.
Email would be signed by the sender's server (in current design, we only support gmail) - and this signature can be verified by the contract.
## High level design
The setup consists of 3 sub-projects: control-delegator contract, dkim-controller contract and email-relayer server.
### control-delegator contract
This is the contract that is running on the 'users' account - to handle delegated requests coming from the dkim-controller contract.
### dkim-controller contract
This is the main contract that takes are of validating DKIM messages - and passing them to workers (and creating workers accounts).
### email-relayer server
This is the job that gets emails from the imap server - and sends them as transactions.
IMPORTANT: server doesn't actually have any special powers. It is acting more like a relayer - that takes the incoming email and executes the Near function call. If it tried to change anything in the email contents, then the signature verification in contract would have failed.
|
ikataev_spinfi | index.html
package.json
readme.md
src
near
NearAPI.ts
types.ts
utils.ts
store
near
nearSlice.ts
store.ts
vite-env.d.ts
tsconfig.json
tsconfig.node.json
vite.config.ts
| |
novilusio_play-dice | 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)
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.
[](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.
[](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
```
[](https://asciinema.org/a/409580)
### Other documentation
- See `./scripts/README.md` for documentation about the scripts
- Watch this video where Willem Wyndham walks us through refactoring a simple example of a NEAR smart contract written in AssemblyScript
https://youtu.be/QP7aveSqRPo
```
There are 2 "styles" of implementing AssemblyScript NEAR contracts:
- the contract interface can either be a collection of exported functions
- or the contract interface can be the methods of a an exported class
We call the second style "Singleton" because there is only one instance of the class which is serialized to the blockchain storage. Rust contracts written for NEAR do this by default with the contract struct.
0:00 noise (to cut)
0:10 Welcome
0:59 Create project starting with "npm init"
2:20 Customize the project for AssemblyScript development
9:25 Import the Counter example and get unit tests passing
18:30 Adapt the Counter example to a Singleton style contract
21:49 Refactoring unit tests to access the new methods
24:45 Review and summary
```
## The file system
```sh
โโโ README.md # this file
โโโ as-pect.config.js # configuration for as-pect (AssemblyScript unit testing)
โโโ asconfig.json # configuration for AssemblyScript compiler (supports multiple contracts)
โโโ package.json # NodeJS project manifest
โโโ scripts
โย ย โโโ 1.dev-deploy.sh # helper: build and deploy contracts
โย ย โโโ 2.use-contract.sh # helper: call methods on ContractPromise
โย ย โโโ 3.cleanup.sh # helper: delete build and deploy artifacts
โย ย โโโ README.md # documentation for helper scripts
โโโ src
โย ย โโโ as_types.d.ts # AssemblyScript headers for type hints
โย ย โโโ simple # Contract 1: "Simple example"
โย ย โย ย โโโ __tests__
โย ย โย ย โย ย โโโ as-pect.d.ts # as-pect unit testing headers for type hints
โย ย โย ย โย ย โโโ index.unit.spec.ts # unit tests for contract 1
โย ย โย ย โโโ asconfig.json # configuration for AssemblyScript compiler (one per contract)
โย ย โย ย โโโ assembly
โย ย โย ย โโโ index.ts # contract code for contract 1
โย ย โโโ singleton # Contract 2: "Singleton-style example"
โย ย โย ย โโโ __tests__
โย ย โย ย โย ย โโโ as-pect.d.ts # as-pect unit testing headers for type hints
โย ย โย ย โย ย โโโ index.unit.spec.ts # unit tests for contract 2
โย ย โย ย โโโ asconfig.json # configuration for AssemblyScript compiler (one per contract)
โย ย โย ย โโโ assembly
โย ย โย ย โโโ index.ts # contract code for contract 2
โย ย โโโ tsconfig.json # Typescript configuration
โย ย โโโ utils.ts # common contract utility functions
โโโ yarn.lock # project manifest version lock
```
You may clone this repo to get started OR create everything from scratch.
Please note that, in order to create the AssemblyScript and tests folder structure, you may use the command `asp --init` which will create the following folders and files:
```
./assembly/
./assembly/tests/
./assembly/tests/example.spec.ts
./assembly/tests/as-pect.d.ts
```
## Setting up your terminal
The scripts in this folder are designed to help you demonstrate the behavior of the contract(s) in this project.
It uses the following setup:
```sh
# set your terminal up to have 2 windows, A and B like this:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ โ
โ โ โ
โ A โ B โ
โ โ โ
โ โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
```
### Terminal **A**
*This window is used to compile, deploy and control the contract*
- Environment
```sh
export CONTRACT= # depends on deployment
export OWNER= # any account you control
# for example
# export CONTRACT=dev-1615190770786-2702449
# export OWNER=sherif.testnet
```
- Commands
_helper scripts_
```sh
1.dev-deploy.sh # helper: build and deploy contracts
2.use-contract.sh # helper: call methods on ContractPromise
3.cleanup.sh # helper: delete build and deploy artifacts
```
### Terminal **B**
*This window is used to render the contract account storage*
- Environment
```sh
export CONTRACT= # depends on deployment
# for example
# export CONTRACT=dev-1615190770786-2702449
```
- Commands
```sh
# monitor contract storage using near-account-utils
# https://github.com/near-examples/near-account-utils
watch -d -n 1 yarn storage $CONTRACT
```
---
## OS Support
### Linux
- The `watch` command is supported natively on Linux
- To learn more about any of these shell commands take a look at [explainshell.com](https://explainshell.com)
### MacOS
- Consider `brew info visionmedia-watch` (or `brew install watch`)
### Windows
- Consider this article: [What is the Windows analog of the Linux watch command?](https://superuser.com/questions/191063/what-is-the-windows-analog-of-the-linuo-watch-command#191068)
|
near_nearcore | chain
jsonrpc
res
chain_n_chunk_info.html
debug.html
epoch_info.html
last_blocks.html
last_blocks.js
network_info.html
network_info.js
split_store.html
sync.html
tier1_network_info.html
validator.html
debug_scripts
__init__.py
request_chain_info.py
send_validator_logs.py
tests
__init__.py
send_validator_logs_test.py
nightly
expensive.txt
nayduck.py
nightly.txt
pytest-adversarial.txt
pytest-contracts.txt
pytest-sanity.txt
pytest-spec.txt
pytest.txt
sandbox.txt
pytest
__init__.py
endtoend
__init__.py
endtoend.py
lib
__init__.py
account.py
branches.py
cluster.py
configured_logger.py
data.py
key.py
lightclient.py
messages
__init__.py
block.py
bridge.py
crypto.py
network.py
shard.py
tx.py
metrics.py
mocknet.py
mocknet_helpers.py
network.py
peer.py
populate.py
proxy.py
proxy_instances.py
resharding_lib.py
serializer.py
state_sync_lib.py
transaction.py
utils.py
requirements.txt
tests
__init__.py
adversarial
fork_sync.py
gc_rollback.py
malicious_chain.py
start_from_genesis.py
contracts
deploy_call_smart_contract.py
gibberish.py
infinite_loops.py
delete_remote_nodes.py
loadtest
loadtest.py
loadtest2.py
locust
common
base.py
congestion.py
ft.py
sharding.py
social.py
sweat.py
locustfiles
congestion.py
ft.py
social.py
sweat.py
setup.py
mocknet
__init__.py
cmd_utils.py
helpers
__init__.py
genesis_updater.py
load_test_spoon_helper.py
load_test_utils.py
neard_runner.py
requirements.txt
load_test_betanet.py
load_test_spoon.py
local_test_node.py
locust.py
mirror.py
node_handle.py
remote_node.py
run_adversenet.py
stop.py
replay
replay.py
sandbox
fast_forward.py
fast_forward_epoch_boundary.py
patch_state.py
sanity
__init__.py
backward_compatible.py
block_chunk_signature.py
block_production.py
block_sync.py
block_sync_archival.py
block_sync_flat_storage.py
catchup_flat_storage_deletions.py
concurrent_function_calls.py
db_migration.py
docker.py
epoch_switches.py
garbage_collection.py
garbage_collection1.py
garbage_collection_archival.py
garbage_collection_intense.py
gc_after_sync.py
gc_after_sync1.py
gc_sync_after_sync.py
handshake_tie_resolution.py
large_messages.py
lightclnt.py
meta_tx.py
network_drop_package.py
one_val.py
proxy_example.py
proxy_restart.py
proxy_simple.py
recompress_storage.py
repro_2916.py
resharding.py
resharding_error_handling.py
resharding_restart.py
resharding_rpc_tx.py
restart.py
rosetta.py
rpc_finality.py
rpc_hash.py
rpc_light_client_execution_outcome_proof.py
rpc_max_gas_burnt.py
rpc_state_changes.py
rpc_tx_forwarding.py
rpc_tx_status.py
rpc_tx_submission.py
simple.py
skip_epoch.py
spin_up_cluster.py
split_storage.py
staking1.py
staking2.py
staking_repro1.py
staking_repro2.py
state_parts_dump_check.py
state_sync.py
state_sync1.py
state_sync2.py
state_sync3.py
state_sync4.py
state_sync5.py
state_sync_epoch_boundary.py
state_sync_fail.py
state_sync_late.py
state_sync_massive.py
state_sync_massive_validator.py
state_sync_routed.py
state_sync_then_catchup.py
switch_node_key.py
sync_ban.py
sync_chunks_from_archival.py
transactions.py
upgradable.py
validator_switch.py
validator_switch_key.py
shardnet
__init__.py
collect_ips.py
restake.py
spec
network
peers_request.py
tools
mirror
mirror_utils.py
offline_test.py
online_test.py
prober
prober.py
prober_split.py
prober_util.py
runtime
near-vm
tests
ignores.txt
runtime-params-estimator
costs.txt
emu-cost
data_builder.py
scripts
__init__.py
check_nightly.py
check_pytests.py
fix_nightly_feature_flags.py
flaky_test_check.py
nayduck.py
nodelib.py
parallel_coverage.py
remote_diff
show_config_hash.py
show_neard_version.py
utils.py
state
mega-migrate.py
split-genesis.py
update_res.py
testlib.py
tools
debug-ui
public
index.html
| |
near_near-analytics | .github
workflows
lint.yml
CONTRIBUTING.md
README.md
aggregations
__init__.py
base_aggregations.py
db_tables
__init__.py
daily_accounts_added_per_ecosystem_entity.py
daily_active_accounts_count.py
daily_active_contracts_count.py
daily_deleted_accounts_count.py
daily_deposit_amount.py
daily_gas_used.py
daily_ingoing_transactions_per_account_count.py
daily_new_accounts_count.py
daily_new_accounts_per_ecosystem_entity_count.py
daily_new_contracts_count.py
daily_new_unique_contracts_count.py
daily_outgoing_transactions_per_account_count.py
daily_receipts_per_contract_count.py
daily_tokens_spent_on_fees.py
daily_transaction_count_by_gas_burnt_ranges.py
daily_transactions_count.py
deployed_contracts.py
near_ecosystem_entities.py
unique_contracts.py
weekly_active_accounts_count.py
periodic_aggregations.py
sql_aggregations.py
main.py
requirements.txt
| # near-analytics
Analytics Tool for NEAR Blockchain.
[NEAR Explorer](https://explorer.near.org/) uses it for [mainnet](https://explorer.near.org/stats) and [testnet](https://explorer.testnet.near.org/stats).
Keep in mind that the data (both format and the contents) could be changed at any time, the tool is under development.
<img width="918" alt="Example of data" src="https://user-images.githubusercontent.com/11246099/135101272-61fe872f-2129-455d-aee1-00d0f4570900.png">
### Install
```bash
sudo apt install python3.9-distutils libpq-dev python3.9-dev postgresql-server-dev-all
python3.9 -m pip install --upgrade pip
python3.9 -m pip install -r requirements.txt
```
### Run
```bash
python3.9 main.py -h
```
### Contribute
See [Contributing Guide](CONTRIBUTING.md) for details
### Usage examples
Apart from [NEAR Explorer](https://explorer.near.org/stats), see [nice blogpost](https://analyticali.substack.com/p/near-analytics-cheatsheet) with the tutorial and beautiful pictures based on NEAR Analytics data.
|
mattlockyer_near-cbp | .eslintrc.js
README.md
contract
Cargo.toml
build.sh
src
lib.rs
utils.rs
package.json
test
contract.test.js
test-utils.js
utils
config.js
near-utils.js
patch-config.js
| # NEAR Protocol Smart Contract Boilerplate
๐จ๐จ๐จ WARNING WIP ๐จ๐จ๐จ
It's not that bad...
## Instructions
Install rust: https://www.rust-lang.org/tools/install
`yarn && yarn test:deploy`
If no contract edits (only test changes) use `yarn test`
Review code in `/test/*` and don't bother me when it doesn't work ๐
|
kwklly_kms-COIN | README.md
package.json
src
blockchains
celo
hw
index.ts
utils.ts
keyStore.ts
ledger.ts
cosmos
keyStore.ts
ledger.ts
flow
keyStore.ts
ledger.ts
kusama
keyStore.ts
ledger.ts
mina
keyStore.ts
ledger.ts
near
keyStore.ts
ledger.ts
polkadot
keyStore.ts
ledger.ts
solana
hw
index.ts
keyStore.ts
ledger.ts
terra
keyStore.ts
ledger.ts
tezos
hw
index.ts
keyStore.ts
ledger.ts
index.ts
keyStore.ts
ledger.ts
types.ts
test
keystore.js
keystore
_getAccount.js
mina.js
near.js
ledger.js
ledger
_getAccount.js
cosmos.js
mina.js
near.js
mnemonic.sample.json
tsconfig.json
| # @dsrv/kms
dsrv key management store
## Usage
```html
<script src="node_modules/argon2-browser/lib/argon2.js"></script>
```
```javascript
import { KMS, COIN, createKeyStore } from "@dsrv/kms";
// create key store
const mnemonic = "....";
const password = "strong password";
const keyStore = await createKeyStore(mnemonic.split(" "), password);
/*
{
t: 9,
m: 262144,
s: '89aaLUkbh3E3yvBvatitUsmznTMd2p7jU1cri5D5xBnu',
j: [
'eyJlbmMiOiJBMjU2R0NNIiwiYWxnIjoiUEJFUzItSFMyNTYrQTEyOEtXIiwia2lkIjoiT1lBd0hGRW4zYmFKSWJkLXoyc09VMFhnRjVLRmtfb2ZBeWQwWmxMM0FjMCIsInAycyI6IlBqNHpCdS1aMC1laVVPcGx5emh5dXciLCJwMmMiOjgxOTJ9',
'A7jjx9G1jwylhRqmk9WLgc29_G_0Bn36buUSXC1u6zRq0jLzAEKOpg',
'9COzNxXnCc_T1Jtg',
'VD5EXQ',
'BboSFxRBdGQlNyHqG8hOxw'
]
}
*/
// get account
const kms = new KMS({
keyStore,
transport: null,
});
const account = await kms.getAccount({
type: COIN.MINA,
account: 0,
index: 0,
password
});
/*
B62qpgyAmA5yNgY4buNhTxTKYTvkqSFf442KkHzYHribCFjDmXcfHHm
*/
```
## Test keysore
1. yarn build
2. modify test/mnemonic.json
3. node test/keystore
## Test ledger nano s, nano x
1. yarn build
2. node test/ledger/mina o node test/ledger/cosmos
|
Learn-NEAR-Club_nCaptchaExample | Readme.md
example-npm
example.html
index.js
package.json
example
example.html
package-lock.json
package.json
| |
NEARworld_nearspring-hello | backend
Cargo.toml
src
lib.rs
frontend
README.md
package-lock.json
package.json
public
index.html
manifest.json
robots.txt
src
App.css
App.js
App.test.js
index.css
index.js
logo.svg
reportWebVitals.js
setupTests.js
| # Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
The page will reload when you make changes.\
You may also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you can't go back!**
If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.
You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
### Analyzing the Bundle Size
This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
### Making a Progressive Web App
This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
### Advanced Configuration
This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
### Deployment
This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
### `npm run build` fails to minify
This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
|
evigore_Tipbot | Contract
Cargo.toml
compile.js
deploy.js
src
auth_tips.rs
generic_tips.rs
internal.rs
lib.rs
migration.rs
tiptoken.rs
DiscordBot
Command.ts
Tipbot.ts
bot.ts
commands
Balance.ts
Connect.ts
Deposit.ts
Tip.ts
Tips.ts
Withdraw.ts
WithdrawTips.ts
config.json
tsconfig.json
Frontend
App.js
__mocks__
fileMock.js
assets
logo-black.svg
logo-white.svg
babel.config.js
css
app.css
global.css
index.html
index.js
js
app-settings.js
config.js
useDetectOutsideClick.js
utils.js
pages
login.html
docs
Frontend.8db0786c.css
Frontend.cd2ddd41.js
index.html
logo-black.3916bf24.svg
logo-white.c927fc35.svg
index.html
package-lock.json
package.json
| |
Matrix2045_project-beep-frontend | README.md
index.html
package-lock.json
package.json
src
assets
images
common
message-error.svg
oldCommon
message-success.svg
js
loading.js
message.js
axios
api
comment.js
community.js
drip.js
post.js
profile.js
config.js
index.js
config.js
contract
CommunityContract.js
CommunityGenesisContract.js
DripContract.js
MainContract.js
NftContract.js
TokenContract.js
main.js
router
index.js
store
index.js
utils
ceramic.js
fetch.js
init.js
localStorage.js
nearAuthProvider.js
sender.js
theme.js
tokenData.js
transaction.js
upload.js
util.js
vite.config.js
| # Vue 3 + Vite
This template should help get you started developing with Vue 3 in Vite. The template uses Vue 3 `<script setup>` SFCs, check out the [script setup docs](https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup) to learn more.
## Recommended IDE Setup
- [VSCode](https://code.visualstudio.com/) + [Volar](https://marketplace.visualstudio.com/items?itemName=johnsoncodehk.volar)
|
phamr39_reviewcompany | README.md
asconfig.json
assembly
__test__
as-pect.d.ts
main.spec.ts
as_types.d.ts
controller
company.controller.ts
index.ts
model
comment.model.ts
company.model.ts
storage
comment.storage.ts
company.storage.ts
tsconfig.json
cmds_test.txt
neardev
shared-test-staging
test.near.json
shared-test
test.near.json
package-lock.json
package.json
src
config.js
| # How to install
## Install dependencies
========================
```js
yarn install
```
## 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 `amm.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `amm.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 amm.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 || 'amm.YOUR-NAME.testnet'
Step 3: deploy!
---------------
yarn deploy or near 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
# Code structure
```js
/**
**/
```
```js
/**
**/
```
```js
/**
**/
```
```js
/**
**/
```
|
phongnguyen2012_near-defi-ui | .gitpod.yml
.postcssrc.json
README.md
jest.config.js
netlify.toml
package.json
src
assets
imgs
discord.svg
medium.svg
tele.svg
twitter.svg
global.css
index.html
locales
en_US.ts
vi_VN.ts
shim.js
utils
SpecialWallet.ts
config.ts
faucet-contract.ts
ft-contract.ts
near.ts
simple-pool.rs.ts
staking-contract.ts
token.ts
wrapnear-contract.ts
tailwind.config.js
tsconfig.json
vercel.json
| # VBI-UI
This is the front-end for VBI examples.
## Quick Start
To run this project locally:
1. Prerequisites: Make sure you've installed [Node.js] โฅ 12
2. Install dependencies: `yarn`
3. Run the local development server connected to `testnet`: `yarn start` (see `package.json` for a full list of `scripts` you can run with `yarn`)
## Architecture
This project consists of three layers:
1. `services` is where communication (via the NEAR RPC API) to smart contracts happen.
2. `state` is where the services are used and connected to react state management
3. `components` and `pages` is where the view is created
## Tests
Tests use [React Testing Library](https://testing-library.com/docs/react-testing-library/intro) and can be run with `yarn test`.
## Code Formatting
This project uses [Prettier](https://prettier.io/) to create consistently styled code.
Prettier can be installed to auto-format on save for most editors. You can also run
`yarn prettier` to check for styling errors and `yarn prettier:fix` to fix styling errors.
|
NearDeFi_polygon-bos-gateway__deprecated | .devcontainer
devcontainer.json
.eslintrc.json
README.md
next.config.js
package.json
public
next.svg
vercel.svg
src
assets
images
near_social_combo.svg
near_social_icon.svg
vs_code_icon.svg
components
lib
Spinner
index.ts
Toast
README.md
api.ts
index.ts
store.ts
styles.ts
data
bos-components.ts
links.ts
web3.ts
hooks
useBosComponents.ts
useBosLoaderInitializer.ts
useClearCurrentComponent.ts
useFlags.ts
useHashUrlBackwardsCompatibility.ts
index.d.ts
lib
selector
setup.js
wallet.js
stores
auth.ts
bos-loader.ts
current-component.ts
vm.ts
styles
globals.css
theme.css
utils
auth.js
config.ts
firebase.ts
form-validation.ts
keypom-options.ts
navigation.ts
types.ts
tsconfig.json
| # BOS Gateway for Polygon zkEVM apps
## Setup & Development
Initialize repo:
```bash
pnpm i
```
Start development version:
```bash
cp .env.example .env
pnpm dev
```
The entry component is ```PolygonZkEVM``` and it's located at
```/src/components/polygon/index.tsx```
It loads the ```mattlock.near/widget/zk-evm-lp``` BOS component. The source can be found [here](https://near.org/near/widget/ComponentDetailsPage?src=mattlock.near/widget/zk-evm-lp&tab=source).
## Deployment
This is a [Next.js](https://github.com/vercel/next.js/) app and a fork of [NEAR Discovery](https://github.com/near/near-discovery) gateway app.
For static exports just run ```next build``` and upload the build files to your hosting provider. More info [here](https://nextjs.org/docs/pages/building-your-application/deploying/static-exports).
For Vercel, Cloudflare or others that supports a Next app just connect the repo and follow the deploy steps from the dashboards.
More info on Next.js deployments [here](https://nextjs.org/docs/pages/building-your-application/deploying/static-exports).
## Running with docker
```bash
docker build -t bos-polygon-gateway .
docker run -p 3000:3000 bos-polygon-gateway
```
# 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>
```
|
pagoda-gallery-repos_Review | .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
build.yml
deploy-to-console.yml
labels.yml
lock.yml
pr-labels.yml
stale.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
.eslintrc.json
.prettierrc.json
hooks
wallet-selector.ts
next.config.js
package-lock.json
package.json
pages
api
hello.ts
postcss.config.js
public
next.svg
thirteen.svg
vercel.svg
start.sh
styles
globals.css
tailwind.config.js
tsconfig.json
integration-tests
Cargo.toml
src
tests.rs
package-lock.json
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 />
[](https://github.com/near/boilerplate-template-rs/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22)
[](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)
- [Deploy on Vercel](#deploy-on-vercel)
- [Roadmap](#roadmap)
- [Support](#support)
- [Project assistance](#project-assistance)
- [Contributing](#contributing)
- [Authors & contributors](#authors--contributors)
- [Security](#security)
</details>
---
## About
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) created for easy-to-start as a React + Rust skeleton template in the Pagoda Gallery. Smart-contract was initialized with [create-near-app]. Use this template and start to build your own gallery project!
### Built With
[`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app), [`tailwindcss`](https://tailwindcss.com/docs/guides/nextjs), [`tailwindui`](https://tailwindui.com/), [`@headlessui/react`](https://headlessui.com/), [`@heroicons/react`](https://heroicons.com/), [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 `18>`.
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
=====
Start your frontend:
npm run start
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
Test your contract:
npm run test
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. You can start editing the page by
modifying `frontend/pages/index.tsx`. The page auto-updates as you edit the file.
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.
4. [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 `frontend/pages/api/hello.ts`.
5. The `frontend/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.
6. This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font.
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 `contract/neardev/dev-account.env` that sets the account name of the contract. Set it to the account id you used above.
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-next-app]: https://github.com/vercel/next.js/tree/canary/packages/create-next-app
[Node.js]: https://nodejs.org/en/download/package-manager
[tailwindcss]: https://tailwindcss.com/docs/guides/nextjs
[create-near-app]: https://github.com/near/create-near-app
[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
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.
## 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>`.
|
mohammadreza-ashouri_NEAR-Protocol-Airdrop-Contract | README.md
src
lib.rs
| # NEAR-Protocol-Airdrop-Contract
This is an Airdop contract written in Rust for the NEAR protocol
1) Install Rustup by running:
```
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
```
2) Configure your current shell by running:
```
source $HOME/.cargo/env
```
3) Add wasm target to your toolchain by running:
```
rustup target add wasm32-unknown-unknown
```
Next, make sure you have near-cli by running:
```
near --version
```
If you need to install near-cli:
```
npm install near-cli -g
```
|
open-web-academy_nft-subscriptions-ui | README.md
package.json
public
index.html
manifest.json
robots.txt
src
App.js
App.test.js
Logo.js
assets
logo-black.svg
logo-white.svg
components
Footer.js
Header.js
sections
Hero.js
config.js
index.js
logo.svg
reportWebVitals.js
serviceWorker.js
setupTests.js
test-utils.js
utils.js
utils
ColorModeSwitcher.js
common.js
near.js
near_interaction.js
sentry.js
views
BuySubscriptions.js
MySubscriptions.js
| # PROYECTO PARA LAS SUSCRIPCIONES DE OPEN WEB ACADEMY
Versiรณn de Node: 12.22.5
Para correr el siguiente proyecto de manera local deberรก ejecutar los siguientes comandos:
Para instalar las dependencias del proyecyo, deberรก ejecutar el siguiente comando:
### `npm install`
Despues ejecute el siguiente comando para correr el proyecto:
### `npm start`
|
nearuaguild_near-server-side | CONTRIBUTING.md
LICENSE.txt
Readme.md
config
index.ts
verify.ts
contracts
fungible_token.ts
index.ts
middlewares
check_validation_result.ts
package.json
tsconfig.json
utils
index.ts
| |
nearprotocol_assemblyscript | .eslintrc.js
.github
FUNDING.yml
ISSUE_TEMPLATE.md
PULL_REQUEST_TEMPLATE.md
workflows
publish.yml
stale.yml
test.yml
CODE_OF_CONDUCT.md
CONTRIBUTING.md
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
index.d.ts
index.js
index.release.d.ts
index.release.js
lib
loader
README.md
index.d.ts
index.js
package.json
tests
assembly
index.ts
tsconfig.json
index.html
index.js
umd
index.js
package.json
umd
index.d.ts
index.js
package.json
parse
README.md
assembly
index.ts
options.ts
tsconfig.json
index.d.ts
index.js
package.json
src
common.ts
index.ts
tsconfig.json
tests
index.ts
webpack.config.js
rtrace
README.md
bin
rtplot.js
index.d.ts
index.js
package.json
plot.js
tests
index.js
tlsfvis.html
umd
index.d.ts
index.js
package.json
sdk
README.md
index.js
tests
index.html
webpack
README.md
decode.js
index.js
package.json
media
architecture.svg
architecture.xml
package-lock.json
package.json
scripts
build-diagnostics.js
build-dts.js
build-sdk.js
build.js
clean.js
hexfloat.html
hexfloat.js
postpublish-files.json
postpublish.js
prepublish.js
update-constants.js
snap
README.md
src
README.md
asconfig.json
ast.ts
builtins.ts
common.ts
compiler.ts
definitions.ts
diagnosticMessages.generated.ts
diagnosticMessages.json
diagnostics.ts
extra
README.md
ast.ts
tsconfig.json
flow.ts
glue
README.md
binaryen.d.ts
binaryen.js
js
collections.d.ts
collections.js
float.d.ts
float.js
i64.d.ts
i64.js
index.ts
node.d.ts
tsconfig.json
wasm
collections.ts
float.ts
i64.ts
index.ts
tsconfig.json
index.ts
module.ts
parser.ts
passes
findusedlocals.ts
ministack.ts
pass.ts
rtrace.ts
shadowstack.ts
program.ts
resolver.ts
tokenizer.ts
tsconfig.json
types.ts
util
binary.ts
collections.ts
index.ts
math.ts
path.ts
terminal.ts
text.ts
vector.ts
PassRunner::addDefaultGlobalOptimizationPrePasses
PassRunner::addDefaultFunctionOptimizationPasses
PassRunner::addDefaultGlobalOptimizationPostPasses
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
tests
README.md
allocators
default
assembly
index.ts
tsconfig.json
package.json
forever.js
index.js
package.json
runner.js
stub
assembly
index.ts
tsconfig.json
package.json
asconfig
complicated
asconfig.json
assembly
index.ts
package.json
cyclical
asconfig.json
assembly
index.ts
extends.json
package.json
entry-points
asconfig.json
assembly
data.ts
globalTwo.ts
globals.ts
index.ts
nested
asconfig.json
assembly
index.ts
package.json
node-resolution
asconfig.json
assembly
index.ts
node_modules
entry-points
asconfig.json
package.json
package.json
extends
asconfig.json
assembly
index.ts
expected.json
extends.json
package.json
index.js
package.json
respect-inheritence
asconfig.json
assembly
index.ts
package.json
target
asconfig.json
assembly
index.ts
expected.json
package.json
use-consts
asconfig.json
assembly
index.ts
package.json
binaryen
asmjs-math-builtins.js
block-pre.js
block-stack.js
break-value.js
const-expr.js
const-global.js
const-local.js
constant-indirect-arg.js
constant-indirect.js
get_global-missing.js
get_local-missing.js
i64-binary-result.js
inline-export.js
libm.html
multi-value.js
optimize-if-eqz.js
reloop.js
return-flatten.js
set_global-immutable.js
unreachable-loop.js
unreachable-spam.js
browser-asc.js
cli
options.js
compiler.js
compiler
NonNullable.ts
ReturnType.json
ReturnType.ts
abi.json
abi.ts
asc-constants.json
asc-constants.ts
assert-nonnull.json
assert-nonnull.ts
assert.json
assert.ts
basic-nullable.json
basic-nullable.ts
binary.json
binary.ts
bool.json
bool.ts
builtins.json
builtins.ts
call-inferred.json
call-inferred.ts
call-optional.json
call-optional.ts
call-super.json
call-super.ts
cast.json
cast.ts
class-abstract-errors.json
class-abstract-errors.ts
class-extends.json
class-extends.ts
class-implements.json
class-implements.ts
class-overloading-cast.json
class-overloading-cast.ts
class-overloading.json
class-overloading.ts
class-static-function.json
class-static-function.ts
class.json
class.ts
closure.json
closure.ts
comma.json
comma.ts
const-folding.json
const-folding.ts
constant-assign.json
constant-assign.ts
constructor-errors.json
constructor-errors.ts
constructor.json
constructor.ts
continue.json
continue.ts
converge.json
converge.ts
declare.js
declare.json
declare.ts
do.json
do.ts
duplicate-identifier.json
duplicate-identifier.ts
empty-exportruntime.json
empty-exportruntime.ts
empty-new.json
empty-new.ts
empty-use.json
empty-use.ts
empty.json
empty.ts
enum.json
enum.ts
export-default.json
export-default.ts
export-generic.json
export-generic.ts
export.json
export.ts
exportimport-table.js
exportimport-table.json
exportimport-table.ts
exports-lazy.json
exports-lazy.ts
exports.json
exports.ts
exportstar-rereexport.json
exportstar-rereexport.ts
exportstar.json
exportstar.ts
extends-baseaggregate.json
extends-baseaggregate.ts
extends-recursive.json
extends-recursive.ts
extends-self.json
extends-self.ts
external.js
external.json
external.ts
features
README.md
gc.json
gc.ts
js-bigint-integration.js
js-bigint-integration.json
js-bigint-integration.ts
mutable-globals.js
mutable-globals.json
mutable-globals.ts
nontrapping-f2i.json
nontrapping-f2i.ts
not-supported.json
not-supported.ts
reference-types.js
reference-types.json
reference-types.ts
simd.json
simd.ts
threads.json
threads.ts
field-initialization-errors.json
field-initialization-errors.ts
field-initialization-warnings.json
field-initialization-warnings.ts
field-initialization.json
field-initialization.ts
for.json
for.ts
function-call.json
function-call.ts
function-expression.json
function-expression.ts
function-types.json
function-types.ts
function.json
function.ts
getter-call.json
getter-call.ts
getter-setter.json
getter-setter.ts
heap.json
heap.ts
if.json
if.ts
implicit-getter-setter.js
implicit-getter-setter.json
implicit-getter-setter.ts
import.json
import.ts
indexof-valueof.json
indexof-valueof.ts
infer-array.json
infer-array.ts
infer-generic.json
infer-generic.ts
infer-type.json
infer-type.ts
inlining-blocklocals.json
inlining-blocklocals.ts
inlining-recursive.json
inlining-recursive.ts
inlining.json
inlining.ts
instanceof-class.json
instanceof-class.ts
instanceof.json
instanceof.ts
issues
1095.json
1095.ts
1225.json
1225.ts
1699.ts
1714.ts
1751.ts
1751
_common.ts
_foo.ts
_reexport.ts
limits.json
limits.ts
literals.json
literals.ts
logical.json
logical.ts
loop-flow.json
loop-flow.ts
loop-wrap.json
loop-wrap.ts
managed-cast.json
managed-cast.ts
many-locals.json
many-locals.ts
memcpy.json
memcpy.ts
memmove.json
memmove.ts
memory-config-errors.json
memory-config-errors.ts
memory-config-shared-errors.json
memory-config-shared-errors.ts
memory.json
memory.ts
memorybase.json
memorybase.ts
memset.json
memset.ts
merge.json
merge.ts
named-export-default.json
named-export-default.ts
named-import-default.json
named-import-default.ts
namespace.json
namespace.ts
new.json
new.ts
nonnullable.json
nullable.json
nullable.ts
number.json
number.ts
object-literal.json
object-literal.ts
optional-typeparameters.json
optional-typeparameters.ts
overflow.json
overflow.ts
portable-conversions.json
portable-conversions.ts
possibly-null.json
possibly-null.ts
recursive.json
recursive.ts
reexport.json
reexport.ts
rereexport.json
rereexport.ts
resolve-access.json
resolve-access.ts
resolve-binary.json
resolve-binary.ts
resolve-elementaccess.json
resolve-elementaccess.ts
resolve-function-expression.json
resolve-function-expression.ts
resolve-nested.json
resolve-nested.ts
resolve-new.json
resolve-new.ts
resolve-propertyaccess.json
resolve-propertyaccess.ts
resolve-ternary.ts
resolve-unary.json
resolve-unary.ts
retain-i32.json
retain-i32.ts
rt
finalize.json
finalize.ts
flags.json
flags.ts
ids.json
ids.ts
instanceof.json
instanceof.ts
runtime-incremental-export.json
runtime-incremental-export.ts
runtime-incremental.json
runtime-incremental.ts
runtime-minimal-export.json
runtime-minimal-export.ts
runtime-minimal.json
runtime-minimal.ts
runtime-stub-export.json
runtime-stub-export.ts
runtime-stub.json
runtime-stub.ts
scoped.json
scoped.ts
static-this.json
static-this.ts
std-wasi
console.json
console.ts
crypto.json
crypto.ts
process.json
process.ts
std
array-access.json
array-access.ts
array-literal.json
array-literal.ts
array.json
array.ts
arraybuffer.json
arraybuffer.ts
dataview.json
dataview.ts
date.json
date.ts
hash.json
hash.ts
map.json
map.ts
math.js
math.json
math.ts
mod.js
mod.json
mod.ts
new.json
new.ts
object.json
object.ts
operator-overloading.json
operator-overloading.ts
pointer.json
pointer.ts
polyfills.json
polyfills.ts
set.json
set.ts
simd.json
simd.ts
static-array.json
static-array.ts
staticarray.json
staticarray.ts
string-casemapping.js
string-casemapping.json
string-casemapping.ts
string-encoding.json
string-encoding.ts
string.json
string.ts
symbol.json
symbol.ts
trace.json
trace.ts
typedarray.json
typedarray.ts
uri.json
uri.ts
super-inline.json
super-inline.ts
switch.json
switch.ts
tablebase.json
tablebase.ts
templateliteral.json
templateliteral.ts
ternary.json
ternary.ts
throw.json
throw.ts
tsconfig.json
typealias.json
typealias.ts
typeof.json
typeof.ts
unary.json
unary.ts
unify-local-flags.json
unify-local-flags.ts
unknown-bool-ident.json
unknown-bool-ident.ts
unsafe.json
unsafe.ts
variable-access-in-initializer.json
variable-access-in-initializer.ts
void.json
void.ts
wasi
abort.js
abort.json
abort.ts
seed.js
seed.json
seed.ts
snapshot_preview1.json
snapshot_preview1.ts
trace.js
trace.json
trace.ts
while.json
while.ts
decompiler.js
extension
package.json
features.json
packages
package.json
packages
a
assembly
a.ts
index.ts
as
as
as.ts
index.ts
package.json
b
assembly
b.ts
index.ts
node_modules
a
assembly
a.ts
index.ts
c
assembly
c.ts
index.ts
node_modules
b
assembly
b.ts
index.ts
node_modules
a
assembly
a.ts
index.ts
d
assembly
d.ts
index.ts
node_modules
as
notassembly
as.ts
index.ts
package.json
c
assembly
c.ts
index.ts
node_modules
b
assembly
b.ts
index.ts
node_modules
a
assembly
a.ts
index.ts
packages
e
assembly
e.ts
index.ts
packages
f
assembly
f.ts
index.ts
g
assembly
g.ts
index.ts
node_modules
c
assembly
c.ts
index.ts
node_modules
b
assembly
b.ts
index.ts
node_modules
a
assembly
a.ts
index.ts
test.js
h
assembly
index.ts
node_modules
@foo
bar
assembly
index.ts
node_modules
@bar
baz
assembly
index.ts
tsconfig.json
parser.js
parser
also-identifier.ts
also-identifier.ts.fixture.ts
arrow-functions.ts
arrow-functions.ts.fixture.ts
call-function-return.ts
call-function-return.ts.fixture.ts
calls.ts
calls.ts.fixture.ts
class-abstract.ts
class-abstract.ts.fixture.ts
class-expression.ts
class-expression.ts.fixture.ts
class.ts
class.ts.fixture.ts
constructor.ts
constructor.ts.fixture.ts
continue-on-error.ts
continue-on-error.ts.fixture.ts
decorators.ts
decorators.ts.fixture.ts
definite-assignment-assertion.ts
definite-assignment-assertion.ts.fixture.ts
do.ts
do.ts.fixture.ts
empty.ts
empty.ts.fixture.ts
enum.ts
enum.ts.fixture.ts
export-default.ts
export-default.ts.fixture.ts
for.ts
for.ts.fixture.ts
forof.ts
forof.ts.fixture.ts
function-expression.ts
function-expression.ts.fixture.ts
function-type.ts
function-type.ts.fixture.ts
function.ts
function.ts.fixture.ts
import.ts
import.ts.fixture.ts
index-declaration.ts
index-declaration.ts.fixture.ts
interface-errors.ts
interface-errors.ts.fixture.ts
interface.ts
interface.ts.fixture.ts
literals.ts
literals.ts.fixture.ts
namespace.ts
namespace.ts.fixture.ts
nonNullAssertion.ts
nonNullAssertion.ts.fixture.ts
numeric-separators.ts
numeric-separators.ts.fixture.ts
object-literal.ts
object-literal.ts.fixture.ts
optional-property.ts
optional-property.ts.fixture.ts
optional-typeparameters.ts
optional-typeparameters.ts.fixture.ts
parameter-optional.ts
parameter-optional.ts.fixture.ts
parameter-order.ts
parameter-order.ts.fixture.ts
propertyelementaccess.ts
propertyelementaccess.ts.fixture.ts
regexp.ts
regexp.ts.fixture.ts
reserved-keywords.ts
reserved-keywords.ts.fixture.ts
string-binding.ts
string-binding.ts.fixture.ts
trailing-commas.ts
trailing-commas.ts.fixture.ts
tsconfig.json
type-signature.ts
type-signature.ts.fixture.ts
type.ts
type.ts.fixture.ts
var.ts
var.ts.fixture.ts
while.ts
while.ts.fixture.ts
require
index-release.ts
index.ts
resolve-ternary.json
tokenizer.js
util-path.js
util
diff.js
tsconfig-base.json
tsconfig-docs.json
webpack.config.js
| # assemblyscript-bson
BSON encoder / decoder for AssemblyScript somewhat based on https://github.com/mpaland/bsonfy.
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:
- Only limited data types are supported:
- arrays
- objects
- 32-bit integers
- strings
- booleans
- null
- `Uint8Array`
- 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 BSON
```ts
// Make sure memory allocator is available
import "allocator/arena";
// Import encoder
import { BSONEncoder } from "path/to/module";
// Create encoder
let encoder = new BSONEncoder();
// Construct necessary object
encoder.pushObject("obj");
encoder.setInteger("int", 10);
encoder.setString("str", "");
encoder.popObject();
// Get serialized data
let bson: Uint8Array = encoder.serialize();
```
## Parsing BSON
```ts
// Make sure memory allocator is available
import "allocator/arena";
// Import decoder
import { BSONDecoder, BSONHandler } from "path/to/module";
// Events need to be received by custom object extending BSONHandler.
// NOTE: All methods are optional to implement.
class MyBSONEventsHandler extends BSONHandler {
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
}
setUint8Array(name: string, value: Uint8Array): void {
// Handle field
}
pushArray(name: string): bool {
// Handle array start
return true; // true means that nested object needs to be traversed, false otherwise
}
popArray(): void {
// Handle array end
}
pushObject(name: string): bool {
// Handle object start
return true; // true means that nested object needs to be traversed, false otherwise
}
popObject(): void {
// Handle object end
}
}
// Create decoder
let decoder = new BSONDecoder<MyBSONEventsHandler>(new MyBSONEventsHandler());
// Let's assume BSON data is available in this variable
let bson: Uint8Array = ...;
// Parse BSON
decoder.deserialize(bson); // This will send events to MyBSONEventsHandler
```
<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> ยท
<a href="https://assemblyscript.org/introduction.html">Introduction</a> ยท
<a href="https://assemblyscript.org/quick-start.html">Quick start</a> ยท
<a href="https://assemblyscript.org/examples.html">Examples</a> ยท
<a href="https://assemblyscript.org/development.html">Development 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>
# WebAssembly Parser
A WebAssembly binary parser in WebAssembly. Super small, super fast, with TypeScript support.
API
---
* **parse**(binary: `Uint8Array`, options?: `ParseOptions`): `void`<br />
Parses the contents of a WebAssembly binary according to the specified options.
* **ParseOptions**<br />
Options specified to the parser. The `onSection` callback determines the sections being evaluated in detail.
* **onSection**?(id: `SectionId`, payloadOff: `number`, payloadLen: `number`, nameOff: `number`, nameLen: `number`): `boolean`<br />
Called with each section in the binary. Returning `true` evaluates the section.
* **onType**?(index: `number`, form: `number`): `void`<br />
Called with each function type if the type section is evaluated.
* **onTypeParam**?(index: `number`, paramIndex: `number`, paramType: `Type`): `void`<br />
Called with each function parameter if the type section is evaluated.
* **onTypeReturn**?(index: `number`, returnIndex: `number`, returnType: `Type`): `void`<br />
Called with each function return type if the type section is evaluated.
* **onImport**?(index: `number`, kind: `ExternalKind`, moduleOff: `number`, moduleLen: `number`, fieldOff: `number`, fieldLen: `number`): `void`<br />
Called with each import if the import section is evaluated.
* **onFunctionImport**?(index: `number`, type: `number`): `void`<br />
Called with each function import if the import section is evaluated.
* **onTableImport**?(index: `number`, type: `Type`, initial: `number`, maximum: `number`, flags: `number`): `void`<br />
Called with each table import if the import section is evaluated.
* **onMemoryImport**?(index: `number`, initial: `number`, maximum: `number`, flags: `number`): `void`<br />
Called with each memory import if the import section is evaluated.
* **onGlobalImport**?(index: `number`, type: `Type`, mutability: `number`): `void`<br />
Called with each global import if the import section is evaluated.
* **onMemory**?(index: `number`, initial: `number`, maximum: `number`, flags: `number`): `void`<br />
Called with each memory if the memory section is evaluated.
* **onFunction**?(index: `number`, typeIndex: `number`): `void`<br />
Called with each function if the function section is evaluated.
* **onGlobal**?(index: `number`, type: `Type`, mutability: `number`): `void`<br />
Called with each global if the global section is evaluated.
* **onStart**?(index: `number`): `void`<br />
Called with the start function index if the start section is evaluated.
* **onExport**?(index: `number`, kind: `ExternalKind`, kindIndex: `number`, nameOff: `number`, nameLen: `number`): `void`<br />
Called with each export if the export section is evaluated.
* **onSourceMappingURL**?(offset: `number`, length: `number`): `void`<br />
Called with the source map URL if the 'sourceMappingURL' section is evaluated.
* **onModuleName**?(offset: `number`, length: `number`): `void`<br />
Called with the module name if present and the 'name' section is evaluated.
* **onFunctionName**?(index: `number`, offset: `number`, length: `number`): `void`<br />
Called with each function name if present and the 'name' section is evaluated.
* **onLocalName**?(funcIndex: `number`, index: `number`, offset: `number`, length: `number`): `void`<br />
Called with each local name if present and the 'name' section is evaluated.
* **Type**<br />
A value or element type, depending on context.
| Name | Value
|---------|-------
| i32 | 0x7f
| i64 | 0x7e
| f32 | 0x7d
| f64 | 0x7c
| anyfunc | 0x70
| func | 0x60
| none | 0x40
* **SectionId**<br />
Numerical id of the current section.
| Name | Value
|----------|-------
| Custom | 0
| Type | 1
| Import | 2
| Function | 3
| Table | 4
| Memory | 5
| Global | 6
| Export | 7
| Start | 8
| Element | 9
| Code | 10
| Data | 11
* **ExternalKind**<br />
Kind of an export or import.
| Name | Value
|----------|-------
| Function | 0
| Table | 1
| Memory | 2
| Global | 3
Test cases for post-MVP WebAssembly features.
# Webpack loader
An experimental [webpack](https://webpack.js.org/) loader for [AssemblyScript](http://assemblyscript.org) modules.
Usage
-----
```js
import MyModule from "@assemblyscript/webpack!mymodule.wasm";
var myModule = new MyModule({ imports: { /* if any */ } });
```
TODO: Pipe .ts files through `asc`, accepting the usual options, but also keep raw .wasm support.
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 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)
Extra components that are not ultimately required in a standalone compiler.
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`.
Snaps are containerised software packages that are simple to create and install on all major Linux systems without modification. [Learn more](https://docs.snapcraft.io/).
[](https://snapcraft.io/assemblyscript)
Compiler
========
Portable compiler sources that compile to both JavaScript using `tsc` and WebAssembly using `asc`.
Architecture
------------

Usage
-----
Note that using the compiler as a library requires awaiting Binaryen ready state, like so:
```js
const binaryen = require("binaryen");
const assemblyscript = require("assemblyscript");
binaryen.ready.then(() => {
// do something with assemblyscript
});
```
Building
--------
Note that building the compiler is not necessary if you only want to run it (in development). If not built, `ts-node` is used to run the sources directly.
### Building to JavaScript
To build the compiler to a JavaScript bundle, run:
```sh
npm run build
```
Uses webpack under the hood, building to `dist/`.
### Building to WebAssembly
To build the compiler to a WebAssembly binary, run:
```sh
npm run bootstrap
```
Uses the AssemblyScript compiler compiled to JavaScript to compile itself to WebAssembly, building to WebAssembly again using itself compiled to WebAssembly. Builds to `out/`. Performs a `git diff` to make sure that both the initial and the final artifacts are the same. Note that this builds the compiler as a library, while the `asc` frontend setting it up and feeding it source files is JavaScript for now.
Running `asc` with the WebAssembly variant:
```ts
asc [options...] --wasm out/assemblyscript.optimized-bootstrap.wasm
```
Running the compiler tests with the WebAssembly variant:
```ts
npm run test:compiler -- --wasm out/assemblyscript.optimized-bootstrap.wasm
```
Shims used when bundling asc for browser usage.
# assemblyscript-rlp
Assemblyscript implmementation of [RLP](https://github.com/ethereum/wiki/wiki/RLP) base on the [typescript implementation](https://github.com/ethereumjs/rlp). Mostly work in progress.
## Development
To build the project, run
```bash
npm install && npm run asbuild
```
To test, run
```bash
npm run test
```
Tests are written using [as-pect](https://github.com/jtenner/as-pect).
# Browser SDK
An SDK to use the AssemblyScript compiler on the web. This is built to distribution files using the exact versions of the compiler and its dependencies.
Expects [require.js](https://requirejs.org) (or compatible) on the web, primarily targeting [WebAssembly Studio](https://webassembly.studio). Note that consuming the source file in this directory directly does not solve any versioning issues - use `dist/sdk.js` instead. Do not try to bundle this.
Exports
-------
* **binaryen**<br />
The version of binaryen required by the compiler.
* **long**<br />
The version of long.js required by the compiler.
* **assemblyscript**<br />
The AssemblyScript compiler as a library.
* **asc**<br />
AssemblyScript compiler frontend that one will interact with
([see](https://github.com/AssemblyScript/assemblyscript/tree/main/cli)).
Example usage
-------------
```js
require(
["https://cdn.jsdelivr.net/npm/assemblyscript@latest/dist/sdk"],
function(sdk) {
const { asc } = sdk;
asc.ready.then(() => {
asc.main(...);
});
}
);
```
There is also the [SDK example](https://github.com/AssemblyScript/examples/tree/main/sdk) showing how to compile some actual code.
Environment specific glue code.
Tests
=====
This directory contains the test cases for AssemblyScript's parser and compiler. A test case
consists of:
* A test file that is parsed or compiled (.ts)
* One or multiple automatically generated fixtures generated from the source file
### Creating a test:
* Run `npm run clean` to make sure that the sources are tested instead of the distribution
* Create a new test file (.ts) within the respective directory (see below) that contains your test code
* Follow the instructions below to generate the first fixture(s)
* Make sure the fixture(s) contain exactly what you'd expect
### Updating a test:
* Run `npm run clean` to make sure that the sources are tested instead of the distribution
* Make changes to the respective test file (.ts)
* Follow the instructions below to update the fixture(s)
* Make sure the fixture(s) contain exactly what you'd expect
See also: [Contribution guidelines](../CONTRIBUTING.md)
Parser
------
Directory: [tests/parser](./parser)
The test file is parsed while warnings and errors are recorded and re-serialized to a new source
afterwards. The new source with warnings and errors appended as comments is compared to the fixture.
Running all tests:
```
$> npm run test:parser
```
Running a specific test only:
```
$> npm run test:parser -- testNameWithoutTs
```
To (re-)create all fixtures:
```
$>npm run test:parser -- --create
```
To (re-)create a specific fixture only:
```
$> npm run test:parser -- testNameWithoutTs --create
```
Compiler
--------
General directory: [tests/compiler](./compiler)<br />
Standard library directory: [tests/compiler/std](./compiler/std)
The source file is parsed and compiled to a module, validated and the resulting module converted to
WebAsssembly text format.
The text format output is compared to its fixture and the module interpreted in a WebAssembly VM. To
assert for runtime conditions, the `assert` builtin can be used. Note that tree-shaking is enabled
and it might be necessary to export entry points.
Additional fixtures for the optimized module etc. are generated as well but are used for visual
confirmation only.
If present, error checks are performed by expecting the exact sequence of substrings provided within
the respective `.json` file. Using the `stderr` config option will skip instantiating and running
the module.
Optionally, a `.js` file of the same name as the test file can be added containing code to run pre
and post instantiation of the module, with the following export signatures:
* **preInstantiate**(imports: `object`, exports: `object`): `void`<br />
Can be used to populate imports with functionality required by the test. Note that `exports` is an
empty object that will be populated with the actual exports after instantiation. Useful if an import
needs to call an export (usually in combination with the `--explicitStart` flag).
* **postInstantiate**(instance: `WebAssembly.Instance`): `void`<br />
Can be used to execute custom test logic once the module is ready. Throwing an error will fail the
instantiation test.
Running all tests:
```
$> npm run test:compiler
```
Running a specific test only:
```
$> npm run test:compiler -- testNameWithoutTs
```
To (re-)create all fixtures:
```
$> npm run test:compiler -- --create
```
To (re-)create a specific fixture only:
```
$> npm run test:compiler -- testNameWithoutTs --create
```
Features
--------
Tests for experimental features (usually enabled via the `--enable` CLI flag) are disabled by default. To enable a feature, set the `ASC_FEATURES` environment variable to a comma-separated list of feature names (see [`features.json`](./features.json)). You can also set `ASC_FEATURES="*"` to enable all features.
Other
-----
Tests in other directories are not run automatically and do not need to be updated.
* [tests/allocators](./allocators) contains the memory allocator test suite
* [tests/binaryen](./binaryen) contains various triggers for earlier Binaryen issues
* [tests/tokenizer](./tokenizer.js) is a visual test for the tokenizer tokenizing itself
* [tests/util-path](./util-path.js) is a sanity test for the path utility
# 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.
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 });
});
...
```
|
keypom_keypom-airfoil | .eslintrc.js
.github
ISSUE_TEMPLATE
1-feature_request_template.md
2-issue_template.md
pull_request_template.md
workflows
main.yml
.vscode
extensions.json
settings.json
CONTRIBUTING.md
README.md
package.json
public
README.md
src
components
AppModal
index.ts
AvatarImage
index.ts
BoxWithShape
index.ts
Breadcrumbs
index.ts
Checkboxes
index.ts
ConnectWalletButton
ConnectWalletModal
index.ts
index.ts
CoreLayout
index.ts
DropBox
index.ts
ErrorBox
index.ts
Footer
index.ts
FormControl
index.ts
GradientSpan
index.ts
IconBox
index.ts
Icons
index.ts
ImageFileInput
index.ts
KeypomLogo
index.ts
Loading
index.ts
Menu
index.ts
Navbar
index.ts
NotFound404
index.ts
Pagination
index.ts
PopoverTemplate
index.ts
ProtectedRoutes
index.ts
RoundedTabs
index.ts
SignedInButton
index.ts
Step
index.ts
SwitchInput
index.ts
Table
constants.ts
index.ts
types.ts
TextAreaInput
index.ts
TextInput
index.ts
TokenIcon
index.ts
TokenInputMenu
index.ts
ViewFinder
index.ts
WalletIcon
index.ts
WalletSelectorModal
WalletSelectorModal.css
config
config.ts
constants
common.ts
toast.ts
features
create-drop
components
DropSummary
index.ts
nft
index.ts
ticket
index.ts
token
index.ts
contexts
CreateTicketDropContext
FormValidations.ts
index.ts
index.ts
nft-utils.ts
routes
index.ts
types
types.ts
drop-manager
constants
common.ts
types
types.ts
utils
getClaimStatus.ts
index.html
lib
keypom.ts
walletSelector.ts
theme
colors.ts
components
BadgeTheme.ts
ButtonTheme.ts
CheckboxTheme.ts
HeadingTheme.ts
InputTheme.ts
MenuTheme.ts
ModalTheme
index.ts
TableTheme.ts
TextTheme.ts
index.ts
config.ts
fontSizes.ts
fonts.ts
index.ts
sizes.ts
theme.ts
types
common.ts
utils
claimedDrops.ts
file.ts
formatAmount.ts
localStorage.ts
replaceSpace.ts
share.ts
truncateAddress.ts
tsconfig.json
tslint.json
| # Keypom App ๐





This is a React application which comes with a suite of use cases to create drops with UI that interacts with Keypom SDK and NEAR protocol.
The project is hosted on Cloudflare - https://keypom.xyz/.
### Tools Required
All tools required go here. You would require the following tools to develop and run the project:
- A text editor or an IDE (like VSCode)
- Node.js => `v16.0.0`
- Yarn => `v1.22.10`
### Running the App
All installation steps go here.
- Clone the repository
```bash
git clone https://github.com/keypom/keypom-airfoil
```
- Install dependencies
```bash
yarn install
```
- Run the app
```bash
yarn dev
```
- Build the app
```bash
yarn build
```
## Project Structure
The project structure is inspired by [Bulletproof React](https://github.com/alan2207/bulletproof-react/blob/master/docs/project-structure.md).
## Deployment
This app is deployed on Cloudflare Pages. Preview site is deployed when a feature branch has been commited to origin.
`pr-main` is the current production/mainnet branch.
`testnet` is the current staging/testnet branch.
This is the public directory of your application. You can place your static assets here.
|
onmachina_onmachina-ui-demo | README.md
index.html
lib
nearsetup.js
utils.js
mock-data
get-container.json
netlify.toml
package-lock.json
package.json
src
assets
empty-container.svg
file-icon.svg
react.svg
hooks
useEscape.js
useOnClickOutside.js
index.css
vite.config.js
| # OnMachina Demo Interface
This is a simple react demo application of a web client built with OnMachina Decentralized Storage Network protocols, authenticating through Near Protocol testnet.
# Pre-requisites
- You will need a Near Protocol testnet account. You can create one at https://testnet.mynearwallet.com/
- Depending on when you test, your testnet account may need to be allowed into the private beta. Contact the OnMachina Association team directly to request this
- To run locally, you will also need npm working
- You may also be able to visit https://demo.onmachina.io
**Note:** this URL is not currently managed as a production-level resource so may not be available at all times
# Local install instructions
1. Clone the demo repo
git clone [email protected]:onmachina/onmachina-ui-demo.git
2. Start the app in dev mode
cd onmachina-ui-demo.git
npm i
npm run dev
3. Open the app in your browser using the link provided. Most likely something like http://127.0.0.1:5173/
4. Authenticate with a testnet wallet
5. Add and delete containers (i.e. folders) and objects (i.e. files)
|
MrQuyenIT_SmartContractDemo | .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
| Guest Book
==========
[](https://travis-ci.com/near-examples/guest-book)
[](https://gitpod.io/#https://github.com/near-examples/guest-book)
<!-- MAGIC COMMENT: DO NOT DELETE! Everything above this line is hidden on NEAR Examples page -->
Sign in with [NEAR] and add a message to the guest book! A starter app built with an [AssemblyScript] backend and a [React] frontend.
Quick Start
===========
To run this project locally:
1. Prerequisites: Make sure you have Node.js โฅ 12 installed (https://nodejs.org), then use it to install [yarn]: `npm install --global yarn` (or just `npm i -g yarn`)
2. Run the local development server: `yarn && yarn dev` (see `package.json` for a
full list of `scripts` you can run with `yarn`)
Now you'll have a local development environment backed by the NEAR TestNet! Running `yarn dev` will tell you the URL you can visit in your browser to see the app.
Exploring The Code
==================
1. The backend code lives in the `/assembly` folder. This code gets deployed to
the NEAR blockchain when you run `yarn deploy:contract`. This sort of
code-that-runs-on-a-blockchain is called a "smart contract" โ [learn more
about NEAR smart contracts][smart contract docs].
2. The frontend code lives in the `/src` folder.
[/src/index.html](/src/index.html) is a great place to start exploring. Note
that it loads in `/src/index.js`, where you can learn how the frontend
connects to the NEAR blockchain.
3. Tests: there are different kinds of tests for the frontend and backend. The
backend code gets tested with the [asp] command for running the backend
AssemblyScript tests, and [jest] for running frontend tests. You can run
both of these at once with `yarn test`.
Both contract and client-side code will auto-reload as you change source files.
Deploy
======
Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `yarn dev`, your smart contracts get deployed to the live NEAR TestNet with a throwaway account. When you're ready to make it permanent, here's how.
Step 0: Install near-cli
--------------------------
You need near-cli installed globally. Here's how:
npm install --global near-cli
This will give you the `near` [CLI] tool. Ensure that it's installed with:
near --version
Step 1: Create an account for the contract
------------------------------------------
Visit [NEAR Wallet] and make a new account. You'll be deploying these smart contracts to this new account.
Now authorize NEAR CLI for this new account, and follow the instructions it gives you:
near login
Step 2: set contract name in code
---------------------------------
Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above.
const CONTRACT_NAME = process.env.CONTRACT_NAME || 'your-account-here!'
Step 3: change remote URL if you cloned this repo
-------------------------
Unless you forked this repository you will need to change the remote URL to a repo that you have commit access to. This will allow auto deployment to Github Pages from the command line.
1) go to GitHub and create a new repository for this project
2) open your terminal and in the root of this project enter the following:
$ `git remote set-url origin https://github.com/YOUR_USERNAME/YOUR_REPOSITORY.git`
Step 4: deploy!
---------------
One command:
yarn deploy
As you can see in `package.json`, this does two things:
1. builds & deploys smart contracts to NEAR TestNet
2. builds & deploys frontend code to GitHub using [gh-pages]. This will only work if the project already has a repository set up on GitHub. Feel free to modify the `deploy` script in `package.json` to deploy elsewhere.
[NEAR]: https://nearprotocol.com/
[yarn]: https://yarnpkg.com/
[AssemblyScript]: https://docs.assemblyscript.org/
[React]: https://reactjs.org
[smart contract docs]: https://docs.nearprotocol.com/docs/roles/developer/contracts/assemblyscript
[asp]: https://www.npmjs.com/package/@as-pect/cli
[jest]: https://jestjs.io/
[NEAR accounts]: https://docs.nearprotocol.com/docs/concepts/account
[NEAR Wallet]: https://wallet.nearprotocol.com
[near-cli]: https://github.com/nearprotocol/near-cli
[CLI]: https://www.w3schools.com/whatis/whatis_cli.asp
[create-near-app]: https://github.com/nearprotocol/create-near-app
[gh-pages]: https://github.com/tschaub/gh-pages
|
LyiZri_near_demo_shareFileOnWeb3 | .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
utils
web3.js
| Guest Book
==========
[](https://travis-ci.com/near-examples/guest-book)
[](https://gitpod.io/#https://github.com/near-examples/guest-book)
<!-- MAGIC COMMENT: DO NOT DELETE! Everything above this line is hidden on NEAR Examples page -->
Sign in with [NEAR] and add a message to the guest book! A starter app built with an [AssemblyScript] backend and a [React] frontend.
Quick Start
===========
To run this project locally:
1. Prerequisites: Make sure you have Node.js โฅ 12 installed (https://nodejs.org), then use it to install [yarn]: `npm install --global yarn` (or just `npm i -g yarn`)
2. Run the local development server: `yarn && yarn dev` (see `package.json` for a
full list of `scripts` you can run with `yarn`)
Now you'll have a local development environment backed by the NEAR TestNet! Running `yarn dev` will tell you the URL you can visit in your browser to see the app.
Exploring The Code
==================
1. The backend code lives in the `/assembly` folder. This code gets deployed to
the NEAR blockchain when you run `yarn deploy:contract`. This sort of
code-that-runs-on-a-blockchain is called a "smart contract" โ [learn more
about NEAR smart contracts][smart contract docs].
2. The frontend code lives in the `/src` folder.
[/src/index.html](/src/index.html) is a great place to start exploring. Note
that it loads in `/src/index.js`, where you can learn how the frontend
connects to the NEAR blockchain.
3. Tests: there are different kinds of tests for the frontend and backend. The
backend code gets tested with the [asp] command for running the backend
AssemblyScript tests, and [jest] for running frontend tests. You can run
both of these at once with `yarn test`.
Both contract and client-side code will auto-reload as you change source files.
Deploy
======
Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `yarn dev`, your smart contracts get deployed to the live NEAR TestNet with a throwaway account. When you're ready to make it permanent, here's how.
Step 0: Install near-cli
--------------------------
You need near-cli installed globally. Here's how:
npm install --global near-cli
This will give you the `near` [CLI] tool. Ensure that it's installed with:
near --version
Step 1: Create an account for the contract
------------------------------------------
Visit [NEAR Wallet] and make a new account. You'll be deploying these smart contracts to this new account.
Now authorize NEAR CLI for this new account, and follow the instructions it gives you:
near login
Step 2: set contract name in code
---------------------------------
Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above.
const CONTRACT_NAME = process.env.CONTRACT_NAME || 'your-account-here!'
Step 3: change remote URL if you cloned this repo
-------------------------
Unless you forked this repository you will need to change the remote URL to a repo that you have commit access to. This will allow auto deployment to GitHub Pages from the command line.
1) go to GitHub and create a new repository for this project
2) open your terminal and in the root of this project enter the following:
$ `git remote set-url origin https://github.com/YOUR_USERNAME/YOUR_REPOSITORY.git`
Step 4: deploy!
---------------
One command:
yarn deploy
As you can see in `package.json`, this does two things:
1. builds & deploys smart contracts to NEAR TestNet
2. builds & deploys frontend code to GitHub using [gh-pages]. This will only work if the project already has a repository set up on GitHub. Feel free to modify the `deploy` script in `package.json` to deploy elsewhere.
[NEAR]: https://near.org/
[yarn]: https://yarnpkg.com/
[AssemblyScript]: https://www.assemblyscript.org/introduction.html
[React]: https://reactjs.org
[smart contract docs]: https://docs.near.org/docs/develop/contracts/overview
[asp]: https://www.npmjs.com/package/@as-pect/cli
[jest]: https://jestjs.io/
[NEAR accounts]: https://docs.near.org/docs/concepts/account
[NEAR Wallet]: https://wallet.near.org
[near-cli]: https://github.com/near/near-cli
[CLI]: https://www.w3schools.com/whatis/whatis_cli.asp
[create-near-app]: https://github.com/near/create-near-app
[gh-pages]: https://github.com/tschaub/gh-pages
# near_demo_shareFileOnWeb3
|
inteldev2080_NFT-Staking | .eslintrc.js
README.md
contracts
ft
Cargo.toml
README.md
build.sh
src
fungible_token_core.rs
fungible_token_metadata.rs
internal.rs
lib.rs
storage_manager.rs
market-simple
Cargo.toml
README.md
build.sh
src
external.rs
ft_callbacks.rs
internal.rs
lib.rs
nft_callbacks.rs
sale.rs
sale_views.rs
nft-simple
Cargo.toml
README.md
build.sh
src
burn.rs
enumerable.rs
internal.rs
lib.rs
metadata.rs
mint.rs
nft_core.rs
token.rs
docs
css
animate.css
bbp-theme.css
bbpress.css
bootstrap-timepicker.css
bootstrap.min.css
buddypress-theme.css
buddypress.css
colors
20 color scheme.txt
c1.css
c10.css
c11.css
c12.css
c13.css
c14.css
c15.css
c16.css
c17.css
c18.css
c19.css
c2.css
c20.css
c3.css
c4.css
c5.css
c6.css
c7.css
c8.css
c9.css
example.css
flaticon.css
font-awesome.min.css
icomoon.css
jquery-ui.min.css
jquery.bxslider.css
jquery.fullPage.css
jquery.gridder.min.css
jquery.pagepiling.css
jquery.sidr.dark.css
jquery.timepicker.css
lightbox.css
magnific-popup.css
main.css
media-queries.css
multiscroll.css
onepage-scroll.css
owl.carousel.css
prettyPhoto.css
selectize.default.css
supersized.css
fonts
flaticons
flaticon.html
flaticon.svg
fontawesome-webfont.svg
mission-script
mission-script-webfont.svg
img
misc
vault.svg
index.html
js
app.js
bootstrap-progressbar.min.js
bootstrap-timepicker.js
bootstrap.min.js
form.min.js
img-filter
jquery.gray.min.js
jflickrfeed.min.js
jquery-countTo.js
jquery-migrate.min.js
jquery-ui.min.js
jquery-validation.min.js
jquery.appear.js
jquery.backstretch.min.js
jquery.bxslider.min.js
jquery.circliful.min.js
jquery.countdown.js
jquery.easing.min.js
jquery.easypiechart.js
jquery.fullPage.min.js
jquery.isotope.min.js
jquery.magnific-popup.min.js
jquery.mb.YTPlayer.js
jquery.multiscroll.min.js
jquery.nav.js
jquery.nicescroll.min.js
jquery.pagepiling.min.js
jquery.parallax-1.1.3.js
jquery.prettySocial.min.js
jquery.scrollNav.min.js
jquery.selectbox-0.2.min.js
jquery.singlePageNav.min.js
jquery.stellar.min.js
jquery.superslides.min.js
jquery.ticker.js
jquery.timepicker.min.js
jquery.tubular.1.0.js
jquery.webticker.min.js
jquery.zoom.min.js
kenburned.min.js
lightbox.min.js
main.js
masonry.pkgd.js
mediaelement-and-player.min.js
okvideo.min.js
owl.carousel.min.js
particles.min.js
selectize.min.js
supersized.3.2.7.min.js
theme
supersized.shutter.css
supersized.shutter.min.js
tweetie.min.js
vendor
jquery-1.11.1.min.js
modernizr-2.6.2.min.js
owl.carousel.css
owl.carousel.min.js
wow.min.js
shortcodes
css
camera.css
eislideshow.css
elastislide.css
flexslider.css
fonts
flexslider-icon.svg
glyphicons-halflings-regular.svg
icomoon.svg
iconmoon.css
liteaccordion.css
main.css
media-queries.css
nivo-slider.css
owl.carousel.css
prettyPhoto.css
slicebox.css
fonts
flexslider-icon.svg
glyphicons-halflings-regular.svg
icomoon.svg
images
camera
slides
thumbs
_notes
dwsync.xml
js
camera.min.js
jquery.eislideshow.js
jquery.flexslider-min.js
jquery.nivo.slider.pack.js
jquery.prettyPhoto.js
jquery.slicebox.min.js
jquery.zaccordion.min.js
main.js
owl.carousel.js
syntax-highlighter
scripts
prettify.min.css
prettify.min.js
vault
batch-transaction.js
batch-transaction.ts
index.html
narwallet.js
narwallet.ts
util.js
utils.ts
wallet-interface.js
wallet-interface.ts
Header Top
navbar nav
nav4
Mega Menu
Header 2
Header 6
Header 14
header 15
header 16
header 17
index 18
vertical nav
header19
Header 21
Header 22
Header 23
Header 24
Home 25
Header 25
Header 27
Home 27
Header 28
Home 28
Dropdown
Timeline Blog
Post Comment Section
Right SIdebar
Related Products
compare page
Shop Header
Shop Intro
shop 2 product single
Promo Block
Product
shop list view
Look book
top-nav type 3
End top-nav
photography
Home Shop 3
utils
deploy.js
patch-config.js
patch-deploy-config.js
definition
addOptionMethod
plugin bridge
bridget
module definition
helpers
measurements
setup
box sizing
getSize
match
appendToFragment
query
matchChild
matchesSelector
get style
Outlayer definition
CSS3 support
Item
transition
events
show
hide
remove
transport
vars
Outlayer
init & layout
ignore & stamps
resize
methods
destroy
data
create Outlayer class
declarative
jQuery bridge
fin
masonryDefinition
jest.config.js
package.json
src
App.js
components
Contract.js
Gallery.js
Token.js
Wallet.js
config.js
img
near_icon.svg
index.html
index.js
state
app.js
near.js
utils
history.js
mobile.js
near-utils.js
state.js
storage.js
test
app.test.js
near-utils.js
test-utils.js
| Minimal NEP141 + Metadata Token Launcher
TBD
Fork of: https://github.com/mikedotexe/nep-141-examples (basic)
# TBD
# Varda NFT market implementation
Using the PoC backbone for NFT Marketplaces on NEAR Protocol.
[Reference](https://nomicon.io/Standards/NonFungibleToken/README.html)
## ToDo:
- [ ] add stNEAR as a trading ft
- [ ] implement [Narwallet](https://narwallets.github.io/meta-pool/) with Varda Vault NEARNFT dispay for unlockable content
## Varda strategy game and staking mechanics explained
[](https://www.youtube.com/watch?v=xM8EhLeGOEI)
## Varda cultural reference
[](https://www.youtube.com/watch?v=6rOkVq8qPrs)
[Varda Tokenomics](https://varda-vision.medium.com/)
## Progress:
- [x] basic purchase of NFT with FT
- [x] demo pay out royalties (FTs and NEAR)
- [x] test and determine standards for markets (best practice?) to buy/sell NFTs (finish standard) with FTs (already standard)
- [x] demo some basic auction types, secondary markets and
- [x] frontend example
- [x] first pass / internal audit
- [ ] connect with bridged tokens e.g. buy and sell with wETH/nDAI (or whatever we call these)
- [ ] add ability to migrate NFT to ethereum blockchain using rainbowbridge/aurora
## Notes:
High level diagram of NFT sale on Market using Fungible Token:

Remove the FT steps for NEAR transfers (but nft_transfer_payout and resolve_purchase still the same).
Differences from `nft-simple` NFT standard reference implementation:
- anyone can mint an NFT
- Optional token_type
- capped supply by token_type
- lock transfers by token_token
- enumerable.rs
## Working
**Frontend App Demo: `/test/app.test.js/`**
- install, deploy, test `yarn && yarn test:deploy`
- run app - `yarn start`
**App Tests: `/test/app.test.js/`**
- install, deploy, test `yarn && yarn test:deploy`
- if you update contracts - `yarn test:deploy`
- if you update tests only - `yarn test`
# NFT Specific Notes
Associated Video Demos (most recent at top)
[](https://www.youtube.com/watch?v=AevmMAtkIr4)
[](https://youtu.be/sGTC3rs8OJQ)
Some additional ideas around user onboarding:
[](https://www.youtube.com/watch?v=59Lzt1PFF6I)
# Detailed Installation / Quickstart
#### If you don't have Rust
Install Rust https://rustup.rs/
#### If you have never used near-cli
1. Install near-cli: `npm i -g near-cli`
2. Create testnet account: [Wallet](https://wallet.testnet.near.org)
3. Login: `near login`
#### Installing and Running Tests for this Example
1. Install everything: `yarn && (cd server && yarn)`
2. Deploy the contract and run the app tests: `yarn test:deploy`
3. (WIP) Start server and run server tests: `cd server && yarn start` then in another terminal from the root `yarn test:server`
#### Notes
- If you ONLY change the JS tests use `yarn test`.
- If you change the contract run `yarn test:deploy` again.
- If you run out of funds in the dev account run `yarn test:deploy` again.
- If you change the dev account (yarn test:deploy) the server should restart automatically, but you may need to restart the app and sign out/in again with NEAR Wallet.
### Moar Context
There's 3 main areas to explore:
- frontend app - shows how to create guest accounts that are added to the app contract via the nodejs server. Guests can mind NFTs, put them up for sale and earn NEAR tokens. When the guest has NEAR they can upgrade their account to a full account.
- app.test.js (demos frontend only tests)
### Owner Account, Token Account, etc...
The tests are set up to auto generate the dev account each time you run `test:deploy` **e.g. you will get a new NFT contract address each time you run a test**.
This is just for testing. You can obviously deploy a token to a fixed address on testnet / mainnet, it's an easy config update.
#### Guests Account (key and tx gas sponsorship)
When you run app / server tests. There's a contract deployed and a special account created `guests.OWNER_ACCOUNT_ID` to manage the sponsored users (the ones you will pay for gas fees while onboarding). This special "guests" account is different from the test guest account `bob.TOKEN_ID.OWNER_ACCOUNT_ID`. It is an account, different from the owner or token accounts, that manages the guests keys.
#### Guest Accounts
The guest users can `claim_drop, ft_transfer_guest` and receive tokens from other users, e.g. in the server tests the owner transfers tokens to the guest account via API call and using client side code.
Then, following the server tests, the guest transfers tokens to alice (who is a real NEAR account e.g. she pays her own gas).
Finally, the guest upgrades themselves to a real NEAR account, something demoed in the video.
It's a lot to digest but if you focus on the `/test/app.test.js` you will start to see the patterns.
# Background
One of the issues with onboarding new users to crypto is that they need to have crypto to do anything e.g. mint an NFT. A creator, artist or community might want to drop a bunch of free minting options to their fans for them to mint user generated content, but the audience has (1) no crypto to pay for fees (2) no wallet (3) no concept of crypto or blockchain; prior to the drop.
So let's solve these issues by allowing users to generate content the traditional Web2 way!
We do a demo of creating a "guest" named account for an app where the gas fees are sponsored by a special app account called "guests.APP_NAME.near". The guest account doesn't exist (sometimes called a virtual or contract account) until the user creates and sells and NFT that generates some NEAR tokens and then they can upgrade to a real account. Until then their name is reserved because only the app is able to create "USERNAME.APP_NAME.near".
This has many advantages for user onboarding, where users can use the app immediately and later can be upgraded to a full account. The users also don't have to move any assets - namely the fungible tokens they earned as a guest user.
## Installation
Beyond having npm and node (latest versions), you should have Rust installed. I recommend nightly because living on the edge is fun.
https://rustup.rs/
Also recommend installing near-cli globally
`npm i -g near-cli`
Everything else can be installed via:
`yarn`
`cd server && yarn`
## NEAR Config
There is only one config.js file found in `src/config.js`, this is also used for running tests.
Using `src/config.js` you can set up your different environments. Use `REACT_APP_ENV` to switch environments e.g. in `package.json` script `deploy`.
## Running Tests
You can run unit tests in the Rust contracts themselves, but it may be more useful to JS tests against testnet itself.
Note: to run the app and server tests make sure you install and start the server.
- cd server
- yarn && yarn start
Commands:
- `test` will simply run app tests against the contract already deployed. You can mess around with `app.test.js` and try different frontend stuff
- `test:deploy` - will deploy a new dev account (`/neardev`) and deploy a new contract to this account, then run `test`
- `test:server` - will test the server, make sure you start it (see "Note" above)
- `test:unit` - runs the rust unit tests
If you've changed your contract or your dev account has run out of funds use `test:deploy`, if you're updating your JS tests only then use `test`.
## Test Utils
There are helpers in `test/test-utils.js` that take care of:
1. creating a near connection and establishing a keystore for the dev account
2. creating test accounts each time a test is run
3. establishing a contract instance so you can call methods
You can change the default funding amount for test accounts in `src/config.js`
## Using the NEAR Config in your app
In `src/state/near.js` you will see that `src/config.js` is loaded as a function. This is to satisfy the jest/node test runner.
You can destructure any properies of the config easily in any module you import it in like this:
```
// example file app.js
import getConfig from '../config';
export const {
GAS,
networkId, nodeUrl, walletUrl, nameSuffix,
contractName,
} = getConfig();
```
Note the export const in the destructuring?
Now you can import these like so:
```
//example file Component.js
import { GAS } from '../app.js'
...
await contract.withdraw({ amount: parseNearAmount('1') }, GAS)
...
```
# React 17, Parcel with useContext and useReducer
- Bundled with Parcel 2.0 (@next) && eslint
- *Minimal all-in-one state management with async/await support*
## Getting Started: State Store & useContext
>The following steps describe how to use `src/utils/state` to create and use your own `store` and `StateProvider`.
1. Create a file e.g. `/state/app.js` and add the following code
```js
import { State } from '../utils/state';
// example
const initialState = {
app: {
mounted: false
}
};
export const { store, Provider } = State(initialState);
```
2. Now in your `index.js` wrap your `App` component with the `StateProvider`
```js
import { Provider } from './state/app';
ReactDOM.render(
<Provider>
<App />
</Provider>,
document.getElementById('root')
);
```
3. Finally in `App.js` you can `useContext(store)`
```js
const { state, dispatch, update } = useContext(store);
```
## Usage in Components
### Print out state values
```js
<p>Hello {state.foo && state.foo.bar.hello}</p>
```
### Update state directly in component functions
```js
const handleClick = () => {
update('clicked', !state.clicked);
};
```
### Dispatch a state update function (action listener)
```js
const onMount = () => {
dispatch(onAppMount('world'));
};
useEffect(onMount, []);
```
## Dispatched Functions with context (update, getState, dispatch)
When a function is called using dispatch, it expects arguments passed in to the outer function and the inner function returned to be async with the following json args: `{ update, getState, dispatch }`
Example of a call:
```js
dispatch(onAppMount('world'));
```
All dispatched methods **and** update calls are async and can be awaited. It also doesn't matter what file/module the functions are in, since the json args provide all the context needed for updates to state.
For example:
```js
import { helloWorld } from './hello';
export const onAppMount = (message) => async ({ update, getState, dispatch }) => {
update('app', { mounted: true });
update('clicked', false);
update('data', { mounted: true });
await update('', { data: { mounted: false } });
console.log('getState', getState());
update('foo.bar', { hello: true });
update('foo.bar', { hello: false, goodbye: true });
update('foo', { bar: { hello: true, goodbye: false } });
update('foo.bar.goodbye', true);
await new Promise((resolve) => setTimeout(() => {
console.log('getState', getState());
resolve();
}, 2000));
dispatch(helloWorld(message));
};
```
## Prefixing store and Provider
The default names the `State` factory method returns are `store` and `Provider`. However, if you want multiple stores and provider contexts you can pass an additional `prefix` argument to disambiguate.
```js
export const { appStore, AppProvider } = State(initialState, 'app');
```
## Performance and memo
The updating of a single store, even several levels down, is quite quick. If you're worried about components re-rendering, use `memo`:
```js
import React, { memo } from 'react';
const HelloMessage = memo(({ message }) => {
console.log('rendered message');
return <p>Hello { message }</p>;
});
export default HelloMessage;
```
Higher up the component hierarchy you might have:
```js
const App = () => {
const { state, dispatch, update } = useContext(appStore);
...
const handleClick = () => {
update('clicked', !state.clicked);
};
return (
<div className="root">
<HelloMessage message={state.foo && state.foo.bar.hello} />
<p>clicked: {JSON.stringify(state.clicked)}</p>
<button onClick={handleClick}>Click Me</button>
</div>
);
};
```
When the button is clicked, the component HelloMessage will not re-render, it's value has been memoized (cached). Using this method you can easily prevent performance intensive state updates in further down components until they are neccessary.
Reference:
- https://reactjs.org/docs/context.html
- https://dmitripavlutin.com/use-react-memo-wisely/
# TBD
|
josefophe_nearmock-encode | README.md
as-pect.config.js
asconfig.json
contract
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
nearmock
asconfig.json
assembly
asconfig.json
index.ts
model.ts
tsconfig.json
tsconfig.json
utils.ts
next-env.d.ts
next.config.js
package.json
public
vercel.svg
src
config
near.config.js
lib
auth-near.js
firebase-admin.ts
firebase.ts
pages
api
quiz
[id]
answer.ts
index.ts
utils
db.ts
service.ts
tsconfig.json
| ## Inspiration
I have been in the education space for some years and I see the need for genuine community sharing between tutors and students for positive changes students performance using technology. This has been my personal project for some time now how tutors can share knowledge and earn token when student access their assessments within the Near Protocol ecosystem.
## What it does.
iMock is an decentralized app solution aimed to improve secondary school students(as a first case study), an Educational platform that enables learning at an easy pace, cost-effective and community based solution, providing seamless access to curated education assessment for students based on their curriculum. iMock is transparent in services and payment between authors/tutors and learners/students. User interface friendly, and on the blockchain (Near protocol).
- A tutor login with their near account and post their questions making a contract call and paying initial deposit of some near token(which covers gas fee and iMock storage fee)
- Students login with their near accounts, pay a token which in turns go back to the tutor (owner of the contract) they can practice the questions based on what they've learnt during the week at the end of each week making them conversant of what they learnt.
## How I built it
The contract was written in assembly script while the front was built with Typescript, chakra ui and firebase.
## Challenges I ran into
I had a learning challenge working with server side database storage with smart contracts or web3 as I cannot write to the database without a user token from firebase to authenticate the user writing to the database. This remain a big challenge for me storing data with a near account login model. I am yet to resolve this.
## Accomplishments that I am proud of
I was able to set up a login with near feature and authentication and smart contracts on assembly script.
## What I learned
Building with near protocol is quite an interesting journey as there is a lot to learn about web3 technology and how it works. With near I was able to full understand deployment and web3 accounts.
# `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.
[](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.
[](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
```
[](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)
|
jbrit_nearfusion-gateway | README.md
near-wallet.js
next-env.d.ts
next.config.js
package-lock.json
package.json
public
blue-grid.svg
fonts
GTWalsheimPro
stylesheet.css
Joystix
stylesheet.css
PPMonumentExtended
stylesheet.css
grid.svg
vercel.svg
src
assets
images
near-logo-black.svg
near-logotype.svg
near_social_combo.svg
near_social_icon.svg
vs_code_icon.svg
components
lib
Spinner
index.ts
Toast
README.md
api.ts
index.ts
store.ts
styles.ts
data
bos-components.ts
web3.ts
hooks
useBosComponents.ts
useBosLoaderInitializer.ts
useFlags.ts
useHashUrlBackwardsCompatibility.ts
useScrollBlock.ts
useSignInRedirect.ts
index.d.ts
lib
selector
setup.js
wallet.js
stores
auth.ts
bos-loader.ts
current-component.ts
vm.ts
styles
globals.css
home.css
theme.css
utils
auth.js
config.ts
firebase.ts
form-validation.ts
keypom-options.ts
nearblocks.ts
types.ts
tsconfig.json
types
rudderstack-analytics.ts
| # Gateway
The gateway is a Next JS app that serves the frontend and loads the `bos-components`.
## Setup & Development
Initialize repo in the root:
```
yarn
```
Start development server:
```
cd gateway && yarn run dev
```
## Local Component Development
1. Run an instance of a component server like [near/bos-loader](https://github.com/near/bos-loader)
2. Run from the project root:
```
bos-loader sweeter.testnet -p ./bos-components/src
```
3. 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
# 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>
```
|
here-wallet_data-proxy-server | docker-compose.yml
requirements.txt
src
app
__init__.py
models.py
routes.py
trx_generator_routes.py
configs.py
connection_manager.py
push_notification.py
run_web.py
| |
NearPass_near-nft-js-example | .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
| This was practice!
|
nqdinh-1203_near-k10 | .gitpod.yml
README.md
command.txt
contract
README.md
babel.config.json
build.sh
build
builder.c
code.h
hello_near.js
methods.h
deploy.sh
neardev
dev-account.env
package-lock.json
package.json
src
contract.ts
metadata.ts
token.ts
tsconfig.json
integration-tests
package-lock.json
package.json
src
main.ava.ts
package-lock.json
package.json
| 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.
```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>`.
|
NookieGrey_my-near | README.md
docs
index.html
index.html
package.json
src
assets
react.svg
shims.ts
vite-env.d.ts
tsconfig.json
tsconfig.node.json
vite.config.ts
| ### Demo
https://nookiegrey.github.io/my-near/
|
PrimeLabCore_cli-releases | README.md
| ### PrimeLab TPS-CLI
To run the PrimeLab TPS Testing CLI tool you will need a `client-id` and `start-key`. This will provide you with a private key and certificate to manage this client. You can get these from the PrimeLab team ([Here](https://primelab.io/contact/))
#### Current Release - ([Here](https://github.com/PrimeLabCore/cli-releases/releases/tag/4943941xca))
|OS|Arch|CLI Version|Download|
|--|--|--|--|
|Windows 10 and later|`64 bit`|`windows_amd64`| [Download](https://github.com/PrimeLabCore/cli-releases/releases/download/4943941xca/windows_amd64.zip) |
|Windows 7 and later|`32 bit, i386`|`windows_386`| [Download](https://github.com/PrimeLabCore/cli-releases/releases/download/4943941xca/windows_386.zip) |
|macOS Big Sur and later|`M1, M2`|`darwin_arm64`| [Download](https://github.com/PrimeLabCore/cli-releases/releases/download/4943941xca/darwin_arm64.zip) |
|macOS Big Sur and later|`intel 64 bit`|`darwin_amd64`| [Download](https://github.com/PrimeLabCore/cli-releases/releases/download/4943941xca/darwin_amd64.zip) |
|Linux - Debian Based distro|`64 bit`|`linux_amd64`| [Download](https://github.com/PrimeLabCore/cli-releases/releases/download/4943941xca/linux_amd64.zip) |
|Linux - Debian Based distro|`32 bit`|`linux_386`| [Download](https://github.com/PrimeLabCore/cli-releases/releases/download/4943941xca/linux_386.zip) |
### Step 1: Authenticate your CLI client with the network
./primechain init --client-id YOUR-CLIENT-ID --start-key YOUR-START-KEY
**Important** - `client-id` and `start-key` are both non-transferrable keys and may not be used by more than one user.
### Step 2: Create a PrimeLab Wallet
./primechain accounts create
**Important** - The `accounts create` command will output your 12 word seed phrase as well as your pub/private key. We recommend saving your seed phrase in a secure location.
### Step 3: Execute TPS Test on PrimeLab TestNet
**Parameters** - The `benchmark` command supports modifying parameters in order to test different types of transactions on the PrimeLab TestNet. You may modify the parameters to execute the TPS test to fit your specific use-case.
**Supported Transaction Types:**
1. createNFT
2. createConnection
3. generateFAK
4. sendToken
5. signContract
**Example CMD:**
./primechain benchmark --createNFT 10000 --createConnection 20000 --generateFAK 30000 --sendToken 40000 --signContract 50000
### Need Help?
```shell
$ ./primechain help
_____ _ _ _
| __ \ (_) | | | |
| |__) | _ __ _ _ __ ___ ___ | | __ _ | |__
| ___/ | '__| | | | '_ ` _ \ / _ \ | | / _` | | '_ \
| | | | | | | | | | | | | __/ | |____ | (_| | | |_) |
|_| |_| |_| |_| |_| |_| \___| |______| \__,_| |_.__/
Primechain TPS Tool is a tool to test the performance of Primechain network.
Usage:
tools [command]
Available Commands:
accounts Accounts commands
benchmark Benchmark the performance of PrimeChain
completion Generate the autocompletion script for the specified shell
help Help about any command
init Initialize Primechain CLI tool
Flags:
--auth-server string Authorization server address (default "traffic.cloudweb3.io")
-h, --help help for tools
-t, --toggle Help message for toggle
Use "tools [command] --help" for more information about a command.
```
|
NEARBuilders_NEP-Ideation | README.md
SUMMARY.md
nep-0000-template.md
nep-9999.md
| # NEP-Ideation
Let's ideate standards ๐ก
{% content-ref url="nep-0000-template.md" %}
[nep-0000-template.md](nep-0000-template.md)
{% endcontent-ref %}
## 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/Lk6pH07brRsxHEHhBO7d/" %}
[Community Groups](https://app.gitbook.com/o/wxNIOkA8NaT6omjLbqYh/s/Lk6pH07brRsxHEHhBO7d/)
{% endcontent-ref %}
{% content-ref url="https://app.gitbook.com/o/wxNIOkA8NaT6omjLbqYh/s/thv9RgvV6S5LYy0BQz01/" %}
[Resources](https://app.gitbook.com/o/wxNIOkA8NaT6omjLbqYh/s/thv9RgvV6S5LYy0BQz01/)
{% endcontent-ref %}
|
Learn-NEAR-Club_ncaptcha-gravity-addon | Controllers
FieldsController.php
PageConstructor.php
Helper
FormData.php
View.php
Model
Abstractions
AdminPages.php
Config.php
Constructor
ConfigPage.php
Constructor.php
Fields
NearPayableField.php
NearTransactionField.php
composer.json
index.php
readme.txt
templates
lnc-n-captcha-config.php
vendor
autoload.php
composer
ClassLoader.php
InstalledVersions.php
autoload_classmap.php
autoload_namespaces.php
autoload_psr4.php
autoload_real.php
autoload_static.php
installed.json
installed.php
webpack.config.js
| |
kyunghyunHan_near_counter_dapp | .gitpod.yml
README.md
contract
Cargo.toml
README.md
build.sh
deploy.sh
neardev
dev-account.env
src
lib.rs
frontend
.parcel-cache
d03bba54a655be5c.txt
App.js
assets
global.css
dist
index.94148097.css
index.bc0daea6.css
index.html
logo-black.4514ed42.svg
logo-black.54439fde.svg
logo-white.605d2742.svg
logo-white.a7716062.svg
index.html
index.js
near-wallet.js
package-lock.json
package.json
start.sh
ui-components.js
package-lock.json
package.json
| # Hello NEAR Contract
The smart contract exposes two methods to enable storing and retrieving a greeting in the NEAR network.
```rust
const DEFAULT_GREETING: &str = "Hello";
#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize)]
pub struct Contract {
greeting: String,
}
impl Default for Contract {
fn default() -> Self {
Self{greeting: DEFAULT_GREETING.to_string()}
}
}
#[near_bindgen]
impl Contract {
// Public: Returns the stored greeting, defaulting to 'Hello'
pub fn get_greeting(&self) -> String {
return self.greeting.clone();
}
// Public: Takes a greeting, such as 'howdy', and records it
pub fn set_greeting(&mut self, greeting: String) {
// Record a log permanently to the blockchain!
log!("Saving greeting {}", greeting);
self.greeting = greeting;
}
}
```
<br />
# Quickstart
1. Make sure you have installed [rust](https://rust.org/).
2. Install the [`NEAR CLI`](https://github.com/near/near-cli#setup)
<br />
## 1. Build and Deploy the Contract
You can automatically compile and deploy the contract in the NEAR testnet by running:
```bash
./deploy.sh
```
Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed:
```bash
cat ./neardev/dev-account
# e.g. dev-1659899566943-21539992274727
```
<br />
## 2. Retrieve the Greeting
`get_greeting` is a read-only method (aka `view` method).
`View` methods can be called for **free** by anyone, even people **without a NEAR account**!
```bash
# Use near-cli to get the greeting
near view <dev-account> get_greeting
```
<br />
## 3. Store a New Greeting
`set_greeting` changes the contract's state, for which it is a `change` method.
`Change` methods can only be invoked using a NEAR account, since the account needs to pay GAS for the transaction.
```bash
# Use near-cli to set a new greeting
near call <dev-account> set_greeting '{"message":"howdy"}' --accountId <dev-account>
```
**Tip:** If you would like to call `set_greeting` using your own account, first login into NEAR using:
```bash
# Use near-cli to login your NEAR account
near login
```
and then use the logged account to sign the transaction: `--accountId <your-account>`.
# near_counter_dapp
- ์ซ์ ์นด์ดํธ dapp

|
LTBach_Blockchain_in_Manufacturing_Integration_Tests | Cargo.toml
README.md
src
tests.rs
| # Blockchain_in_Manufacturing_Integration_Tests
_ This project is subproject of Blockchain_in_Manufacturing
_ Link to Blockchain_in_Manufacturing: https://github.com/LTBach/Blockchain_in_Manufacturing
# How to interact with code:
1. Clone repo
2. Paste this command-line in your terminal to see the magic
```
cargo run --example integration-tests
```
P/s: If you get trouble some thing like not install Cargo you can follow instruction on this link: https://doc.rust-lang.org/book/ch01-01-installation.html
|
near_useragent-discovery-container | .eslintrc.json
.github
ISSUE_TEMPLATE
BOUNTY.yml
README.md
middleware.ts
next-env.d.ts
package-lock.json
package.json
postcss.config.js
tailwind.config.js
tsconfig.json
turbo.json
vercel.json
| ---
name: User-Agent Based Rendering
slug: edge-functions-user-agent-based-rendering
description: Learn how to render a different page based on the User-Agent header.
framework: Next.js
useCase: Edge Middleware
css: Tailwind
deployUrl: https://vercel.com/new/clone?repository-url=https://github.com/vercel/examples/tree/main/edge-middleware/user-agent-based-rendering&project-name=user-agent-based-rendering&repository-name=user-agent-based-rendering
demoUrl: https://edge-user-agent-based-rendering.vercel.app
relatedTemplates:
- ab-testing-simple
---
# User-Agent Based Rendering
This example shows how to render a different page based on the [User-Agent header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent).
## Demo
https://edge-user-agent-based-rendering.vercel.app
## How to Use
You can choose from one of the following two methods to use this repository:
### One-Click Deploy
Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=vercel-examples):
[](https://vercel.com/new/clone?repository-url=https://github.com/vercel/examples/tree/main/edge-middleware/user-agent-based-rendering&project-name=user-agent-based-rendering&repository-name=user-agent-based-rendering)
### Clone and Deploy
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init) or [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) to bootstrap the example:
```bash
pnpm create next-app --example https://github.com/vercel/examples/tree/main/edge-middleware/user-agent-based-rendering
```
Next, run Next.js in development mode:
```bash
pnpm dev
```
Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=edge-middleware-eap) ([Documentation](https://nextjs.org/docs/deployment)).
|
glumb_IOTAtangle | .eslintrc.yml
.github
FUNDING.yml
README.md
|
package-lock.json
package.json
server
app.js
cleanup.js
mainnetApp.js
mainnetdata.json
mockZMQ.js
mocknetApp.js
mocknetdata.json
sub.js
webroot
index.html
lib
vivagraph.js
main.css
main.js
tangleGenerator.html
tangleglumb.html
tangleglumbTimemachine.html
| # IOTA Tangle Visualiser ๐ฆ
[](https://app.codacy.com/app/glumb/IOTAtangle?utm_source=github.com&utm_medium=referral&utm_content=glumb/IOTAtangle&utm_campaign=Badge_Grade_Dashboard)

Live Visualisation of the IOTA Tangle using a dynamically layouted graph.
Demo: [http://tangle.glumb.de](http://tangle.glumb.de)

## Usage and UI
All circles represent transactions (tx) in the IOTA Tangle.
A circular buffer is used to populate the viewer with the last 1800 (configurable) tx on page load.
Hover a tx to see more details:
- bottom left: value, tag, hash
- top left: how many tx are confirming the selcted one (yellow)
- top left: how many tx are confirmed by the selcted one (magenta)
- tx of the same bundle are highlightes in blue
Use the input boxes on the left to filter by hast, tag or bundle. The tag filter is applied using a regex.
Toggle switches on the top right:
| config | description |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| remove floating tx | some tx are not visually attached to the tangle since their attachement point lays so far back that it is not displayed anymore. Automatic removal of those tx increases performance |
| limit to 4k tx | for continuous use only 4000 tx are kept on screen. Older tx are deleted first. |
| pin old tx | pinning old tx increases performance by disabling their physics ad thus excluding them from the layouting process |
| reduce moevement | spawns new nodes close to their neighbours |
| size by # of confirms | tx that have been confirmed by more tx have a bigger diameter |
| size by weight | tx that confirm more tx have a bigger diameter |
| size by value | size based on transferred iota value |
| color by order | color ty based on the order they appear on screen. Continuous hue rotation |
### Configuration
In adition to setting configuration parameters using the ui, URL parameters can be used for presets.
**Example:**
`http://tangle.glumb.de/?DARK_MODE=true&CIRCLE_SIZE=40&HIGHLIGHT_COLOR_FORWARD="0xbada55ff"&svg`
**Syntax**
`http://tangle.glumb.de/?<CONFIG_PARAM_NAME>=<VALUE>[&<CONFIG_PARAM_NAME>=<VALUE>]`
**Available Configuration Parameters**
```json
CIRCLE_SIZE: 30, // size of a node
REMOVE_LONLY_AFTER_S: 30, // remove floating nodes after time
REMOVE_SMALLER_THAN_PERCENTAGE_OF_TOTAL_MESH: 0.03, // remove graphs that are smaller than % of all nodes
MAX_CIRCLE_SIZE: 80, // max node size used e.g. for 'size by value'
MAX_NODES: 4000, // max nodes when 'limit to 4k nodes' is enabled
// options
REMOVE_FLOATING_NODES: true,
COLOR_BY_DEPTH: false,
SIZE_BY_VALUE: false, // size based on transferred iota value
SIZE_BY_WEIGHT: false, // tx that confirm more tx have a bigger diameter
REMOVE_OLD_NODES: false, // only MAX_NODES tx are kept on screen. Older tx are deleted first.
PIN_OLD_NODES: true, // pinning old tx increases performance by disabling their physics ad thus excluding them from the layouting process
LIGHT_LINKS: false,
SPAWN_NODE_NEAR_FINAL_POSITION: true, // spawns new nodes close to their neighbours
COLOR_BY_NUMBER: false, // color ty based on the order they appear on screen. Continuous hue rotation
DARK_MODE: false,
// colors
HIGHLIGHT_MULTIPLE_COLOR: 0xda4b29, // for tags, hash, bundle filter
SAME_BUNDLE_COLOR: 0x1287ff,
LIGHT_LINK_COLOR: 0x222222ff,
LIGHT_NODE_COLOR: 0x000000ff,
LIGHT_NODE_BG_COLOR: 0xffffff,
NODE_CONFIRMED_COLOR: 0x000000,
HIGHLIGHT_COLOR_FORWARD: 0xf1b727ff,
HIGHLIGHT_COLOR_BACKWARD: 0xe23df4ff,
NODE_MILESTONE_COLOR: 0xe53d6f,
NODE_TIP_COLOR: 0x1fe0be,
LINK_COLOR: 0,
NODE_COLOR: 0,
NODE_BG_COLOR: 0,
// sizes
NODE_CONFIRMED_BORDER_SIZE: 1,
NODE_BASE_BORDER_SIZE: 0.8,
NODE_MILESTONE_BORDER_SIZE: 0.6,
NODE_TIP_BORDER_SIZE: 0.6,
// other
TITLE: "The Tangle",
EXPLORER_TX_LINK: "https://thetangle.org/transaction/",
EXPLORER_BUNDLE_LINK: "https://thetangle.org/bundle/",
```
**Additional Parameters**
Use `hash=<tx-hash>, bundle=<bundle-hash>, tag=<tx-tag>` to select a tx. Use with caution. The tx is only highlighted when on screen. Older tx are not queried.
Use `svg=true` to display a svg export utility button on the top left.
## Installation
Clone the repo and run `npm install`.
### Tangle Setup
The visualiser can be used for multiple networks (Mainnet, testnet, Customnet). The main entrypoint is the `<NAME>App.js` file.
To get started open the `mainnetApp.js` and configure the `ZMQ_ENDPOINT` and `LSM_NODE`.
Run `node mainnnetApp.js` to start the server. Done :)
To add another network, copy the `mainnetApp.js` and rename it to `<CustomName>App.js`. Copy the `mainnetdata.json` and also rename it to `<CustomName>data.json`.
Set your network endpoints in `<CustomName>App.js` and also set the `NAME` to `<CustomName>`.
## Architecture
The visualiser follows simple client server architecture. Server-side a ZMQ client is used for for data aquisition. It listens to the ZMQ Transaction stream of an IOTA Fullnode. An Instance of the IOTA JS library is used to peridically poll the latest milestone index.
Transactions are stroed in a ringbuffer to send the last 1800TX to the client on pageload.

## Telegram / Message Format
The data send to the client via WebSocket follow this structure:
**TX - Transaction**
```js
{
hash,
address,
value,
tag,
timestamp,
current_index,
last_index,
bundle_hash,
transaction_trunk,
transaction_branch;
}
```
**SN - Confirmed Transaction**
```js
{
hash, address, transaction_trunk, transaction_branch, bundle;
}
```
### Socket IO Client Events
The clients data interface is based on the SocketIO library. Therefore it is server agnostic as along as the expected SocketIO events are emittet by the backend.
On initialisation/pageload the following events are expected:
```js
socket.emit("config", FRONTEND_CONFIG); // { networkName }
socket.emit("inittx", txArray); // see format above
socket.emit("initsn", snArray); // see format above
socket.emit("initms", mileStoneArray); // Array of milestone tx hashes
```
During runtime the following event can be fired:
```js
socket.emit("tx", tx); // see format above
socket.emit("sn", sn); // see format above
socket.emit("ms", ms); // milestone tx hash
```
### API
include th following scripts
```html
<link rel="stylesheet" href="main.css" />
<script src="lib/vivagraph.js"></script>
<script src="main.js"></script>
<script
src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
crossorigin="anonymous"
></script>
```
Instantiate `TangleGlumb($DOMElement, [config])`
```js
const tg = TangleGlumb(document.getElementById("graph"), {
CIRCLE_SIZE: 60,
PIN_OLD_NODES: false,
STATIC_FRONT: false
});
tg.updateTx([tx]);
tg.removeTx([tx]);
```
Add and update array of transactions using `TG.updateTx(Array<txObj>)`
```js
const tx = {
hash: "",
address: "",
value: 0,
timestamp: Date.now(),
bundle_hash: "",
transaction_branch: "",
transaction_trunk: "",
tag: ""
milestone: false, //optional
confirmed: false, //optional
};
tg.updateTx([tx]);
```
Remove transactions from the visualisation using `TG.removeTx(Array<txObj|hash>)`
```js
const tx = {
hash: "",
address: "",
value: 0,
timestamp: Date.now(),
bundle_hash: "",
transaction_branch: "",
transaction_trunk: "",
tag: ""
milestone: false, //optional
confirmed: false, //optional
};
tg.removeTx([tx, tx.hash]);
```
|
namqdam_merkle-distributor | .eslintrc.json
.vscode
settings.json
Cargo.toml
README.md
contracts
merkle-distributor
Cargo.toml
build.sh
src
constant.rs
internal.rs
lib.rs
merkle_proof.rs
token.rs
util.rs
package.json
scripts
example.json
generate-merkle-root.ts
src
balance-tree.ts
parse-balance-map.ts
tests
config.ts
lib.test.ts
near-utils.ts
test-utils.ts
tsconfig.eslint.json
tsconfig.json
utils
config.ts
hoist-credentials.ts
| Merkle Distributor
===================
[](https://gitpod.io/#https://github.com/namqdam/merkle-distributor)
A program for distributing tokens efficiently via uploading a [Merkle root](https://en.wikipedia.org/wiki/Merkle_tree).
This program is largely based off of [Uniswap's Merkle Distributor](https://github.com/Uniswap/merkle-distributor).
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 `contracts/merkle-distributor/lib.rs`.
Building this contract
======================
Run the following, and we'll build our rust project up via cargo. This will generate our WASM binaries into our `target/` directory. This is the smart contract we'll be deploying onto the NEAR blockchain later.
```bash
cargo build --target wasm32-unknown-unknown --release
```
Testing this contract
=====================
We have some tests that you can run. For example, the following will run our simple tests to verify that our contract code is working.
```bash
cargo test -- --nocapture
```
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 target/wasm32-unknown-unknown/release/merkle_distributor.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-xxx
In this instance, the account is `dev-xxx`. 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
export ACCOUNT_ID=aabbcc
```
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
echo $ACCOUNT_ID
```
The next command will initialize the contract using the `new` method:
```bash
near call $CONTRACT_NAME initialize '{"owner_id": "aaa", "token_id": "bbb", "merkle_root": "bbb"}' --accountId $CONTRACT_NAME
```
To claim:
```bash
near call $CONTRACT_NAME claim '{"index": 0, "amount": 100, "proof": ["xxx"]}' --accountId $ACCOUNT_ID
```
Notes
=====
* To generate merkle_tree, using command
```bash
yarn generate-merkle-root -i scripts/example.json -o merkle.json
```
* The output tree will be located in merkle.json
* Using `merkleRoot` and `proof` for calling contract using near-cli
|
GiselleNessi_creea | .github
scripts
runfe.sh
workflows
scripts.yml
tests.yml
.gitpod.yml
README.md
contract
README.md
babel.config.json
build.sh
deploy.sh
package-lock.json
package.json
src
contract.ts
model.ts
utils.ts
tsconfig.json
frontend
apply.html
assets
global.css
logo-black.svg
logo-white.svg
form.html
home.html
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
| # Creea ๐ฑ
We empower women who can take action in Latam with grants and resources to support their cause through the power of web3. As the world is asking for a change and a new paradigm of society, our community has stepped up to demonstrate the many ways blockchain can be used to enhance real change and provide much-needed support to the people leading the most impactful initiatives
# 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. Only owner can make use of donation or payment systems by NEAR.
<br />
# Quickstart
Clone this repository locally
### 1. Install Dependencies
```bash
npm install
```
### 2. Deploy the Contract
Build the contract and deploy it in a testnet account
```bash
npm run deploy
```
### 3. Start the Frontend
Start the web application to interact with your smart contract
```bash
npm start
```
---
# Nice to have
1. Voting system with NEAR, to vote for grants approvals
2. Use REACT for the UI
3. Integrate a tokenomics strategy to invite DAOs to participate in the voting system
4. Make ir multi chain
# 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>`.
|
jerrymusaga_rusty-near | Cargo.toml
README.md
build.bat
build.sh
src
lib.rs
test.sh
| # Rust Smart Contract Template
## Getting started
To get started with this template:
1. Click the "Use this template" button to create a new repo based on this template
2. Update line 2 of `Cargo.toml` with your project name
3. Update line 4 of `Cargo.toml` with your project author names
4. Set up the [prerequisites](https://github.com/near/near-sdk-rs#pre-requisites)
5. Begin writing your smart contract in `src/lib.rs`
6. Test the contract
`cargo test -- --nocapture`
8. Build the contract
`RUSTFLAGS='-C link-arg=-s' cargo build --target wasm32-unknown-unknown --release`
**Get more info at:**
* [Rust Smart Contract Quick Start](https://docs.near.org/develop/prerequisites)
* [Rust SDK Book](https://www.near-sdk.io/)
|
nearvndev_staking-contract-rs-tutorial | Cargo.toml
build.sh
neardev
dev-account.env
src
account.rs
config.rs
core_impl.rs
enumeration.rs
internal.rs
lib.rs
util.rs
t2
tests
sim
main.rs
| |
koe7_nearcrowdfund | .gitpod.yml
README.md
babel.config.js
contract
Cargo.toml
README.md
compile.js
src
lib.rs
models.rs
utils.rs
package.json
src
App.js
__mocks__
fileMock.js
assets
logo-black.svg
logo-white.svg
components
CreateCrowdfunds.js
ListCrowdfunds.js
config.js
global.css
index.html
index.js
jest.init.js
main.test.js
utils.js
wallet
login
index.html
| crowdfundDapp 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
crowdfundDapp
==================
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 `crowdfundDapp.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `crowdfundDapp.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 crowdfundDapp.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 || 'crowdfundDapp.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
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.