.gitpod.yml
.theia
    settings.json
README.md
node_modules
    @as-pect
        assembly
            README.md
            assembly
                index.ts
                internal
                    Actual.ts
                    Expectation.ts
                    Expected.ts
                    Reflect.ts
                    ReflectedValueType.ts
                    Test.ts
                    assert.ts
                    call.ts
                    comparison
                        toIncludeComparison.ts
                        toIncludeEqualComparison.ts
                    log.ts
                    noOp.ts
            package.json
            types
                as-pect.d.ts
                as-pect.portable.d.ts
                env.d.ts
        cli
            README.md
            init
                as-pect.config.js
                env.d.ts
                example.spec.ts
                init-types.d.ts
                portable-types.d.ts
            lib
                as-pect.cli.amd.d.ts
                as-pect.cli.amd.js
                help.d.ts
                help.js
                index.d.ts
                index.js
                init.d.ts
                init.js
                portable.d.ts
                portable.js
                run.d.ts
                run.js
                test.d.ts
                test.js
                types.d.ts
                types.js
                util
                    CommandLineArg.d.ts
                    CommandLineArg.js
                    IConfiguration.d.ts
                    IConfiguration.js
                    asciiArt.d.ts
                    asciiArt.js
                    collectReporter.d.ts
                    collectReporter.js
                    getTestEntryFiles.d.ts
                    getTestEntryFiles.js
                    removeFile.d.ts
                    removeFile.js
                    strings.d.ts
                    strings.js
                    writeFile.d.ts
                    writeFile.js
                worklets
                    ICommand.d.ts
                    ICommand.js
                    compiler.d.ts
                    compiler.js
            package.json
        core
            README.md
            lib
                as-pect.core.amd.d.ts
                as-pect.core.amd.js
                index.d.ts
                index.js
                reporter
                    CombinationReporter.d.ts
                    CombinationReporter.js
                    EmptyReporter.d.ts
                    EmptyReporter.js
                    IReporter.d.ts
                    IReporter.js
                    SummaryReporter.d.ts
                    SummaryReporter.js
                    VerboseReporter.d.ts
                    VerboseReporter.js
                test
                    IWarning.d.ts
                    IWarning.js
                    TestContext.d.ts
                    TestContext.js
                    TestNode.d.ts
                    TestNode.js
                transform
                    assemblyscript.d.ts
                    assemblyscript.js
                    createAddReflectedValueKeyValuePairsMember.d.ts
                    createAddReflectedValueKeyValuePairsMember.js
                    createGenericTypeParameter.d.ts
                    createGenericTypeParameter.js
                    createStrictEqualsMember.d.ts
                    createStrictEqualsMember.js
                    emptyTransformer.d.ts
                    emptyTransformer.js
                    hash.d.ts
                    hash.js
                    index.d.ts
                    index.js
                util
                    IAspectExports.d.ts
                    IAspectExports.js
                    IWriteable.d.ts
                    IWriteable.js
                    ReflectedValue.d.ts
                    ReflectedValue.js
                    TestNodeType.d.ts
                    TestNodeType.js
                    rTrace.d.ts
                    rTrace.js
                    stringifyReflectedValue.d.ts
                    stringifyReflectedValue.js
                    timeDifference.d.ts
                    timeDifference.js
                    wasmTools.d.ts
                    wasmTools.js
            package.json
        csv-reporter
            index.ts
            lib
                as-pect.csv-reporter.amd.d.ts
                as-pect.csv-reporter.amd.js
                index.d.ts
                index.js
            package.json
            readme.md
            tsconfig.json
        json-reporter
            index.ts
            lib
                as-pect.json-reporter.amd.d.ts
                as-pect.json-reporter.amd.js
                index.d.ts
                index.js
            package.json
            readme.md
            tsconfig.json
        snapshots
            __tests__
                snapshot.spec.ts
            jest.config.js
            lib
                Snapshot.d.ts
                Snapshot.js
                SnapshotDiff.d.ts
                SnapshotDiff.js
                SnapshotDiffResult.d.ts
                SnapshotDiffResult.js
                as-pect.core.amd.d.ts
                as-pect.core.amd.js
                index.d.ts
                index.js
                parser
                    grammar.d.ts
                    grammar.js
            package.json
            src
                Snapshot.ts
                SnapshotDiff.ts
                SnapshotDiffResult.ts
                index.ts
                parser
                    grammar.ts
            tsconfig.json
    @assemblyscript
        loader
            README.md
            index.d.ts
            index.js
            package.json
            umd
                index.d.ts
                index.js
                package.json
    ansi-regex
        index.d.ts
        index.js
        package.json
        readme.md
    ansi-styles
        index.d.ts
        index.js
        package.json
        readme.md
    as-bignum
        .travis.yml
        README.md
        as-pect.config.js
        assembly
            __tests__
                as-pect.d.ts
                safe_u128.spec.as.ts
                u128.spec.as.ts
                u256.spec.as.ts
                utils.ts
            fixed
                fp128.ts
                fp256.ts
                index.ts
                safe
                    fp128.ts
                    fp256.ts
                types.ts
            globals.ts
            index.ts
            integer
                i128.ts
                i256.ts
                index.ts
                safe
                    i128.ts
                    i256.ts
                    i64.ts
                    index.ts
                    u128.ts
                    u256.ts
                    u64.ts
                u128.ts
                u256.ts
            tsconfig.json
            utils.ts
        index.js
        package.json
        tsconfig.json
    asbuild
        README.md
        dist
            cli.d.ts
            cli.js
            index.d.ts
            index.js
            main.d.ts
            main.js
        index.js
        node_modules
            cliui
                CHANGELOG.md
                LICENSE.txt
                README.md
                index.js
                package.json
            wrap-ansi
                index.js
                package.json
                readme.md
            y18n
                CHANGELOG.md
                README.md
                index.js
                package.json
            yargs-parser
                CHANGELOG.md
                LICENSE.txt
                README.md
                index.js
                lib
                    tokenize-arg-string.js
                package.json
            yargs
                CHANGELOG.md
                README.md
                build
                    lib
                        apply-extends.d.ts
                        apply-extends.js
                        argsert.d.ts
                        argsert.js
                        command.d.ts
                        command.js
                        common-types.d.ts
                        common-types.js
                        completion-templates.d.ts
                        completion-templates.js
                        completion.d.ts
                        completion.js
                        is-promise.d.ts
                        is-promise.js
                        levenshtein.d.ts
                        levenshtein.js
                        middleware.d.ts
                        middleware.js
                        obj-filter.d.ts
                        obj-filter.js
                        parse-command.d.ts
                        parse-command.js
                        process-argv.d.ts
                        process-argv.js
                        usage.d.ts
                        usage.js
                        validation.d.ts
                        validation.js
                        yargs.d.ts
                        yargs.js
                        yerror.d.ts
                        yerror.js
                index.js
                locales
                    be.json
                    de.json
                    en.json
                    es.json
                    fi.json
                    fr.json
                    hi.json
                    hu.json
                    id.json
                    it.json
                    ja.json
                    ko.json
                    nb.json
                    nl.json
                    nn.json
                    pirate.json
                    pl.json
                    pt.json
                    pt_BR.json
                    ru.json
                    th.json
                    tr.json
                    zh_CN.json
                    zh_TW.json
                package.json
                yargs.js
        package.json
    assemblyscript-json
        .eslintrc.js
        .travis.yml
        README.md
        as-pect.config.js
        assembly
            JSON.ts
            __tests__
                as-pect.d.ts
                json-parse.spec.ts
                roundtrip.spec.ts
                to-string.spec.ts
                usage.spec.ts
            decoder.ts
            encoder.ts
            index.ts
            tsconfig.json
            util
                index.ts
        docs
            README.md
            classes
                decoderstate.md
                json.arr.md
                json.bool.md
                json.float.md
                json.integer.md
                json.null.md
                json.num.md
                json.obj.md
                json.str.md
                json.value.md
                jsondecoder.md
                jsonencoder.md
                jsonhandler.md
                throwingjsonhandler.md
            modules
                json.md
        index.js
        package.json
    assemblyscript
        README.md
        cli
            README.md
            asc.d.ts
            asc.js
            asc.json
            shim
                README.md
                fs.js
                path.js
                process.js
            transform.d.ts
            transform.js
            util
                colors.d.ts
                colors.js
                find.d.ts
                find.js
                mkdirp.d.ts
                mkdirp.js
                options.d.ts
                options.js
                utf8.d.ts
                utf8.js
        dist
            asc.js
            assemblyscript.d.ts
            assemblyscript.js
            sdk.js
        index.d.ts
        index.js
        lib
            loader
                README.md
                index.d.ts
                index.js
                package.json
                umd
                    index.d.ts
                    index.js
                    package.json
            rtrace
                README.md
                bin
                    rtplot.js
                index.d.ts
                index.js
                package.json
                umd
                    index.d.ts
                    index.js
                    package.json
        package-lock.json
        package.json
        std
            README.md
            assembly.json
            assembly
                array.ts
                arraybuffer.ts
                atomics.ts
                bindings
                    Date.ts
                    Math.ts
                    Reflect.ts
                    asyncify.ts
                    console.ts
                    wasi.ts
                    wasi_snapshot_preview1.ts
                    wasi_unstable.ts
                builtins.ts
                compat.ts
                console.ts
                crypto.ts
                dataview.ts
                date.ts
                diagnostics.ts
                error.ts
                function.ts
                index.d.ts
                iterator.ts
                map.ts
                math.ts
                memory.ts
                number.ts
                object.ts
                polyfills.ts
                process.ts
                reference.ts
                regexp.ts
                rt.ts
                rt
                    README.md
                    common.ts
                    index-incremental.ts
                    index-minimal.ts
                    index-stub.ts
                    index.d.ts
                    itcms.ts
                    rtrace.ts
                    stub.ts
                    tcms.ts
                    tlsf.ts
                set.ts
                shared
                    feature.ts
                    target.ts
                    tsconfig.json
                    typeinfo.ts
                staticarray.ts
                string.ts
                symbol.ts
                table.ts
                tsconfig.json
                typedarray.ts
                util
                    casemap.ts
                    error.ts
                    hash.ts
                    math.ts
                    memory.ts
                    number.ts
                    sort.ts
                    string.ts
                vector.ts
                wasi
                    index.ts
            portable.json
            portable
                index.d.ts
                index.js
            types
                assembly
                    index.d.ts
                    package.json
                portable
                    index.d.ts
                    package.json
        tsconfig-base.json
    axios
        CHANGELOG.md
        README.md
        UPGRADE_GUIDE.md
        dist
            axios.js
            axios.min.js
        index.d.ts
        index.js
        lib
            adapters
                README.md
                http.js
                xhr.js
            axios.js
            cancel
                Cancel.js
                CancelToken.js
                isCancel.js
            core
                Axios.js
                InterceptorManager.js
                README.md
                buildFullPath.js
                createError.js
                dispatchRequest.js
                enhanceError.js
                mergeConfig.js
                settle.js
                transformData.js
            defaults.js
            helpers
                README.md
                bind.js
                buildURL.js
                combineURLs.js
                cookies.js
                deprecatedMethod.js
                isAbsoluteURL.js
                isURLSameOrigin.js
                normalizeHeaderName.js
                parseHeaders.js
                spread.js
            utils.js
        package.json
    balanced-match
        .github
            FUNDING.yml
        LICENSE.md
        README.md
        index.js
        package.json
    base-x
        LICENSE.md
        README.md
        package.json
        src
            index.d.ts
            index.js
    binary-install
        README.md
        example
            binary.js
            package.json
            run.js
        index.js
        package.json
        src
            binary.js
    binaryen
        README.md
        index.d.ts
        package-lock.json
        package.json
        wasm.d.ts
    bn.js
        CHANGELOG.md
        README.md
        lib
            bn.js
        package.json
    brace-expansion
        README.md
        index.js
        package.json
    bs58
        CHANGELOG.md
        README.md
        index.js
        package.json
    camelcase
        index.d.ts
        index.js
        package.json
        readme.md
    chalk
        index.d.ts
        package.json
        readme.md
        source
            index.js
            templates.js
            util.js
    chownr
        README.md
        chownr.js
        package.json
    cliui
        CHANGELOG.md
        LICENSE.txt
        README.md
        build
            lib
                index.js
                string-utils.js
        package.json
    color-convert
        CHANGELOG.md
        README.md
        conversions.js
        index.js
        package.json
        route.js
    color-name
        README.md
        index.js
        package.json
    commander
        CHANGELOG.md
        Readme.md
        index.js
        package.json
        typings
            index.d.ts
    concat-map
        .travis.yml
        example
            map.js
        index.js
        package.json
        test
            map.js
    debug
        .coveralls.yml
        .travis.yml
        CHANGELOG.md
        README.md
        karma.conf.js
        node.js
        package.json
        src
            browser.js
            debug.js
            index.js
            node.js
    decamelize
        index.js
        package.json
        readme.md
    diff
        CONTRIBUTING.md
        README.md
        dist
            diff.js
        lib
            convert
                dmp.js
                xml.js
            diff
                array.js
                base.js
                character.js
                css.js
                json.js
                line.js
                sentence.js
                word.js
            index.es6.js
            index.js
            patch
                apply.js
                create.js
                merge.js
                parse.js
            util
                array.js
                distance-iterator.js
                params.js
        package.json
        release-notes.md
        runtime.js
    discontinuous-range
        .travis.yml
        README.md
        index.js
        package.json
        test
            main-test.js
    emoji-regex
        LICENSE-MIT.txt
        README.md
        es2015
            index.js
            text.js
        index.d.ts
        index.js
        package.json
        text.js
    env-paths
        index.d.ts
        index.js
        package.json
        readme.md
    escalade
        dist
            index.js
        index.d.ts
        package.json
        readme.md
        sync
            index.d.ts
            index.js
    find-up
        index.d.ts
        index.js
        package.json
        readme.md
    follow-redirects
        README.md
        http.js
        https.js
        index.js
        package.json
    fs-minipass
        README.md
        index.js
        package.json
    fs.realpath
        README.md
        index.js
        old.js
        package.json
    get-caller-file
        LICENSE.md
        README.md
        index.d.ts
        index.js
        package.json
    glob
        README.md
        changelog.md
        common.js
        glob.js
        package.json
        sync.js
    has-flag
        index.d.ts
        index.js
        package.json
        readme.md
    hasurl
        README.md
        index.js
        package.json
    inflight
        README.md
        inflight.js
        package.json
    inherits
        README.md
        inherits.js
        inherits_browser.js
        package.json
    is-fullwidth-code-point
        index.d.ts
        index.js
        package.json
        readme.md
    js-base64
        LICENSE.md
        README.md
        base64.d.ts
        base64.js
        package.json
    locate-path
        index.d.ts
        index.js
        package.json
        readme.md
    lodash.clonedeep
        README.md
        index.js
        package.json
    lodash.sortby
        README.md
        index.js
        package.json
    long
        README.md
        dist
            long.js
        index.js
        package.json
        src
            long.js
    minimatch
        README.md
        minimatch.js
        package.json
    minimist
        .travis.yml
        example
            parse.js
        index.js
        package.json
        test
            all_bool.js
            bool.js
            dash.js
            default_bool.js
            dotted.js
            kv_short.js
            long.js
            num.js
            parse.js
            parse_modified.js
            proto.js
            short.js
            stop_early.js
            unknown.js
            whitespace.js
    minipass
        README.md
        index.js
        package.json
    minizlib
        README.md
        constants.js
        index.js
        package.json
    mkdirp
        bin
            cmd.js
            usage.txt
        index.js
        package.json
    moo
        README.md
        moo.js
        package.json
    ms
        index.js
        license.md
        package.json
        readme.md
    near-mock-vm
        assembly
            __tests__
                main.ts
            context.ts
            index.ts
            outcome.ts
            vm.ts
        bin
            bin.js
        package.json
        pkg
            near_mock_vm.d.ts
            near_mock_vm.js
            package.json
        vm
            dist
                cli.d.ts
                cli.js
                context.d.ts
                context.js
                index.d.ts
                index.js
                memory.d.ts
                memory.js
                runner.d.ts
                runner.js
                utils.d.ts
                utils.js
            index.js
    near-sdk-as
        as-pect.config.js
        as_types.d.ts
        asconfig.json
        asp.asconfig.json
        assembly
            __tests__
                as-pect.d.ts
                assert.spec.ts
                avl-tree.spec.ts
                bignum.spec.ts
                contract.spec.ts
                contract.ts
                data.txt
                empty.ts
                generic.ts
                includeBytes.spec.ts
                main.ts
                max-heap.spec.ts
                model.ts
                near.spec.ts
                persistent-set.spec.ts
                promise.spec.ts
                rollback.spec.ts
                roundtrip.spec.ts
                runtime.spec.ts
                unordered-map.spec.ts
                util.ts
                utils.spec.ts
            as_types.d.ts
            bindgen.ts
            index.ts
            json.lib.ts
            tsconfig.json
            vm
                __tests__
                    vm.include.ts
                index.ts
        compiler.js
        imports.js
        package.json
    near-sdk-bindgen
        README.md
        assembly
            index.ts
        compiler.js
        dist
            JSONBuilder.d.ts
            JSONBuilder.js
            classExporter.d.ts
            classExporter.js
            index.d.ts
            index.js
            transformer.d.ts
            transformer.js
            typeChecker.d.ts
            typeChecker.js
            utils.d.ts
            utils.js
        index.js
        package.json
    near-sdk-core
        README.md
        asconfig.json
        assembly
            as_types.d.ts
            base58.ts
            base64.ts
            bignum.ts
            collections
                avlTree.ts
                index.ts
                maxHeap.ts
                persistentDeque.ts
                persistentMap.ts
                persistentSet.ts
                persistentUnorderedMap.ts
                persistentVector.ts
                util.ts
            contract.ts
            env
                env.ts
                index.ts
                runtime_api.ts
            index.ts
            logging.ts
            math.ts
            promise.ts
            storage.ts
            tsconfig.json
            util.ts
        docs
            assets
                css
                    main.css
                js
                    main.js
                    search.json
            classes
                _sdk_core_assembly_collections_avltree_.avltree.html
                _sdk_core_assembly_collections_avltree_.avltreenode.html
                _sdk_core_assembly_collections_avltree_.childparentpair.html
                _sdk_core_assembly_collections_avltree_.nullable.html
                _sdk_core_assembly_collections_persistentdeque_.persistentdeque.html
                _sdk_core_assembly_collections_persistentmap_.persistentmap.html
                _sdk_core_assembly_collections_persistentset_.persistentset.html
                _sdk_core_assembly_collections_persistentunorderedmap_.persistentunorderedmap.html
                _sdk_core_assembly_collections_persistentvector_.persistentvector.html
                _sdk_core_assembly_contract_.context-1.html
                _sdk_core_assembly_contract_.contractpromise.html
                _sdk_core_assembly_contract_.contractpromiseresult.html
                _sdk_core_assembly_math_.rng.html
                _sdk_core_assembly_promise_.contractpromisebatch.html
                _sdk_core_assembly_storage_.storage-1.html
            globals.html
            index.html
            modules
                _sdk_core_assembly_base58_.base58.html
                _sdk_core_assembly_base58_.html
                _sdk_core_assembly_base64_.base64.html
                _sdk_core_assembly_base64_.html
                _sdk_core_assembly_collections_avltree_.html
                _sdk_core_assembly_collections_index_.collections.html
                _sdk_core_assembly_collections_index_.html
                _sdk_core_assembly_collections_persistentdeque_.html
                _sdk_core_assembly_collections_persistentmap_.html
                _sdk_core_assembly_collections_persistentset_.html
                _sdk_core_assembly_collections_persistentunorderedmap_.html
                _sdk_core_assembly_collections_persistentvector_.html
                _sdk_core_assembly_collections_util_.html
                _sdk_core_assembly_contract_.html
                _sdk_core_assembly_env_env_.env.html
                _sdk_core_assembly_env_env_.html
                _sdk_core_assembly_env_index_.html
                _sdk_core_assembly_env_runtime_api_.html
                _sdk_core_assembly_index_.html
                _sdk_core_assembly_logging_.html
                _sdk_core_assembly_logging_.logging.html
                _sdk_core_assembly_math_.html
                _sdk_core_assembly_math_.math.html
                _sdk_core_assembly_promise_.html
                _sdk_core_assembly_storage_.html
                _sdk_core_assembly_util_.html
                _sdk_core_assembly_util_.util.html
        package.json
    near-sdk-simulator
        __tests__
            avl-tree-contract.spec.ts
            cross.spec.ts
            empty.spec.ts
            exportAs.spec.ts
            singleton-no-constructor.spec.ts
            singleton.spec.ts
        asconfig.js
        asconfig.json
        assembly
            __tests__
                avlTreeContract.ts
                empty.ts
                exportAs.ts
                model.ts
                sentences.ts
                singleton-fail.ts
                singleton-no-constructor.ts
                singleton.ts
                words.ts
            as_types.d.ts
            tsconfig.json
        dist
            bin.d.ts
            bin.js
            context.d.ts
            context.js
            index.d.ts
            index.js
            runtime.d.ts
            runtime.js
            types.d.ts
            types.js
            utils.d.ts
            utils.js
        jest.config.js
        out
            assembly
                __tests__
                    exportAs.ts
                    model.ts
                    sentences.ts
                    singleton-no-constructor.ts
                    singleton.ts
        package.json
        src
            context.ts
            index.ts
            runtime.ts
            types.ts
            utils.ts
        tsconfig.json
    near-vm
        getBinary.js
        install.js
        package.json
        run.js
        uninstall.js
    nearley
        LICENSE.txt
        README.md
        bin
            nearley-railroad.js
            nearley-test.js
            nearley-unparse.js
            nearleyc.js
        lib
            compile.js
            generate.js
            lint.js
            nearley-language-bootstrapped.js
            nearley.js
            stream.js
            unparse.js
        package.json
    once
        README.md
        once.js
        package.json
    p-limit
        index.d.ts
        index.js
        package.json
        readme.md
    p-locate
        index.d.ts
        index.js
        package.json
        readme.md
    p-try
        index.d.ts
        index.js
        package.json
        readme.md
    path-exists
        index.d.ts
        index.js
        package.json
        readme.md
    path-is-absolute
        index.js
        package.json
        readme.md
    punycode
        LICENSE-MIT.txt
        README.md
        package.json
        punycode.es6.js
        punycode.js
    railroad-diagrams
        README.md
        example.html
        generator.html
        package.json
        railroad-diagrams.css
        railroad-diagrams.js
        railroad_diagrams.py
    randexp
        README.md
        lib
            randexp.js
        package.json
    require-directory
        .travis.yml
        index.js
        package.json
    require-main-filename
        CHANGELOG.md
        LICENSE.txt
        README.md
        index.js
        package.json
    ret
        README.md
        lib
            index.js
            positions.js
            sets.js
            types.js
            util.js
        package.json
    rimraf
        CHANGELOG.md
        README.md
        bin.js
        package.json
        rimraf.js
    safe-buffer
        README.md
        index.d.ts
        index.js
        package.json
    set-blocking
        CHANGELOG.md
        LICENSE.txt
        README.md
        index.js
        package.json
    string-width
        index.d.ts
        index.js
        package.json
        readme.md
    strip-ansi
        index.d.ts
        index.js
        package.json
        readme.md
    supports-color
        browser.js
        index.js
        package.json
        readme.md
    tar
        README.md
        index.js
        lib
            create.js
            extract.js
            get-write-flag.js
            header.js
            high-level-opt.js
            large-numbers.js
            list.js
            mkdir.js
            mode-fix.js
            pack.js
            parse.js
            path-reservations.js
            pax.js
            read-entry.js
            replace.js
            types.js
            unpack.js
            update.js
            warn-mixin.js
            winchars.js
            write-entry.js
        package.json
    tr46
        LICENSE.md
        README.md
        index.js
        lib
            mappingTable.json
            regexes.js
        package.json
    ts-mixer
        CHANGELOG.md
        README.md
        dist
            decorator.d.ts
            decorator.js
            index.d.ts
            index.js
            mixin-tracking.d.ts
            mixin-tracking.js
            mixins.d.ts
            mixins.js
            proxy.d.ts
            proxy.js
            settings.d.ts
            settings.js
            types.d.ts
            types.js
            util.d.ts
            util.js
        package.json
    universal-url
        README.md
        browser.js
        index.js
        package.json
    visitor-as
        .github
            workflows
                test.yml
        README.md
        as
            index.d.ts
            index.js
        asconfig.json
        dist
            astBuilder.d.ts
            astBuilder.js
            base.d.ts
            base.js
            baseTransform.d.ts
            baseTransform.js
            decorator.d.ts
            decorator.js
            examples
                capitalize.d.ts
                capitalize.js
                exportAs.d.ts
                exportAs.js
                functionCallTransform.d.ts
                functionCallTransform.js
                includeBytesTransform.d.ts
                includeBytesTransform.js
                list.d.ts
                list.js
            index.d.ts
            index.js
            path.d.ts
            path.js
            simpleParser.d.ts
            simpleParser.js
            transformer.d.ts
            transformer.js
            utils.d.ts
            utils.js
            visitor.d.ts
            visitor.js
        package.json
        tsconfig.json
    webidl-conversions
        LICENSE.md
        README.md
        lib
            index.js
        package.json
    whatwg-url
        LICENSE.txt
        README.md
        lib
            URL-impl.js
            URL.js
            URLSearchParams-impl.js
            URLSearchParams.js
            infra.js
            public-api.js
            url-state-machine.js
            urlencoded.js
            utils.js
        package.json
    which-module
        CHANGELOG.md
        README.md
        index.js
        package.json
    wrap-ansi
        index.js
        package.json
        readme.md
    wrappy
        README.md
        package.json
        wrappy.js
    y18n
        CHANGELOG.md
        README.md
        build
            lib
                cjs.js
                index.js
                platform-shims
                    node.js
        package.json
    yallist
        README.md
        iterator.js
        package.json
        yallist.js
    yargs-parser
        CHANGELOG.md
        LICENSE.txt
        README.md
        browser.js
        build
            lib
                index.js
                string-utils.js
                tokenize-arg-string.js
                yargs-parser-types.js
                yargs-parser.js
        package.json
    yargs
        CHANGELOG.md
        README.md
        build
            lib
                argsert.js
                command.js
                completion-templates.js
                completion.js
                middleware.js
                parse-command.js
                typings
                    common-types.js
                    yargs-parser-types.js
                usage.js
                utils
                    apply-extends.js
                    is-promise.js
                    levenshtein.js
                    obj-filter.js
                    process-argv.js
                    set-blocking.js
                    which-module.js
                validation.js
                yargs-factory.js
                yerror.js
        helpers
            index.js
            package.json
        locales
            be.json
            de.json
            en.json
            es.json
            fi.json
            fr.json
            hi.json
            hu.json
            id.json
            it.json
            ja.json
            ko.json
            nb.json
            nl.json
            nn.json
            pirate.json
            pl.json
            pt.json
            pt_BR.json
            ru.json
            th.json
            tr.json
            zh_CN.json
            zh_TW.json
        package.json
|
package.json

# base-x

[![NPM Package](https://img.shields.io/npm/v/base-x.svg?style=flat-square)](https://www.npmjs.org/package/base-x)
[![Build Status](https://img.shields.io/travis/cryptocoinjs/base-x.svg?branch=master&style=flat-square)](https://travis-ci.org/cryptocoinjs/base-x)

[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)

Fast base encoding / decoding of any given alphabet using bitcoin style leading
zero compression.

**WARNING:** This module is **NOT RFC3548** compliant,  it cannot be used for base16 (hex), base32, or base64 encoding in a standards compliant manner. 

## Example

Base58

``` javascript
var BASE58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
var bs58 = require('base-x')(BASE58)

var decoded = bs58.decode('5Kd3NBUAdUnhyzenEwVLy9pBKxSwXvE9FMPyR4UKZvpe6E3AgLr')

console.log(decoded)
// => <Buffer 80 ed db dc 11 68 f1 da ea db d3 e4 4c 1e 3f 8f 5a 28 4c 20 29 f7 8a d2 6a f9 85 83 a4 99 de 5b 19>

console.log(bs58.encode(decoded))
// => 5Kd3NBUAdUnhyzenEwVLy9pBKxSwXvE9FMPyR4UKZvpe6E3AgLr
```

### Alphabets

See below for a list of commonly recognized alphabets, and their respective base.

Base | Alphabet
------------- | -------------
2 | `01`
8 | `01234567`
11 | `0123456789a`
16 | `0123456789abcdef`
32 | `0123456789ABCDEFGHJKMNPQRSTVWXYZ`
32 | `ybndrfg8ejkmcpqxot1uwisza345h769` (z-base-32)
36 | `0123456789abcdefghijklmnopqrstuvwxyz`
58 | `123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz`
62 | `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`
64 | `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`
66 | `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~`

## How it works

It encodes octet arrays by doing long divisions on all significant digits in the
array, creating a representation of that number in the new base. Then for every
leading zero in the input (not significant as a number) it will encode as a
single leader character. This is the first in the alphabet and will decode as 8
bits. The other characters depend upon the base. For example, a base58 alphabet
packs roughly 5.858 bits per character.

This means the encoded string 000f (using a base16, 0-f alphabet) will actually decode
to 4 bytes unlike a canonical hex encoding which uniformly packs 4 bits into each
character.

While unusual, this does mean that no padding is required and it works for bases
like 43. 

## LICENSE [MIT](LICENSE)
A direct derivation of the base58 implementation from [`bitcoin/bitcoin`](https://github.com/bitcoin/bitcoin/blob/f1e2f2a85962c1664e4e55471061af0eaa798d40/src/base58.cpp),  generalized for variable length alphabets.
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)
# color-convert

[![Build Status](https://travis-ci.org/Qix-/color-convert.svg?branch=master)](https://travis-ci.org/Qix-/color-convert)

Color-convert is a color conversion library for JavaScript and node.
It converts all ways between `rgb`, `hsl`, `hsv`, `hwb`, `cmyk`, `ansi`, `ansi16`, `hex` strings, and CSS `keyword`s (will round to closest):

```js
var convert = require('color-convert');

convert.rgb.hsl(140, 200, 100);             // [96, 48, 59]
convert.keyword.rgb('blue');                // [0, 0, 255]

var rgbChannels = convert.rgb.channels;     // 3
var cmykChannels = convert.cmyk.channels;   // 4
var ansiChannels = convert.ansi16.channels; // 1
```

# Install

```console
$ npm install color-convert
```

# API

Simply get the property of the _from_ and _to_ conversion that you're looking for.

All functions have a rounded and unrounded variant. By default, return values are rounded. To get the unrounded (raw) results, simply tack on `.raw` to the function.

All 'from' functions have a hidden property called `.channels` that indicates the number of channels the function expects (not including alpha).

```js
var convert = require('color-convert');

// Hex to LAB
convert.hex.lab('DEADBF');         // [ 76, 21, -2 ]
convert.hex.lab.raw('DEADBF');     // [ 75.56213190997677, 20.653827952644754, -2.290532499330533 ]

// RGB to CMYK
convert.rgb.cmyk(167, 255, 4);     // [ 35, 0, 98, 0 ]
convert.rgb.cmyk.raw(167, 255, 4); // [ 34.509803921568626, 0, 98.43137254901961, 0 ]
```

### Arrays
All functions that accept multiple arguments also support passing an array.

Note that this does **not** apply to functions that convert from a color that only requires one value (e.g. `keyword`, `ansi256`, `hex`, etc.)

```js
var convert = require('color-convert');

convert.rgb.hex(123, 45, 67);      // '7B2D43'
convert.rgb.hex([123, 45, 67]);    // '7B2D43'
```

## Routing

Conversions that don't have an _explicitly_ defined conversion (in [conversions.js](conversions.js)), but can be converted by means of sub-conversions (e.g. XYZ -> **RGB** -> CMYK), are automatically routed together. This allows just about any color model supported by `color-convert` to be converted to any other model, so long as a sub-conversion path exists. This is also true for conversions requiring more than one step in between (e.g. LCH -> **LAB** -> **XYZ** -> **RGB** -> Hex).

Keep in mind that extensive conversions _may_ result in a loss of precision, and exist only to be complete. For a list of "direct" (single-step) conversions, see [conversions.js](conversions.js).

# Contribute

If there is a new model you would like to support, or want to add a direct conversion between two existing models, please send us a pull request.

# License
Copyright &copy; 2011-2016, Heather Arthur and Josh Junon. Licensed under the [MIT License](LICENSE).
assemblyscript-json

# assemblyscript-json

## Table of contents

### Namespaces

- [JSON](modules/json.md)

### Classes

- [DecoderState](classes/decoderstate.md)
- [JSONDecoder](classes/jsondecoder.md)
- [JSONEncoder](classes/jsonencoder.md)
- [JSONHandler](classes/jsonhandler.md)
- [ThrowingJSONHandler](classes/throwingjsonhandler.md)
# minizlib

A fast zlib stream built on [minipass](http://npm.im/minipass) and
Node.js's zlib binding.

This module was created to serve the needs of
[node-tar](http://npm.im/tar) and
[minipass-fetch](http://npm.im/minipass-fetch).

Brotli is supported in versions of node with a Brotli binding.

## How does this differ from the streams in `require('zlib')`?

First, there are no convenience methods to compress or decompress a
buffer.  If you want those, use the built-in `zlib` module.  This is
only streams.  That being said, Minipass streams to make it fairly easy to
use as one-liners: `new zlib.Deflate().end(data).read()` will return the
deflate compressed result.

This module compresses and decompresses the data as fast as you feed
it in.  It is synchronous, and runs on the main process thread.  Zlib
and Brotli operations can be high CPU, but they're very fast, and doing it
this way means much less bookkeeping and artificial deferral.

Node's built in zlib streams are built on top of `stream.Transform`.
They do the maximally safe thing with respect to consistent
asynchrony, buffering, and backpressure.

See [Minipass](http://npm.im/minipass) for more on the differences between
Node.js core streams and Minipass streams, and the convenience methods
provided by that class.

## Classes

- Deflate
- Inflate
- Gzip
- Gunzip
- DeflateRaw
- InflateRaw
- Unzip
- BrotliCompress (Node v10 and higher)
- BrotliDecompress (Node v10 and higher)

## USAGE

```js
const zlib = require('minizlib')
const input = sourceOfCompressedData()
const decode = new zlib.BrotliDecompress()
const output = whereToWriteTheDecodedData()
input.pipe(decode).pipe(output)
```

## REPRODUCIBLE BUILDS

To create reproducible gzip compressed files across different operating
systems, set `portable: true` in the options.  This causes minizlib to set
the `OS` indicator in byte 9 of the extended gzip header to `0xFF` for
'unknown'.
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
# cliui

[![Build Status](https://travis-ci.org/yargs/cliui.svg)](https://travis-ci.org/yargs/cliui)
[![Coverage Status](https://coveralls.io/repos/yargs/cliui/badge.svg?branch=)](https://coveralls.io/r/yargs/cliui?branch=)
[![NPM version](https://img.shields.io/npm/v/cliui.svg)](https://www.npmjs.com/package/cliui)
[![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version)

easily create complex multi-column command-line-interfaces.

## Example

```js
var ui = require('cliui')()

ui.div('Usage: $0 [command] [options]')

ui.div({
  text: 'Options:',
  padding: [2, 0, 2, 0]
})

ui.div(
  {
    text: "-f, --file",
    width: 20,
    padding: [0, 4, 0, 4]
  },
  {
    text: "the file to load." +
      chalk.green("(if this description is long it wraps).")
    ,
    width: 20
  },
  {
    text: chalk.red("[required]"),
    align: 'right'
  }
)

console.log(ui.toString())
```

<img width="500" src="screenshot.png">

## Layout DSL

cliui exposes a simple layout DSL:

If you create a single `ui.div`, passing a string rather than an
object:

* `\n`: characters will be interpreted as new rows.
* `\t`: characters will be interpreted as new columns.
* `\s`: characters will be interpreted as padding.

**as an example...**

```js
var ui = require('./')({
  width: 60
})

ui.div(
  'Usage: node ./bin/foo.js\n' +
  '  <regex>\t  provide a regex\n' +
  '  <glob>\t  provide a glob\t [required]'
)

console.log(ui.toString())
```

**will output:**

```shell
Usage: node ./bin/foo.js
  <regex>  provide a regex
  <glob>   provide a glob          [required]
```

## Methods

```js
cliui = require('cliui')
```

### cliui({width: integer})

Specify the maximum width of the UI being generated.
If no width is provided, cliui will try to get the current window's width and use it, and if that doesn't work, width will be set to `80`.

### cliui({wrap: boolean})

Enable or disable the wrapping of text in a column.

### cliui.div(column, column, column)

Create a row with any number of columns, a column
can either be a string, or an object with the following
options:

* **text:** some text to place in the column.
* **width:** the width of a column.
* **align:** alignment, `right` or `center`.
* **padding:** `[top, right, bottom, left]`.
* **border:** should a border be placed around the div?

### cliui.span(column, column, column)

Similar to `div`, except the next row will be appended without
a new line being created.

### cliui.resetOutput()

Resets the UI elements of the current cliui instance, maintaining the values
set for `width` and `wrap`.
# 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)
# tr46.js

> An implementation of the [Unicode TR46 specification](http://unicode.org/reports/tr46/).

## Installation

[Node.js](http://nodejs.org) `>= 6` is required. To install, type this at the command line:
```shell
npm install tr46
```

## API

### `toASCII(domainName[, options])`

Converts a string of Unicode symbols to a case-folded Punycode string of ASCII symbols.

Available options:
* [`checkBidi`](#checkBidi)
* [`checkHyphens`](#checkHyphens)
* [`checkJoiners`](#checkJoiners)
* [`processingOption`](#processingOption)
* [`useSTD3ASCIIRules`](#useSTD3ASCIIRules)
* [`verifyDNSLength`](#verifyDNSLength)

### `toUnicode(domainName[, options])`

Converts a case-folded Punycode string of ASCII symbols to a string of Unicode symbols.

Available options:
* [`checkBidi`](#checkBidi)
* [`checkHyphens`](#checkHyphens)
* [`checkJoiners`](#checkJoiners)
* [`useSTD3ASCIIRules`](#useSTD3ASCIIRules)

## Options

### `checkBidi`
Type: `Boolean`  
Default value: `false`  
When set to `true`, any bi-directional text within the input will be checked for validation.

### `checkHyphens`
Type: `Boolean`  
Default value: `false`  
When set to `true`, the positions of any hyphen characters within the input will be checked for validation.

### `checkJoiners`
Type: `Boolean`  
Default value: `false`  
When set to `true`, any word joiner characters within the input will be checked for validation.

### `processingOption`
Type: `String`  
Default value: `"nontransitional"`  
When set to `"transitional"`, symbols within the input will be validated according to the older IDNA2003 protocol. When set to `"nontransitional"`, the current IDNA2008 protocol will be used.

### `useSTD3ASCIIRules`
Type: `Boolean`  
Default value: `false`  
When set to `true`, input will be validated according to [STD3 Rules](http://unicode.org/reports/tr46/#STD3_Rules).

### `verifyDNSLength`
Type: `Boolean`  
Default value: `false`  
When set to `true`, the length of each DNS label within the input will be checked for validation.
# lodash.clonedeep v4.5.0

The [lodash](https://lodash.com/) method `_.cloneDeep` exported as a [Node.js](https://nodejs.org/) module.

## Installation

Using npm:
```bash
$ {sudo -H} npm i -g npm
$ npm i --save lodash.clonedeep
```

In Node.js:
```js
var cloneDeep = require('lodash.clonedeep');
```

See the [documentation](https://lodash.com/docs#cloneDeep) or [package source](https://github.com/lodash/lodash/blob/4.5.0-npm-packages/lodash.clonedeep) for more details.
[![Build Status](https://travis-ci.org/isaacs/rimraf.svg?branch=master)](https://travis-ci.org/isaacs/rimraf) [![Dependency Status](https://david-dm.org/isaacs/rimraf.svg)](https://david-dm.org/isaacs/rimraf) [![devDependency Status](https://david-dm.org/isaacs/rimraf/dev-status.svg)](https://david-dm.org/isaacs/rimraf#info=devDependencies)

The [UNIX command](http://en.wikipedia.org/wiki/Rm_(Unix)) `rm -rf` for node.

Install with `npm install rimraf`, or just drop rimraf.js somewhere.

## API

`rimraf(f, [opts], callback)`

The first parameter will be interpreted as a globbing pattern for files. If you
want to disable globbing you can do so with `opts.disableGlob` (defaults to
`false`). This might be handy, for instance, if you have filenames that contain
globbing wildcard characters.

The callback will be called with an error if there is one.  Certain
errors are handled for you:

* Windows: `EBUSY` and `ENOTEMPTY` - rimraf will back off a maximum of
  `opts.maxBusyTries` times before giving up, adding 100ms of wait
  between each attempt.  The default `maxBusyTries` is 3.
* `ENOENT` - If the file doesn't exist, rimraf will return
  successfully, since your desired outcome is already the case.
* `EMFILE` - Since `readdir` requires opening a file descriptor, it's
  possible to hit `EMFILE` if too many file descriptors are in use.
  In the sync case, there's nothing to be done for this.  But in the
  async case, rimraf will gradually back off with timeouts up to
  `opts.emfileWait` ms, which defaults to 1000.

## options

* unlink, chmod, stat, lstat, rmdir, readdir,
  unlinkSync, chmodSync, statSync, lstatSync, rmdirSync, readdirSync

    In order to use a custom file system library, you can override
    specific fs functions on the options object.

    If any of these functions are present on the options object, then
    the supplied function will be used instead of the default fs
    method.

    Sync methods are only relevant for `rimraf.sync()`, of course.

    For example:

    ```javascript
    var myCustomFS = require('some-custom-fs')

    rimraf('some-thing', myCustomFS, callback)
    ```

* maxBusyTries

    If an `EBUSY`, `ENOTEMPTY`, or `EPERM` error code is encountered
    on Windows systems, then rimraf will retry with a linear backoff
    wait of 100ms longer on each try.  The default maxBusyTries is 3.

    Only relevant for async usage.

* emfileWait

    If an `EMFILE` error is encountered, then rimraf will retry
    repeatedly with a linear backoff of 1ms longer on each try, until
    the timeout counter hits this max.  The default limit is 1000.

    If you repeatedly encounter `EMFILE` errors, then consider using
    [graceful-fs](http://npm.im/graceful-fs) in your program.

    Only relevant for async usage.

* glob

    Set to `false` to disable [glob](http://npm.im/glob) pattern
    matching.

    Set to an object to pass options to the glob module.  The default
    glob options are `{ nosort: true, silent: true }`.

    Glob version 6 is used in this module.

    Relevant for both sync and async usage.

* disableGlob

    Set to any non-falsey value to disable globbing entirely.
    (Equivalent to setting `glob: false`.)

## rimraf.sync

It can remove stuff synchronously, too.  But that's not so good.  Use
the async API.  It's better.

## CLI

If installed with `npm install rimraf -g` it can be used as a global
command `rimraf <path> [<path> ...]` which is useful for cross platform support.

## mkdirp

If you need to create a directory recursively, check out
[mkdirp](https://github.com/substack/node-mkdirp).
long.js
=======

A Long class for representing a 64 bit two's-complement integer value derived from the [Closure Library](https://github.com/google/closure-library)
for stand-alone use and extended with unsigned support.

[![Build Status](https://travis-ci.org/dcodeIO/long.js.svg)](https://travis-ci.org/dcodeIO/long.js)

Background
----------

As of [ECMA-262 5th Edition](http://ecma262-5.com/ELS5_HTML.htm#Section_8.5), "all the positive and negative integers
whose magnitude is no greater than 2<sup>53</sup> are representable in the Number type", which is "representing the
doubleprecision 64-bit format IEEE 754 values as specified in the IEEE Standard for Binary Floating-Point Arithmetic".
The [maximum safe integer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)
in JavaScript is 2<sup>53</sup>-1.

Example: 2<sup>64</sup>-1 is 1844674407370955**1615** but in JavaScript it evaluates to 1844674407370955**2000**.

Furthermore, bitwise operators in JavaScript "deal only with integers in the range −2<sup>31</sup> through
2<sup>31</sup>−1, inclusive, or in the range 0 through 2<sup>32</sup>−1, inclusive. These operators accept any value of
the Number type but first convert each such value to one of 2<sup>32</sup> integer values."

In some use cases, however, it is required to be able to reliably work with and perform bitwise operations on the full
64 bits. This is where long.js comes into play.

Usage
-----

The class is compatible with CommonJS and AMD loaders and is exposed globally as `Long` if neither is available.

```javascript
var Long = require("long");

var longVal = new Long(0xFFFFFFFF, 0x7FFFFFFF);

console.log(longVal.toString());
...
```

API
---

### Constructor

* new **Long**(low: `number`, high: `number`, unsigned?: `boolean`)<br />
  Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. See the from* functions below for more convenient ways of constructing Longs.

### Fields

* Long#**low**: `number`<br />
  The low 32 bits as a signed value.

* Long#**high**: `number`<br />
  The high 32 bits as a signed value.

* Long#**unsigned**: `boolean`<br />
  Whether unsigned or not.

### Constants

* Long.**ZERO**: `Long`<br />
  Signed zero.

* Long.**ONE**: `Long`<br />
  Signed one.

* Long.**NEG_ONE**: `Long`<br />
  Signed negative one.

* Long.**UZERO**: `Long`<br />
  Unsigned zero.

* Long.**UONE**: `Long`<br />
  Unsigned one.

* Long.**MAX_VALUE**: `Long`<br />
  Maximum signed value.

* Long.**MIN_VALUE**: `Long`<br />
  Minimum signed value.

* Long.**MAX_UNSIGNED_VALUE**: `Long`<br />
  Maximum unsigned value.

### Utility

* Long.**isLong**(obj: `*`): `boolean`<br />
  Tests if the specified object is a Long.

* Long.**fromBits**(lowBits: `number`, highBits: `number`, unsigned?: `boolean`): `Long`<br />
  Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is assumed to use 32 bits.

* Long.**fromBytes**(bytes: `number[]`, unsigned?: `boolean`, le?: `boolean`): `Long`<br />
  Creates a Long from its byte representation.

* Long.**fromBytesLE**(bytes: `number[]`, unsigned?: `boolean`): `Long`<br />
  Creates a Long from its little endian byte representation.

* Long.**fromBytesBE**(bytes: `number[]`, unsigned?: `boolean`): `Long`<br />
  Creates a Long from its big endian byte representation.

* Long.**fromInt**(value: `number`, unsigned?: `boolean`): `Long`<br />
  Returns a Long representing the given 32 bit integer value.

* Long.**fromNumber**(value: `number`, unsigned?: `boolean`): `Long`<br />
  Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.

* Long.**fromString**(str: `string`, unsigned?: `boolean`, radix?: `number`)<br />
  Long.**fromString**(str: `string`, radix: `number`)<br />
  Returns a Long representation of the given string, written using the specified radix.

* Long.**fromValue**(val: `*`, unsigned?: `boolean`): `Long`<br />
  Converts the specified value to a Long using the appropriate from* function for its type.

### Methods

* Long#**add**(addend: `Long | number | string`): `Long`<br />
  Returns the sum of this and the specified Long.

* Long#**and**(other: `Long | number | string`): `Long`<br />
  Returns the bitwise AND of this Long and the specified.

* Long#**compare**/**comp**(other: `Long | number | string`): `number`<br />
  Compares this Long's value with the specified's. Returns `0` if they are the same, `1` if the this is greater and `-1` if the given one is greater.

* Long#**divide**/**div**(divisor: `Long | number | string`): `Long`<br />
  Returns this Long divided by the specified.

* Long#**equals**/**eq**(other: `Long | number | string`): `boolean`<br />
  Tests if this Long's value equals the specified's.

* Long#**getHighBits**(): `number`<br />
  Gets the high 32 bits as a signed integer.

* Long#**getHighBitsUnsigned**(): `number`<br />
  Gets the high 32 bits as an unsigned integer.

* Long#**getLowBits**(): `number`<br />
  Gets the low 32 bits as a signed integer.

* Long#**getLowBitsUnsigned**(): `number`<br />
  Gets the low 32 bits as an unsigned integer.

* Long#**getNumBitsAbs**(): `number`<br />
  Gets the number of bits needed to represent the absolute value of this Long.

* Long#**greaterThan**/**gt**(other: `Long | number | string`): `boolean`<br />
  Tests if this Long's value is greater than the specified's.

* Long#**greaterThanOrEqual**/**gte**/**ge**(other: `Long | number | string`): `boolean`<br />
  Tests if this Long's value is greater than or equal the specified's.

* Long#**isEven**(): `boolean`<br />
  Tests if this Long's value is even.

* Long#**isNegative**(): `boolean`<br />
  Tests if this Long's value is negative.

* Long#**isOdd**(): `boolean`<br />
  Tests if this Long's value is odd.

* Long#**isPositive**(): `boolean`<br />
  Tests if this Long's value is positive.

* Long#**isZero**/**eqz**(): `boolean`<br />
  Tests if this Long's value equals zero.

* Long#**lessThan**/**lt**(other: `Long | number | string`): `boolean`<br />
  Tests if this Long's value is less than the specified's.

* Long#**lessThanOrEqual**/**lte**/**le**(other: `Long | number | string`): `boolean`<br />
  Tests if this Long's value is less than or equal the specified's.

* Long#**modulo**/**mod**/**rem**(divisor: `Long | number | string`): `Long`<br />
  Returns this Long modulo the specified.

* Long#**multiply**/**mul**(multiplier: `Long | number | string`): `Long`<br />
  Returns the product of this and the specified Long.

* Long#**negate**/**neg**(): `Long`<br />
  Negates this Long's value.

* Long#**not**(): `Long`<br />
  Returns the bitwise NOT of this Long.

* Long#**notEquals**/**neq**/**ne**(other: `Long | number | string`): `boolean`<br />
  Tests if this Long's value differs from the specified's.

* Long#**or**(other: `Long | number | string`): `Long`<br />
  Returns the bitwise OR of this Long and the specified.

* Long#**shiftLeft**/**shl**(numBits: `Long | number | string`): `Long`<br />
  Returns this Long with bits shifted to the left by the given amount.

* Long#**shiftRight**/**shr**(numBits: `Long | number | string`): `Long`<br />
  Returns this Long with bits arithmetically shifted to the right by the given amount.

* Long#**shiftRightUnsigned**/**shru**/**shr_u**(numBits: `Long | number | string`): `Long`<br />
  Returns this Long with bits logically shifted to the right by the given amount.

* Long#**subtract**/**sub**(subtrahend: `Long | number | string`): `Long`<br />
  Returns the difference of this and the specified Long.

* Long#**toBytes**(le?: `boolean`): `number[]`<br />
  Converts this Long to its byte representation.

* Long#**toBytesLE**(): `number[]`<br />
  Converts this Long to its little endian byte representation.

* Long#**toBytesBE**(): `number[]`<br />
  Converts this Long to its big endian byte representation.

* Long#**toInt**(): `number`<br />
  Converts the Long to a 32 bit integer, assuming it is a 32 bit integer.

* Long#**toNumber**(): `number`<br />
  Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa).

* Long#**toSigned**(): `Long`<br />
  Converts this Long to signed.

* Long#**toString**(radix?: `number`): `string`<br />
  Converts the Long to a string written in the specified radix.

* Long#**toUnsigned**(): `Long`<br />
  Converts this Long to unsigned.

* Long#**xor**(other: `Long | number | string`): `Long`<br />
  Returns the bitwise XOR of this Long and the given one.

Building
--------

To build an UMD bundle to `dist/long.js`, run:

```
$> npm install
$> npm run build
```

Running the [tests](./tests):

```
$> npm test
```
# emoji-regex [![Build status](https://travis-ci.org/mathiasbynens/emoji-regex.svg?branch=master)](https://travis-ci.org/mathiasbynens/emoji-regex)

_emoji-regex_ offers a regular expression to match all emoji symbols (including textual representations of emoji) as per the Unicode Standard.

This repository contains a script that generates this regular expression based on [the data from Unicode v12](https://github.com/mathiasbynens/unicode-12.0.0). Because of this, the regular expression can easily be updated whenever new emoji are added to the Unicode standard.

## Installation

Via [npm](https://www.npmjs.com/):

```bash
npm install emoji-regex
```

In [Node.js](https://nodejs.org/):

```js
const emojiRegex = require('emoji-regex');
// Note: because the regular expression has the global flag set, this module
// exports a function that returns the regex rather than exporting the regular
// expression itself, to make it impossible to (accidentally) mutate the
// original regular expression.

const text = `
\u{231A}: ⌚ default emoji presentation character (Emoji_Presentation)
\u{2194}\u{FE0F}: ↔️ default text presentation character rendered as emoji
\u{1F469}: 👩 emoji modifier base (Emoji_Modifier_Base)
\u{1F469}\u{1F3FF}: 👩🏿 emoji modifier base followed by a modifier
`;

const regex = emojiRegex();
let match;
while (match = regex.exec(text)) {
  const emoji = match[0];
  console.log(`Matched sequence ${ emoji } — code points: ${ [...emoji].length }`);
}
```

Console output:

```
Matched sequence ⌚ — code points: 1
Matched sequence ⌚ — code points: 1
Matched sequence ↔️ — code points: 2
Matched sequence ↔️ — code points: 2
Matched sequence 👩 — code points: 1
Matched sequence 👩 — code points: 1
Matched sequence 👩🏿 — code points: 2
Matched sequence 👩🏿 — code points: 2
```

To match emoji in their textual representation as well (i.e. emoji that are not `Emoji_Presentation` symbols and that aren’t forced to render as emoji by a variation selector), `require` the other regex:

```js
const emojiRegex = require('emoji-regex/text.js');
```

Additionally, in environments which support ES2015 Unicode escapes, you may `require` ES2015-style versions of the regexes:

```js
const emojiRegex = require('emoji-regex/es2015/index.js');
const emojiRegexText = require('emoji-regex/es2015/text.js');
```

## Author

| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") |
|---|
| [Mathias Bynens](https://mathiasbynens.be/) |

## License

_emoji-regex_ is available under the [MIT](https://mths.be/mit) license.
# axios // helpers

The modules found in `helpers/` should be generic modules that are _not_ specific to the domain logic of axios. These modules could theoretically be published to npm on their own and consumed by other modules or apps. Some examples of generic modules are things like:

- Browser polyfills
- Managing cookies
- Parsing HTTP headers
# [nearley](http://nearley.js.org) ↗️
[![JS.ORG](https://img.shields.io/badge/js.org-nearley-ffb400.svg?style=flat-square)](http://js.org)
[![npm version](https://badge.fury.io/js/nearley.svg)](https://badge.fury.io/js/nearley)

nearley is a simple, fast and powerful parsing toolkit. It consists of:
1. [A powerful, modular DSL for describing
   languages](https://nearley.js.org/docs/grammar)
2. [An efficient, lightweight Earley
   parser](https://nearley.js.org/docs/parser)
3. [Loads of tools, editor plug-ins, and other
   goodies!](https://nearley.js.org/docs/tooling)

nearley is a **streaming** parser with support for catching **errors**
gracefully and providing _all_ parsings for **ambiguous** grammars. It is
compatible with a variety of **lexers** (we recommend
[moo](http://github.com/tjvr/moo)). It comes with tools for creating **tests**,
**railroad diagrams** and **fuzzers** from your grammars, and has support for a
variety of editors and platforms. It works in both node and the browser.

Unlike most other parser generators, nearley can handle *any* grammar you can
define in BNF (and more!). In particular, while most existing JS parsers such
as PEGjs and Jison choke on certain grammars (e.g. [left recursive
ones](http://en.wikipedia.org/wiki/Left_recursion)), nearley handles them
easily and efficiently by using the [Earley parsing
algorithm](https://en.wikipedia.org/wiki/Earley_parser).

nearley is used by a wide variety of projects:

- [artificial
  intelligence](https://github.com/ChalmersGU-AI-course/shrdlite-course-project)
  and
- [computational
  linguistics](https://wiki.eecs.yorku.ca/course_archive/2014-15/W/6339/useful_handouts)
  classes at universities;
- [file format parsers](https://github.com/raymond-h/node-dmi);
- [data-driven markup languages](https://github.com/idyll-lang/idyll-compiler);
- [compilers for real-world programming
  languages](https://github.com/sizigi/lp5562);
- and nearley itself! The nearley compiler is bootstrapped.

nearley is an npm [staff
pick](https://www.npmjs.com/package/npm-collection-staff-picks).

## Documentation

Please visit our website https://nearley.js.org to get started! You will find a
tutorial, detailed reference documents, and links to several real-world
examples to get inspired.

## Contributing

Please read [this document](.github/CONTRIBUTING.md) *before* working on
nearley. If you are interested in contributing but unsure where to start, take
a look at the issues labeled "up for grabs" on the issue tracker, or message a
maintainer (@kach or @tjvr on Github).

nearley is MIT licensed.

A big thanks to Nathan Dinsmore for teaching me how to Earley, Aria Stewart for
helping structure nearley into a mature module, and Robin Windels for
bootstrapping the grammar. Additionally, Jacob Edelman wrote an experimental
JavaScript parser with nearley and contributed ideas for EBNF support. Joshua
T. Corbin refactored the compiler to be much, much prettier. Bojidar Marinov
implemented postprocessors-in-other-languages. Shachar Itzhaky fixed a subtle
bug with nullables.

## Citing nearley

If you are citing nearley in academic work, please use the following BibTeX
entry.

```bibtex
@misc{nearley,
    author = "Kartik Chandra and Tim Radvan",
    title  = "{nearley}: a parsing toolkit for {JavaScript}",
    year   = {2014},
    doi    = {10.5281/zenodo.3897993},
    url    = {https://github.com/kach/nearley}
}
```
# wrappy

Callback wrapping utility

## USAGE

```javascript
var wrappy = require("wrappy")

// var wrapper = wrappy(wrapperFunction)

// make sure a cb is called only once
// See also: http://npm.im/once for this specific use case
var once = wrappy(function (cb) {
  var called = false
  return function () {
    if (called) return
    called = true
    return cb.apply(this, arguments)
  }
})

function printBoo () {
  console.log('boo')
}
// has some rando property
printBoo.iAmBooPrinter = true

var onlyPrintOnce = once(printBoo)

onlyPrintOnce() // prints 'boo'
onlyPrintOnce() // does nothing

// random property is retained!
assert.equal(onlyPrintOnce.iAmBooPrinter, true)
```
# <img src="./logo.png" alt="bn.js" width="160" height="160" />

> BigNum in pure javascript

[![Build Status](https://secure.travis-ci.org/indutny/bn.js.png)](http://travis-ci.org/indutny/bn.js)

## Install
`npm install --save bn.js`

## Usage

```js
const BN = require('bn.js');

var a = new BN('dead', 16);
var b = new BN('101010', 2);

var res = a.add(b);
console.log(res.toString(10));  // 57047
```

**Note**: decimals are not supported in this library.

## Notation

### Prefixes

There are several prefixes to instructions that affect the way the work. Here
is the list of them in the order of appearance in the function name:

* `i` - perform operation in-place, storing the result in the host object (on
  which the method was invoked). Might be used to avoid number allocation costs
* `u` - unsigned, ignore the sign of operands when performing operation, or
  always return positive value. Second case applies to reduction operations
  like `mod()`. In such cases if the result will be negative - modulo will be
  added to the result to make it positive

### Postfixes

* `n` - the argument of the function must be a plain JavaScript
  Number. Decimals are not supported.
* `rn` - both argument and return value of the function are plain JavaScript
  Numbers. Decimals are not supported.

### Examples

* `a.iadd(b)` - perform addition on `a` and `b`, storing the result in `a`
* `a.umod(b)` - reduce `a` modulo `b`, returning positive value
* `a.iushln(13)` - shift bits of `a` left by 13

## Instructions

Prefixes/postfixes are put in parens at the of the line. `endian` - could be
either `le` (little-endian) or `be` (big-endian).

### Utilities

* `a.clone()` - clone number
* `a.toString(base, length)` - convert to base-string and pad with zeroes
* `a.toNumber()` - convert to Javascript Number (limited to 53 bits)
* `a.toJSON()` - convert to JSON compatible hex string (alias of `toString(16)`)
* `a.toArray(endian, length)` - convert to byte `Array`, and optionally zero
  pad to length, throwing if already exceeding
* `a.toArrayLike(type, endian, length)` - convert to an instance of `type`,
  which must behave like an `Array`
* `a.toBuffer(endian, length)` - convert to Node.js Buffer (if available). For
  compatibility with browserify and similar tools, use this instead:
  `a.toArrayLike(Buffer, endian, length)`
* `a.bitLength()` - get number of bits occupied
* `a.zeroBits()` - return number of less-significant consequent zero bits
  (example: `1010000` has 4 zero bits)
* `a.byteLength()` - return number of bytes occupied
* `a.isNeg()` - true if the number is negative
* `a.isEven()` - no comments
* `a.isOdd()` - no comments
* `a.isZero()` - no comments
* `a.cmp(b)` - compare numbers and return `-1` (a `<` b), `0` (a `==` b), or `1` (a `>` b)
  depending on the comparison result (`ucmp`, `cmpn`)
* `a.lt(b)` - `a` less than `b` (`n`)
* `a.lte(b)` - `a` less than or equals `b` (`n`)
* `a.gt(b)` - `a` greater than `b` (`n`)
* `a.gte(b)` - `a` greater than or equals `b` (`n`)
* `a.eq(b)` - `a` equals `b` (`n`)
* `a.toTwos(width)` - convert to two's complement representation, where `width` is bit width
* `a.fromTwos(width)` - convert from two's complement representation, where `width` is the bit width
* `BN.isBN(object)` - returns true if the supplied `object` is a BN.js instance
* `BN.max(a, b)` - return `a` if `a` bigger than `b`
* `BN.min(a, b)` - return `a` if `a` less than `b`

### Arithmetics

* `a.neg()` - negate sign (`i`)
* `a.abs()` - absolute value (`i`)
* `a.add(b)` - addition (`i`, `n`, `in`)
* `a.sub(b)` - subtraction (`i`, `n`, `in`)
* `a.mul(b)` - multiply (`i`, `n`, `in`)
* `a.sqr()` - square (`i`)
* `a.pow(b)` - raise `a` to the power of `b`
* `a.div(b)` - divide (`divn`, `idivn`)
* `a.mod(b)` - reduct (`u`, `n`) (but no `umodn`)
* `a.divmod(b)` - quotient and modulus obtained by dividing
* `a.divRound(b)` - rounded division

### Bit operations

* `a.or(b)` - or (`i`, `u`, `iu`)
* `a.and(b)` - and (`i`, `u`, `iu`, `andln`) (NOTE: `andln` is going to be replaced
  with `andn` in future)
* `a.xor(b)` - xor (`i`, `u`, `iu`)
* `a.setn(b, value)` - set specified bit to `value`
* `a.shln(b)` - shift left (`i`, `u`, `iu`)
* `a.shrn(b)` - shift right (`i`, `u`, `iu`)
* `a.testn(b)` - test if specified bit is set
* `a.maskn(b)` - clear bits with indexes higher or equal to `b` (`i`)
* `a.bincn(b)` - add `1 << b` to the number
* `a.notn(w)` - not (for the width specified by `w`) (`i`)

### Reduction

* `a.gcd(b)` - GCD
* `a.egcd(b)` - Extended GCD results (`{ a: ..., b: ..., gcd: ... }`)
* `a.invm(b)` - inverse `a` modulo `b`

## Fast reduction

When doing lots of reductions using the same modulo, it might be beneficial to
use some tricks: like [Montgomery multiplication][0], or using special algorithm
for [Mersenne Prime][1].

### Reduction context

To enable this tricks one should create a reduction context:

```js
var red = BN.red(num);
```
where `num` is just a BN instance.

Or:

```js
var red = BN.red(primeName);
```

Where `primeName` is either of these [Mersenne Primes][1]:

* `'k256'`
* `'p224'`
* `'p192'`
* `'p25519'`

Or:

```js
var red = BN.mont(num);
```

To reduce numbers with [Montgomery trick][0]. `.mont()` is generally faster than
`.red(num)`, but slower than `BN.red(primeName)`.

### Converting numbers

Before performing anything in reduction context - numbers should be converted
to it. Usually, this means that one should:

* Convert inputs to reducted ones
* Operate on them in reduction context
* Convert outputs back from the reduction context

Here is how one may convert numbers to `red`:

```js
var redA = a.toRed(red);
```
Where `red` is a reduction context created using instructions above

Here is how to convert them back:

```js
var a = redA.fromRed();
```

### Red instructions

Most of the instructions from the very start of this readme have their
counterparts in red context:

* `a.redAdd(b)`, `a.redIAdd(b)`
* `a.redSub(b)`, `a.redISub(b)`
* `a.redShl(num)`
* `a.redMul(b)`, `a.redIMul(b)`
* `a.redSqr()`, `a.redISqr()`
* `a.redSqrt()` - square root modulo reduction context's prime
* `a.redInvm()` - modular inverse of the number
* `a.redNeg()`
* `a.redPow(b)` - modular exponentiation

### Number Size

Optimized for elliptic curves that work with 256-bit numbers.
There is no limitation on the size of the numbers.

## LICENSE

This software is licensed under the MIT License.

[0]: https://en.wikipedia.org/wiki/Montgomery_modular_multiplication
[1]: https://en.wikipedia.org/wiki/Mersenne_prime
Railroad-diagram Generator
==========================

This is a small js library for generating railroad diagrams
(like what [JSON.org](http://json.org) uses)
using SVG.

Railroad diagrams are a way of visually representing a grammar
in a form that is more readable than using regular expressions or BNF.
I think (though I haven't given it a lot of thought yet) that if it's easy to write a context-free grammar for the language,
the corresponding railroad diagram will be easy as well.

There are several railroad-diagram generators out there, but none of them had the visual appeal I wanted.
[Here's an example of how they look!](http://www.xanthir.com/etc/railroad-diagrams/example.html)
And [here's an online generator for you to play with and get SVG code from!](http://www.xanthir.com/etc/railroad-diagrams/generator.html)

The library now exists in a Python port as well!  See the information further down.

Details
-------

To use the library, just include the js and css files, and then call the Diagram() function.
Its arguments are the components of the diagram (Diagram is a special form of Sequence).
An alternative to Diagram() is ComplexDiagram() which is used to describe a complex type diagram.
Components are either leaves or containers.

The leaves:
* Terminal(text) or a bare string - represents literal text
* NonTerminal(text) - represents an instruction or another production
* Comment(text) - a comment
* Skip() - an empty line

The containers:
* Sequence(children) - like simple concatenation in a regex
* Choice(index, children) - like | in a regex.  The index argument specifies which child is the "normal" choice and should go in the middle
* Optional(child, skip) - like ? in a regex.  A shorthand for `Choice(1, [Skip(), child])`.  If the optional `skip` parameter has the value `"skip"`, it instead puts the Skip() in the straight-line path, for when the "normal" behavior is to omit the item.
* OneOrMore(child, repeat) - like + in a regex.  The 'repeat' argument is optional, and specifies something that must go between the repetitions.
* ZeroOrMore(child, repeat, skip) - like * in a regex.  A shorthand for `Optional(OneOrMore(child, repeat))`.  The optional `skip` parameter is identical to Optional().

For convenience, each component can be called with or without `new`.
If called without `new`,
the container components become n-ary;
that is, you can say either `new Sequence([A, B])` or just `Sequence(A,B)`.

After constructing a Diagram, call `.format(...padding)` on it, specifying 0-4 padding values (just like CSS) for some additional "breathing space" around the diagram (the paddings default to 20px).

The result can either be `.toString()`'d for the markup, or `.toSVG()`'d for an `<svg>` element, which can then be immediately inserted to the document.  As a convenience, Diagram also has an `.addTo(element)` method, which immediately converts it to SVG and appends it to the referenced element with default paddings. `element` defaults to `document.body`.

Options
-------

There are a few options you can tweak, at the bottom of the file.  Just tweak either until the diagram looks like what you want.
You can also change the CSS file - feel free to tweak to your heart's content.
Note, though, that if you change the text sizes in the CSS,
you'll have to go adjust the metrics for the leaf nodes as well.

* VERTICAL_SEPARATION - sets the minimum amount of vertical separation between two items.  Note that the stroke width isn't counted when computing the separation; this shouldn't be relevant unless you have a very small separation or very large stroke width.
* ARC_RADIUS - the radius of the arcs used in the branching containers like Choice.  This has a relatively large effect on the size of non-trivial diagrams.  Both tight and loose values look good, depending on what you're going for.
* DIAGRAM_CLASS - the class set on the root `<svg>` element of each diagram, for use in the CSS stylesheet.
* STROKE_ODD_PIXEL_LENGTH - the default stylesheet uses odd pixel lengths for 'stroke'. Due to rasterization artifacts, they look best when the item has been translated half a pixel in both directions. If you change the styling to use a stroke with even pixel lengths, you'll want to set this variable to `false`.
* INTERNAL_ALIGNMENT - when some branches of a container are narrower than others, this determines how they're aligned in the extra space.  Defaults to "center", but can be set to "left" or "right".

Caveats
-------

At this early stage, the generator is feature-complete and works as intended, but still has several TODOs:

* The font-sizes are hard-coded right now, and the font handling in general is very dumb - I'm just guessing at some metrics that are probably "good enough" rather than measuring things properly.

Python Port
-----------

In addition to the canonical JS version, the library now exists as a Python library as well.

Using it is basically identical.  The config variables are globals in the file, and so may be adjusted either manually or via tweaking from inside your program.

The main difference from the JS port is how you extract the string from the Diagram.  You'll find a `writeSvg(writerFunc)` method on `Diagram`, which takes a callback of one argument and passes it the string form of the diagram.  For example, it can be used like `Diagram(...).writeSvg(sys.stdout.write)` to write to stdout.  **Note**: the callback will be called multiple times as it builds up the string, not just once with the whole thing.  If you need it all at once, consider something like a `StringIO` as an easy way to collect it into a single string.

License
-------

This document and all associated files in the github project are licensed under [CC0](http://creativecommons.org/publicdomain/zero/1.0/) ![](http://i.creativecommons.org/p/zero/1.0/80x15.png).
This means you can reuse, remix, or otherwise appropriate this project for your own use **without restriction**.
(The actual legal meaning can be found at the above link.)
Don't ask me for permission to use any part of this project, **just use it**.
I would appreciate attribution, but that is not required by the license.
# axios // adapters

The modules under `adapters/` are modules that handle dispatching a request and settling a returned `Promise` once a response is received.

## Example

```js
var settle = require('./../core/settle');

module.exports = function myAdapter(config) {
  // At this point:
  //  - config has been merged with defaults
  //  - request transformers have already run
  //  - request interceptors have already run
  
  // Make the request using config provided
  // Upon response settle the Promise

  return new Promise(function(resolve, reject) {
  
    var response = {
      data: responseData,
      status: request.status,
      statusText: request.statusText,
      headers: responseHeaders,
      config: config,
      request: request
    };

    settle(resolve, reject, response);

    // From here:
    //  - response transformers will run
    //  - response interceptors will run
  });
}
```
# Regular Expression Tokenizer

Tokenizes strings that represent a regular expressions.

[![Build Status](https://secure.travis-ci.org/fent/ret.js.svg)](http://travis-ci.org/fent/ret.js)
[![Dependency Status](https://david-dm.org/fent/ret.js.svg)](https://david-dm.org/fent/ret.js)
[![codecov](https://codecov.io/gh/fent/ret.js/branch/master/graph/badge.svg)](https://codecov.io/gh/fent/ret.js)

# Usage

```js
var ret = require('ret');

var tokens = ret(/foo|bar/.source);
```

`tokens` will contain the following object

```js
{
  "type": ret.types.ROOT
  "options": [
    [ { "type": ret.types.CHAR, "value", 102 },
      { "type": ret.types.CHAR, "value", 111 },
      { "type": ret.types.CHAR, "value", 111 } ],
    [ { "type": ret.types.CHAR, "value",  98 },
      { "type": ret.types.CHAR, "value",  97 },
      { "type": ret.types.CHAR, "value", 114 } ]
  ]
}
```

# Token Types

`ret.types` is a collection of the various token types exported by ret.

### ROOT

Only used in the root of the regexp. This is needed due to the posibility of the root containing a pipe `|` character. In that case, the token will have an `options` key that will be an array of arrays of tokens. If not, it will contain a `stack` key that is an array of tokens.

```js
{
  "type": ret.types.ROOT,
  "stack": [token1, token2...],
}
```

```js
{
  "type": ret.types.ROOT,
  "options" [
    [token1, token2...],
    [othertoken1, othertoken2...]
    ...
  ],
}
```

### GROUP

Groups contain tokens that are inside of a parenthesis. If the group begins with `?` followed by another character, it's a special type of group. A ':' tells the group not to be remembered when `exec` is used. '=' means the previous token matches only if followed by this group, and '!' means the previous token matches only if NOT followed.

Like root, it can contain an `options` key instead of `stack` if there is a pipe.

```js
{
  "type": ret.types.GROUP,
  "remember" true,
  "followedBy": false,
  "notFollowedBy": false,
  "stack": [token1, token2...],
}
```

```js
{
  "type": ret.types.GROUP,
  "remember" true,
  "followedBy": false,
  "notFollowedBy": false,
  "options" [
    [token1, token2...],
    [othertoken1, othertoken2...]
    ...
  ],
}
```

### POSITION

`\b`, `\B`, `^`, and `$` specify positions in the regexp.

```js
{
  "type": ret.types.POSITION,
  "value": "^",
}
```

### SET

Contains a key `set` specifying what tokens are allowed and a key `not` specifying if the set should be negated. A set can contain other sets, ranges, and characters.

```js
{
  "type": ret.types.SET,
  "set": [token1, token2...],
  "not": false,
}
```

### RANGE

Used in set tokens to specify a character range. `from` and `to` are character codes.

```js
{
  "type": ret.types.RANGE,
  "from": 97,
  "to": 122,
}
```

### REPETITION

```js
{
  "type": ret.types.REPETITION,
  "min": 0,
  "max": Infinity,
  "value": token,
}
```

### REFERENCE

References a group token. `value` is 1-9.

```js
{
  "type": ret.types.REFERENCE,
  "value": 1,
}
```

### CHAR

Represents a single character token. `value` is the character code. This might seem a bit cluttering instead of concatenating characters together. But since repetition tokens only repeat the last token and not the last clause like the pipe, it's simpler to do it this way.

```js
{
  "type": ret.types.CHAR,
  "value": 123,
}
```

## Errors

ret.js will throw errors if given a string with an invalid regular expression. All possible errors are

* Invalid group. When a group with an immediate `?` character is followed by an invalid character. It can only be followed by `!`, `=`, or `:`. Example: `/(?_abc)/`
* Nothing to repeat. Thrown when a repetitional token is used as the first token in the current clause, as in right in the beginning of the regexp or group, or right after a pipe. Example: `/foo|?bar/`, `/{1,3}foo|bar/`, `/foo(+bar)/`
* Unmatched ). A group was not opened, but was closed. Example: `/hello)2u/`
* Unterminated group. A group was not closed. Example: `/(1(23)4/`
* Unterminated character class. A custom character set was not closed. Example: `/[abc/`

# Install

    npm install ret

# Tests

Tests are written with [vows](http://vowsjs.org/)

```bash
npm test
```

# License

MIT
# universal-url [![NPM Version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Dependency Monitor][greenkeeper-image]][greenkeeper-url]

> WHATWG [`URL`](https://developer.mozilla.org/en/docs/Web/API/URL) for Node & Browser.

* For Node.js versions `>= 8`, the native implementation will be used.
* For Node.js versions `< 8`, a [shim](https://npmjs.com/whatwg-url) will be used.
* For web browsers without a native implementation, the same shim will be used.

## Installation

[Node.js](http://nodejs.org/) `>= 6` is required. To install, type this at the command line:
```shell
npm install universal-url
```

## Usage

```js
const {URL, URLSearchParams} = require('universal-url');

const url = new URL('http://domain/');
const params = new URLSearchParams('?param=value');
```

Global shim:
```js
require('universal-url').shim();

const url = new URL('http://domain/');
const params = new URLSearchParams('?param=value');
```

## Browserify/etc

The bundled file size of this library can be large for a web browser. If this is a problem, try using [universal-url-lite](https://npmjs.com/universal-url-lite) in your build as an alias for this module.

[npm-image]: https://img.shields.io/npm/v/universal-url.svg
[npm-url]: https://npmjs.org/package/universal-url
[travis-image]: https://img.shields.io/travis/stevenvachon/universal-url.svg
[travis-url]: https://travis-ci.org/stevenvachon/universal-url
[greenkeeper-image]: https://badges.greenkeeper.io/stevenvachon/universal-url.svg
[greenkeeper-url]: https://greenkeeper.io/
# binary-install

Install .tar.gz binary applications via npm

## Usage

This library provides a single class `Binary` that takes a download url and some optional arguments. You **must** provide either `name` or `installDirectory` when creating your `Binary`.

| option           | decription                                    |
| ---------------- | --------------------------------------------- |
| name             | The name of your binary                       |
| installDirectory | A path to the directory to install the binary |

If an `installDirectory` is not provided, the binary will be installed at your OS specific config directory. On MacOS it defaults to `~/Library/Preferences/${name}-nodejs`

After your `Binary` has been created, you can run `.install()` to install the binary, and `.run()` to run it.

### Example

This is meant to be used as a library - create your `Binary` with your desired options, then call `.install()` in the `postinstall` of your `package.json`, `.run()` in the `bin` section of your `package.json`, and `.uninstall()` in the `preuninstall` section of your `package.json`. See [this example project](/example) to see how to create an npm package that installs and runs a binary using the Github releases API.
# which-module

> Find the module object for something that was require()d

[![Build Status](https://travis-ci.org/nexdrew/which-module.svg?branch=master)](https://travis-ci.org/nexdrew/which-module)
[![Coverage Status](https://coveralls.io/repos/github/nexdrew/which-module/badge.svg?branch=master)](https://coveralls.io/github/nexdrew/which-module?branch=master)
[![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version)

Find the `module` object in `require.cache` for something that was `require()`d
or `import`ed - essentially a reverse `require()` lookup.

Useful for libs that want to e.g. lookup a filename for a module or submodule
that it did not `require()` itself.

## Install and Usage

```
npm install --save which-module
```

```js
const whichModule = require('which-module')

console.log(whichModule(require('something')))
// Module {
//   id: '/path/to/project/node_modules/something/index.js',
//   exports: [Function],
//   parent: ...,
//   filename: '/path/to/project/node_modules/something/index.js',
//   loaded: true,
//   children: [],
//   paths: [ '/path/to/project/node_modules/something/node_modules',
//            '/path/to/project/node_modules',
//            '/path/to/node_modules',
//            '/path/node_modules',
//            '/node_modules' ] }
```

## API

### `whichModule(exported)`

Return the [`module` object](https://nodejs.org/api/modules.html#modules_the_module_object),
if any, that represents the given argument in the `require.cache`.

`exported` can be anything that was previously `require()`d or `import`ed as a
module, submodule, or dependency - which means `exported` is identical to the
`module.exports` returned by this method.

If `exported` did not come from the `exports` of a `module` in `require.cache`,
then this method returns `null`.

## License

ISC © Contributors
# debug
[![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug)  [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master)  [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers)
[![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors)

<img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png">

A tiny JavaScript debugging utility modelled after Node.js core's debugging
technique. Works in Node.js and web browsers.

## Installation

```bash
$ npm install debug
```

## Usage

`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole.

Example [_app.js_](./examples/node/app.js):

```js
var debug = require('debug')('http')
  , http = require('http')
  , name = 'My App';

// fake app

debug('booting %o', name);

http.createServer(function(req, res){
  debug(req.method + ' ' + req.url);
  res.end('hello\n');
}).listen(3000, function(){
  debug('listening');
});

// fake worker of some kind

require('./worker');
```

Example [_worker.js_](./examples/node/worker.js):

```js
var a = require('debug')('worker:a')
  , b = require('debug')('worker:b');

function work() {
  a('doing lots of uninteresting work');
  setTimeout(work, Math.random() * 1000);
}

work();

function workb() {
  b('doing some work');
  setTimeout(workb, Math.random() * 2000);
}

workb();
```

The `DEBUG` environment variable is then used to enable these based on space or
comma-delimited names.

Here are some examples:

<img width="647" alt="screen shot 2017-08-08 at 12 53 04 pm" src="https://user-images.githubusercontent.com/71256/29091703-a6302cdc-7c38-11e7-8304-7c0b3bc600cd.png">
<img width="647" alt="screen shot 2017-08-08 at 12 53 38 pm" src="https://user-images.githubusercontent.com/71256/29091700-a62a6888-7c38-11e7-800b-db911291ca2b.png">
<img width="647" alt="screen shot 2017-08-08 at 12 53 25 pm" src="https://user-images.githubusercontent.com/71256/29091701-a62ea114-7c38-11e7-826a-2692bedca740.png">

#### Windows note

On Windows the environment variable is set using the `set` command.

```cmd
set DEBUG=*,-not_this
```

Note that PowerShell uses different syntax to set environment variables.

```cmd
$env:DEBUG = "*,-not_this"
```

Then, run the program to be debugged as usual.

## Namespace Colors

Every debug instance has a color generated for it based on its namespace name.
This helps when visually parsing the debug output to identify which debug instance
a debug line belongs to.

#### Node.js

In Node.js, colors are enabled when stderr is a TTY. You also _should_ install
the [`supports-color`](https://npmjs.org/supports-color) module alongside debug,
otherwise debug will only use a small handful of basic colors.

<img width="521" src="https://user-images.githubusercontent.com/71256/29092181-47f6a9e6-7c3a-11e7-9a14-1928d8a711cd.png">

#### Web Browser

Colors are also enabled on "Web Inspectors" that understand the `%c` formatting
option. These are WebKit web inspectors, Firefox ([since version
31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/))
and the Firebug plugin for Firefox (any version).

<img width="524" src="https://user-images.githubusercontent.com/71256/29092033-b65f9f2e-7c39-11e7-8e32-f6f0d8e865c1.png">

## Millisecond diff

When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls.

<img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png">

When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below:

<img width="647" src="https://user-images.githubusercontent.com/71256/29091956-6bd78372-7c39-11e7-8c55-c948396d6edd.png">

## Conventions

If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser".  If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable.  You can then use it for normal output as well as debug output.

## Wildcards

The `*` character may be used as a wildcard. Suppose for example your library has
debuggers named "connect:bodyParser", "connect:compress", "connect:session",
instead of listing all three with
`DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do
`DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`.

You can also exclude specific debuggers by prefixing them with a "-" character.
For example, `DEBUG=*,-connect:*` would include all debuggers except those
starting with "connect:".

## Environment Variables

When running through Node.js, you can set a few environment variables that will
change the behavior of the debug logging:

| Name      | Purpose                                         |
|-----------|-------------------------------------------------|
| `DEBUG`   | Enables/disables specific debugging namespaces. |
| `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY).  |
| `DEBUG_COLORS`| Whether or not to use colors in the debug output. |
| `DEBUG_DEPTH` | Object inspection depth.                    |
| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. |

__Note:__ The environment variables beginning with `DEBUG_` end up being
converted into an Options object that gets used with `%o`/`%O` formatters.
See the Node.js documentation for
[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options)
for the complete list.

## Formatters

Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting.
Below are the officially supported formatters:

| Formatter | Representation |
|-----------|----------------|
| `%O`      | Pretty-print an Object on multiple lines. |
| `%o`      | Pretty-print an Object all on a single line. |
| `%s`      | String. |
| `%d`      | Number (both integer and float). |
| `%j`      | JSON. Replaced with the string '[Circular]' if the argument contains circular references. |
| `%%`      | Single percent sign ('%'). This does not consume an argument. |

### Custom formatters

You can add custom formatters by extending the `debug.formatters` object.
For example, if you wanted to add support for rendering a Buffer as hex with
`%h`, you could do something like:

```js
const createDebug = require('debug')
createDebug.formatters.h = (v) => {
  return v.toString('hex')
}

// …elsewhere
const debug = createDebug('foo')
debug('this is hex: %h', new Buffer('hello world'))
//   foo this is hex: 68656c6c6f20776f726c6421 +0ms
```

## Browser Support

You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify),
or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest),
if you don't want to build it yourself.

Debug's enable state is currently persisted by `localStorage`.
Consider the situation shown below where you have `worker:a` and `worker:b`,
and wish to debug both. You can enable this using `localStorage.debug`:

```js
localStorage.debug = 'worker:*'
```

And then refresh the page.

```js
a = debug('worker:a');
b = debug('worker:b');

setInterval(function(){
  a('doing some work');
}, 1000);

setInterval(function(){
  b('doing some work');
}, 1200);
```

## Output streams

  By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method:

Example [_stdout.js_](./examples/node/stdout.js):

```js
var debug = require('debug');
var error = debug('app:error');

// by default stderr is used
error('goes to stderr!');

var log = debug('app:log');
// set this namespace to log via console.log
log.log = console.log.bind(console); // don't forget to bind to console!
log('goes to stdout');
error('still goes to stderr!');

// set all output to go via console.info
// overrides all per-namespace log settings
debug.log = console.info.bind(console);
error('now goes to stdout via console.info');
log('still goes to stdout, but via console.info now');
```

## Checking whether a debug target is enabled

After you've created a debug instance, you can determine whether or not it is
enabled by checking the `enabled` property:

```javascript
const debug = require('debug')('http');

if (debug.enabled) {
  // do stuff...
}
```

You can also manually toggle this property to force the debug instance to be
enabled or disabled.

## Authors

 - TJ Holowaychuk
 - Nathan Rajlich
 - Andrew Rhyne

## Backers

Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)]

<a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a>

## Sponsors

Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)]

<a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a>

## License

(The MIT License)

Copyright (c) 2014-2017 TJ Holowaychuk &lt;tj@vision-media.ca&gt;

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# node-tar

[![Build Status](https://travis-ci.org/npm/node-tar.svg?branch=master)](https://travis-ci.org/npm/node-tar)

[Fast](./benchmarks) and full-featured Tar for Node.js

The API is designed to mimic the behavior of `tar(1)` on unix systems.
If you are familiar with how tar works, most of this will hopefully be
straightforward for you.  If not, then hopefully this module can teach
you useful unix skills that may come in handy someday :)

## Background

A "tar file" or "tarball" is an archive of file system entries
(directories, files, links, etc.)  The name comes from "tape archive".
If you run `man tar` on almost any Unix command line, you'll learn
quite a bit about what it can do, and its history.

Tar has 5 main top-level commands:

* `c` Create an archive
* `r` Replace entries within an archive
* `u` Update entries within an archive (ie, replace if they're newer)
* `t` List out the contents of an archive
* `x` Extract an archive to disk

The other flags and options modify how this top level function works.

## High-Level API

These 5 functions are the high-level API.  All of them have a
single-character name (for unix nerds familiar with `tar(1)`) as well
as a long name (for everyone else).

All the high-level functions take the following arguments, all three
of which are optional and may be omitted.

1. `options` - An optional object specifying various options
2. `paths` - An array of paths to add or extract
3. `callback` - Called when the command is completed, if async.  (If
   sync or no file specified, providing a callback throws a
   `TypeError`.)

If the command is sync (ie, if `options.sync=true`), then the
callback is not allowed, since the action will be completed immediately.

If a `file` argument is specified, and the command is async, then a
`Promise` is returned.  In this case, if async, a callback may be
provided which is called when the command is completed.

If a `file` option is not specified, then a stream is returned.  For
`create`, this is a readable stream of the generated archive.  For
`list` and `extract` this is a writable stream that an archive should
be written into.  If a file is not specified, then a callback is not
allowed, because you're already getting a stream to work with.

`replace` and `update` only work on existing archives, and so require
a `file` argument.

Sync commands without a file argument return a stream that acts on its
input immediately in the same tick.  For readable streams, this means
that all of the data is immediately available by calling
`stream.read()`.  For writable streams, it will be acted upon as soon
as it is provided, but this can be at any time.

### Warnings and Errors

Tar emits warnings and errors for recoverable and unrecoverable situations,
respectively.  In many cases, a warning only affects a single entry in an
archive, or is simply informing you that it's modifying an entry to comply
with the settings provided.

Unrecoverable warnings will always raise an error (ie, emit `'error'` on
streaming actions, throw for non-streaming sync actions, reject the
returned Promise for non-streaming async operations, or call a provided
callback with an `Error` as the first argument).  Recoverable errors will
raise an error only if `strict: true` is set in the options.

Respond to (recoverable) warnings by listening to the `warn` event.
Handlers receive 3 arguments:

- `code` String.  One of the error codes below.  This may not match
  `data.code`, which preserves the original error code from fs and zlib.
- `message` String.  More details about the error.
- `data` Metadata about the error.  An `Error` object for errors raised by
  fs and zlib.  All fields are attached to errors raisd by tar.  Typically
  contains the following fields, as relevant:
  - `tarCode` The tar error code.
  - `code` Either the tar error code, or the error code set by the
    underlying system.
  - `file` The archive file being read or written.
  - `cwd` Working directory for creation and extraction operations.
  - `entry` The entry object (if it could be created) for `TAR_ENTRY_INFO`,
    `TAR_ENTRY_INVALID`, and `TAR_ENTRY_ERROR` warnings.
  - `header` The header object (if it could be created, and the entry could
    not be created) for `TAR_ENTRY_INFO` and `TAR_ENTRY_INVALID` warnings.
  - `recoverable` Boolean.  If `false`, then the warning will emit an
    `error`, even in non-strict mode.

#### Error Codes

* `TAR_ENTRY_INFO`  An informative error indicating that an entry is being
  modified, but otherwise processed normally.  For example, removing `/` or
  `C:\` from absolute paths if `preservePaths` is not set.

* `TAR_ENTRY_INVALID` An indication that a given entry is not a valid tar
  archive entry, and will be skipped.  This occurs when:
  - a checksum fails,
  - a `linkpath` is missing for a link type, or
  - a `linkpath` is provided for a non-link type.

  If every entry in a parsed archive raises an `TAR_ENTRY_INVALID` error,
  then the archive is presumed to be unrecoverably broken, and
  `TAR_BAD_ARCHIVE` will be raised.

* `TAR_ENTRY_ERROR` The entry appears to be a valid tar archive entry, but
  encountered an error which prevented it from being unpacked.  This occurs
  when:
  - an unrecoverable fs error happens during unpacking,
  - an entry has `..` in the path and `preservePaths` is not set, or
  - an entry is extracting through a symbolic link, when `preservePaths` is
    not set.

* `TAR_ENTRY_UNSUPPORTED`  An indication that a given entry is
  a valid archive entry, but of a type that is unsupported, and so will be
  skipped in archive creation or extracting.

* `TAR_ABORT`  When parsing gzipped-encoded archives, the parser will
  abort the parse process raise a warning for any zlib errors encountered.
  Aborts are considered unrecoverable for both parsing and unpacking.

* `TAR_BAD_ARCHIVE`  The archive file is totally hosed.  This can happen for
  a number of reasons, and always occurs at the end of a parse or extract:

  - An entry body was truncated before seeing the full number of bytes.
  - The archive contained only invalid entries, indicating that it is
    likely not an archive, or at least, not an archive this library can
    parse.

  `TAR_BAD_ARCHIVE` is considered informative for parse operations, but
  unrecoverable for extraction.  Note that, if encountered at the end of an
  extraction, tar WILL still have extracted as much it could from the
  archive, so there may be some garbage files to clean up.

Errors that occur deeper in the system (ie, either the filesystem or zlib)
will have their error codes left intact, and a `tarCode` matching one of
the above will be added to the warning metadata or the raised error object.

Errors generated by tar will have one of the above codes set as the
`error.code` field as well, but since errors originating in zlib or fs will
have their original codes, it's better to read `error.tarCode` if you wish
to see how tar is handling the issue.

### Examples

The API mimics the `tar(1)` command line functionality, with aliases
for more human-readable option and function names.  The goal is that
if you know how to use `tar(1)` in Unix, then you know how to use
`require('tar')` in JavaScript.

To replicate `tar czf my-tarball.tgz files and folders`, you'd do:

```js
tar.c(
  {
    gzip: <true|gzip options>,
    file: 'my-tarball.tgz'
  },
  ['some', 'files', 'and', 'folders']
).then(_ => { .. tarball has been created .. })
```

To replicate `tar cz files and folders > my-tarball.tgz`, you'd do:

```js
tar.c( // or tar.create
  {
    gzip: <true|gzip options>
  },
  ['some', 'files', 'and', 'folders']
).pipe(fs.createWriteStream('my-tarball.tgz'))
```

To replicate `tar xf my-tarball.tgz` you'd do:

```js
tar.x(  // or tar.extract(
  {
    file: 'my-tarball.tgz'
  }
).then(_=> { .. tarball has been dumped in cwd .. })
```

To replicate `cat my-tarball.tgz | tar x -C some-dir --strip=1`:

```js
fs.createReadStream('my-tarball.tgz').pipe(
  tar.x({
    strip: 1,
    C: 'some-dir' // alias for cwd:'some-dir', also ok
  })
)
```

To replicate `tar tf my-tarball.tgz`, do this:

```js
tar.t({
  file: 'my-tarball.tgz',
  onentry: entry => { .. do whatever with it .. }
})
```

To replicate `cat my-tarball.tgz | tar t` do:

```js
fs.createReadStream('my-tarball.tgz')
  .pipe(tar.t())
  .on('entry', entry => { .. do whatever with it .. })
```

To do anything synchronous, add `sync: true` to the options.  Note
that sync functions don't take a callback and don't return a promise.
When the function returns, it's already done.  Sync methods without a
file argument return a sync stream, which flushes immediately.  But,
of course, it still won't be done until you `.end()` it.

To filter entries, add `filter: <function>` to the options.
Tar-creating methods call the filter with `filter(path, stat)`.
Tar-reading methods (including extraction) call the filter with
`filter(path, entry)`.  The filter is called in the `this`-context of
the `Pack` or `Unpack` stream object.

The arguments list to `tar t` and `tar x` specify a list of filenames
to extract or list, so they're equivalent to a filter that tests if
the file is in the list.

For those who _aren't_ fans of tar's single-character command names:

```
tar.c === tar.create
tar.r === tar.replace (appends to archive, file is required)
tar.u === tar.update (appends if newer, file is required)
tar.x === tar.extract
tar.t === tar.list
```

Keep reading for all the command descriptions and options, as well as
the low-level API that they are built on.

### tar.c(options, fileList, callback) [alias: tar.create]

Create a tarball archive.

The `fileList` is an array of paths to add to the tarball.  Adding a
directory also adds its children recursively.

An entry in `fileList` that starts with an `@` symbol is a tar archive
whose entries will be added.  To add a file that starts with `@`,
prepend it with `./`.

The following options are supported:

- `file` Write the tarball archive to the specified filename.  If this
  is specified, then the callback will be fired when the file has been
  written, and a promise will be returned that resolves when the file
  is written.  If a filename is not specified, then a Readable Stream
  will be returned which will emit the file data. [Alias: `f`]
- `sync` Act synchronously.  If this is set, then any provided file
  will be fully written after the call to `tar.c`.  If this is set,
  and a file is not provided, then the resulting stream will already
  have the data ready to `read` or `emit('data')` as soon as you
  request it.
- `onwarn` A function that will get called with `(code, message, data)` for
  any warnings encountered.  (See "Warnings and Errors")
- `strict` Treat warnings as crash-worthy errors.  Default false.
- `cwd` The current working directory for creating the archive.
  Defaults to `process.cwd()`.  [Alias: `C`]
- `prefix` A path portion to prefix onto the entries in the archive.
- `gzip` Set to any truthy value to create a gzipped archive, or an
  object with settings for `zlib.Gzip()` [Alias: `z`]
- `filter` A function that gets called with `(path, stat)` for each
  entry being added.  Return `true` to add the entry to the archive,
  or `false` to omit it.
- `portable` Omit metadata that is system-specific: `ctime`, `atime`,
  `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`.  Note
  that `mtime` is still included, because this is necessary for other
  time-based operations.  Additionally, `mode` is set to a "reasonable
  default" for most unix systems, based on a `umask` value of `0o22`.
- `preservePaths` Allow absolute paths.  By default, `/` is stripped
  from absolute paths. [Alias: `P`]
- `mode` The mode to set on the created file archive
- `noDirRecurse` Do not recursively archive the contents of
  directories. [Alias: `n`]
- `follow` Set to true to pack the targets of symbolic links.  Without
  this option, symbolic links are archived as such. [Alias: `L`, `h`]
- `noPax` Suppress pax extended headers.  Note that this means that
  long paths and linkpaths will be truncated, and large or negative
  numeric values may be interpreted incorrectly.
- `noMtime` Set to true to omit writing `mtime` values for entries.
  Note that this prevents using other mtime-based features like
  `tar.update` or the `keepNewer` option with the resulting tar archive.
  [Alias: `m`, `no-mtime`]
- `mtime` Set to a `Date` object to force a specific `mtime` for
  everything added to the archive.  Overridden by `noMtime`.

The following options are mostly internal, but can be modified in some
advanced use cases, such as re-using caches between runs.

- `linkCache` A Map object containing the device and inode value for
  any file whose nlink is > 1, to identify hard links.
- `statCache` A Map object that caches calls `lstat`.
- `readdirCache` A Map object that caches calls to `readdir`.
- `jobs` A number specifying how many concurrent jobs to run.
  Defaults to 4.
- `maxReadSize` The maximum buffer size for `fs.read()` operations.
  Defaults to 16 MB.

### tar.x(options, fileList, callback) [alias: tar.extract]

Extract a tarball archive.

The `fileList` is an array of paths to extract from the tarball.  If
no paths are provided, then all the entries are extracted.

If the archive is gzipped, then tar will detect this and unzip it.

Note that all directories that are created will be forced to be
writable, readable, and listable by their owner, to avoid cases where
a directory prevents extraction of child entries by virtue of its
mode.

Most extraction errors will cause a `warn` event to be emitted.  If
the `cwd` is missing, or not a directory, then the extraction will
fail completely.

The following options are supported:

- `cwd` Extract files relative to the specified directory.  Defaults
  to `process.cwd()`.  If provided, this must exist and must be a
  directory. [Alias: `C`]
- `file` The archive file to extract.  If not specified, then a
  Writable stream is returned where the archive data should be
  written. [Alias: `f`]
- `sync` Create files and directories synchronously.
- `strict` Treat warnings as crash-worthy errors.  Default false.
- `filter` A function that gets called with `(path, entry)` for each
  entry being unpacked.  Return `true` to unpack the entry from the
  archive, or `false` to skip it.
- `newer` Set to true to keep the existing file on disk if it's newer
  than the file in the archive. [Alias: `keep-newer`,
  `keep-newer-files`]
- `keep` Do not overwrite existing files.  In particular, if a file
  appears more than once in an archive, later copies will not
  overwrite earlier copies. [Alias: `k`, `keep-existing`]
- `preservePaths` Allow absolute paths, paths containing `..`, and
  extracting through symbolic links.  By default, `/` is stripped from
  absolute paths, `..` paths are not extracted, and any file whose
  location would be modified by a symbolic link is not extracted.
  [Alias: `P`]
- `unlink` Unlink files before creating them.  Without this option,
  tar overwrites existing files, which preserves existing hardlinks.
  With this option, existing hardlinks will be broken, as will any
  symlink that would affect the location of an extracted file. [Alias:
  `U`]
- `strip` Remove the specified number of leading path elements.
  Pathnames with fewer elements will be silently skipped.  Note that
  the pathname is edited after applying the filter, but before
  security checks. [Alias: `strip-components`, `stripComponents`]
- `onwarn` A function that will get called with `(code, message, data)` for
  any warnings encountered.  (See "Warnings and Errors")
- `preserveOwner` If true, tar will set the `uid` and `gid` of
  extracted entries to the `uid` and `gid` fields in the archive.
  This defaults to true when run as root, and false otherwise.  If
  false, then files and directories will be set with the owner and
  group of the user running the process.  This is similar to `-p` in
  `tar(1)`, but ACLs and other system-specific data is never unpacked
  in this implementation, and modes are set by default already.
  [Alias: `p`]
- `uid` Set to a number to force ownership of all extracted files and
  folders, and all implicitly created directories, to be owned by the
  specified user id, regardless of the `uid` field in the archive.
  Cannot be used along with `preserveOwner`.  Requires also setting a
  `gid` option.
- `gid` Set to a number to force ownership of all extracted files and
  folders, and all implicitly created directories, to be owned by the
  specified group id, regardless of the `gid` field in the archive.
  Cannot be used along with `preserveOwner`.  Requires also setting a
  `uid` option.
- `noMtime` Set to true to omit writing `mtime` value for extracted
  entries. [Alias: `m`, `no-mtime`]
- `transform` Provide a function that takes an `entry` object, and
  returns a stream, or any falsey value.  If a stream is provided,
  then that stream's data will be written instead of the contents of
  the archive entry.  If a falsey value is provided, then the entry is
  written to disk as normal.  (To exclude items from extraction, use
  the `filter` option described above.)
- `onentry` A function that gets called with `(entry)` for each entry
  that passes the filter.

The following options are mostly internal, but can be modified in some
advanced use cases, such as re-using caches between runs.

- `maxReadSize` The maximum buffer size for `fs.read()` operations.
  Defaults to 16 MB.
- `umask` Filter the modes of entries like `process.umask()`.
- `dmode` Default mode for directories
- `fmode` Default mode for files
- `dirCache` A Map object of which directories exist.
- `maxMetaEntrySize` The maximum size of meta entries that is
  supported.  Defaults to 1 MB.

Note that using an asynchronous stream type with the `transform`
option will cause undefined behavior in sync extractions.
[MiniPass](http://npm.im/minipass)-based streams are designed for this
use case.

### tar.t(options, fileList, callback) [alias: tar.list]

List the contents of a tarball archive.

The `fileList` is an array of paths to list from the tarball.  If
no paths are provided, then all the entries are listed.

If the archive is gzipped, then tar will detect this and unzip it.

Returns an event emitter that emits `entry` events with
`tar.ReadEntry` objects.  However, they don't emit `'data'` or `'end'`
events.  (If you want to get actual readable entries, use the
`tar.Parse` class instead.)

The following options are supported:

- `cwd` Extract files relative to the specified directory.  Defaults
  to `process.cwd()`. [Alias: `C`]
- `file` The archive file to list.  If not specified, then a
  Writable stream is returned where the archive data should be
  written. [Alias: `f`]
- `sync` Read the specified file synchronously.  (This has no effect
  when a file option isn't specified, because entries are emitted as
  fast as they are parsed from the stream anyway.)
- `strict` Treat warnings as crash-worthy errors.  Default false.
- `filter` A function that gets called with `(path, entry)` for each
  entry being listed.  Return `true` to emit the entry from the
  archive, or `false` to skip it.
- `onentry` A function that gets called with `(entry)` for each entry
  that passes the filter.  This is important for when both `file` and
  `sync` are set, because it will be called synchronously.
- `maxReadSize` The maximum buffer size for `fs.read()` operations.
  Defaults to 16 MB.
- `noResume` By default, `entry` streams are resumed immediately after
  the call to `onentry`.  Set `noResume: true` to suppress this
  behavior.  Note that by opting into this, the stream will never
  complete until the entry data is consumed.

### tar.u(options, fileList, callback) [alias: tar.update]

Add files to an archive if they are newer than the entry already in
the tarball archive.

The `fileList` is an array of paths to add to the tarball.  Adding a
directory also adds its children recursively.

An entry in `fileList` that starts with an `@` symbol is a tar archive
whose entries will be added.  To add a file that starts with `@`,
prepend it with `./`.

The following options are supported:

- `file` Required. Write the tarball archive to the specified
  filename. [Alias: `f`]
- `sync` Act synchronously.  If this is set, then any provided file
  will be fully written after the call to `tar.c`.
- `onwarn` A function that will get called with `(code, message, data)` for
  any warnings encountered.  (See "Warnings and Errors")
- `strict` Treat warnings as crash-worthy errors.  Default false.
- `cwd` The current working directory for adding entries to the
  archive.  Defaults to `process.cwd()`.  [Alias: `C`]
- `prefix` A path portion to prefix onto the entries in the archive.
- `gzip` Set to any truthy value to create a gzipped archive, or an
  object with settings for `zlib.Gzip()` [Alias: `z`]
- `filter` A function that gets called with `(path, stat)` for each
  entry being added.  Return `true` to add the entry to the archive,
  or `false` to omit it.
- `portable` Omit metadata that is system-specific: `ctime`, `atime`,
  `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`.  Note
  that `mtime` is still included, because this is necessary for other
  time-based operations.  Additionally, `mode` is set to a "reasonable
  default" for most unix systems, based on a `umask` value of `0o22`.
- `preservePaths` Allow absolute paths.  By default, `/` is stripped
  from absolute paths. [Alias: `P`]
- `maxReadSize` The maximum buffer size for `fs.read()` operations.
  Defaults to 16 MB.
- `noDirRecurse` Do not recursively archive the contents of
  directories. [Alias: `n`]
- `follow` Set to true to pack the targets of symbolic links.  Without
  this option, symbolic links are archived as such. [Alias: `L`, `h`]
- `noPax` Suppress pax extended headers.  Note that this means that
  long paths and linkpaths will be truncated, and large or negative
  numeric values may be interpreted incorrectly.
- `noMtime` Set to true to omit writing `mtime` values for entries.
  Note that this prevents using other mtime-based features like
  `tar.update` or the `keepNewer` option with the resulting tar archive.
  [Alias: `m`, `no-mtime`]
- `mtime` Set to a `Date` object to force a specific `mtime` for
  everything added to the archive.  Overridden by `noMtime`.

### tar.r(options, fileList, callback) [alias: tar.replace]

Add files to an existing archive.  Because later entries override
earlier entries, this effectively replaces any existing entries.

The `fileList` is an array of paths to add to the tarball.  Adding a
directory also adds its children recursively.

An entry in `fileList` that starts with an `@` symbol is a tar archive
whose entries will be added.  To add a file that starts with `@`,
prepend it with `./`.

The following options are supported:

- `file` Required. Write the tarball archive to the specified
  filename. [Alias: `f`]
- `sync` Act synchronously.  If this is set, then any provided file
  will be fully written after the call to `tar.c`.
- `onwarn` A function that will get called with `(code, message, data)` for
  any warnings encountered.  (See "Warnings and Errors")
- `strict` Treat warnings as crash-worthy errors.  Default false.
- `cwd` The current working directory for adding entries to the
  archive.  Defaults to `process.cwd()`.  [Alias: `C`]
- `prefix` A path portion to prefix onto the entries in the archive.
- `gzip` Set to any truthy value to create a gzipped archive, or an
  object with settings for `zlib.Gzip()` [Alias: `z`]
- `filter` A function that gets called with `(path, stat)` for each
  entry being added.  Return `true` to add the entry to the archive,
  or `false` to omit it.
- `portable` Omit metadata that is system-specific: `ctime`, `atime`,
  `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`.  Note
  that `mtime` is still included, because this is necessary for other
  time-based operations.  Additionally, `mode` is set to a "reasonable
  default" for most unix systems, based on a `umask` value of `0o22`.
- `preservePaths` Allow absolute paths.  By default, `/` is stripped
  from absolute paths. [Alias: `P`]
- `maxReadSize` The maximum buffer size for `fs.read()` operations.
  Defaults to 16 MB.
- `noDirRecurse` Do not recursively archive the contents of
  directories. [Alias: `n`]
- `follow` Set to true to pack the targets of symbolic links.  Without
  this option, symbolic links are archived as such. [Alias: `L`, `h`]
- `noPax` Suppress pax extended headers.  Note that this means that
  long paths and linkpaths will be truncated, and large or negative
  numeric values may be interpreted incorrectly.
- `noMtime` Set to true to omit writing `mtime` values for entries.
  Note that this prevents using other mtime-based features like
  `tar.update` or the `keepNewer` option with the resulting tar archive.
  [Alias: `m`, `no-mtime`]
- `mtime` Set to a `Date` object to force a specific `mtime` for
  everything added to the archive.  Overridden by `noMtime`.

## Low-Level API

### class tar.Pack

A readable tar stream.

Has all the standard readable stream interface stuff.  `'data'` and
`'end'` events, `read()` method, `pause()` and `resume()`, etc.

#### constructor(options)

The following options are supported:

- `onwarn` A function that will get called with `(code, message, data)` for
  any warnings encountered.  (See "Warnings and Errors")
- `strict` Treat warnings as crash-worthy errors.  Default false.
- `cwd` The current working directory for creating the archive.
  Defaults to `process.cwd()`.
- `prefix` A path portion to prefix onto the entries in the archive.
- `gzip` Set to any truthy value to create a gzipped archive, or an
  object with settings for `zlib.Gzip()`
- `filter` A function that gets called with `(path, stat)` for each
  entry being added.  Return `true` to add the entry to the archive,
  or `false` to omit it.
- `portable` Omit metadata that is system-specific: `ctime`, `atime`,
  `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`.  Note
  that `mtime` is still included, because this is necessary for other
  time-based operations.  Additionally, `mode` is set to a "reasonable
  default" for most unix systems, based on a `umask` value of `0o22`.
- `preservePaths` Allow absolute paths.  By default, `/` is stripped
  from absolute paths.
- `linkCache` A Map object containing the device and inode value for
  any file whose nlink is > 1, to identify hard links.
- `statCache` A Map object that caches calls `lstat`.
- `readdirCache` A Map object that caches calls to `readdir`.
- `jobs` A number specifying how many concurrent jobs to run.
  Defaults to 4.
- `maxReadSize` The maximum buffer size for `fs.read()` operations.
  Defaults to 16 MB.
- `noDirRecurse` Do not recursively archive the contents of
  directories.
- `follow` Set to true to pack the targets of symbolic links.  Without
  this option, symbolic links are archived as such.
- `noPax` Suppress pax extended headers.  Note that this means that
  long paths and linkpaths will be truncated, and large or negative
  numeric values may be interpreted incorrectly.
- `noMtime` Set to true to omit writing `mtime` values for entries.
  Note that this prevents using other mtime-based features like
  `tar.update` or the `keepNewer` option with the resulting tar archive.
- `mtime` Set to a `Date` object to force a specific `mtime` for
  everything added to the archive.  Overridden by `noMtime`.

#### add(path)

Adds an entry to the archive.  Returns the Pack stream.

#### write(path)

Adds an entry to the archive.  Returns true if flushed.

#### end()

Finishes the archive.

### class tar.Pack.Sync

Synchronous version of `tar.Pack`.

### class tar.Unpack

A writable stream that unpacks a tar archive onto the file system.

All the normal writable stream stuff is supported.  `write()` and
`end()` methods, `'drain'` events, etc.

Note that all directories that are created will be forced to be
writable, readable, and listable by their owner, to avoid cases where
a directory prevents extraction of child entries by virtue of its
mode.

`'close'` is emitted when it's done writing stuff to the file system.

Most unpack errors will cause a `warn` event to be emitted.  If the
`cwd` is missing, or not a directory, then an error will be emitted.

#### constructor(options)

- `cwd` Extract files relative to the specified directory.  Defaults
  to `process.cwd()`.  If provided, this must exist and must be a
  directory.
- `filter` A function that gets called with `(path, entry)` for each
  entry being unpacked.  Return `true` to unpack the entry from the
  archive, or `false` to skip it.
- `newer` Set to true to keep the existing file on disk if it's newer
  than the file in the archive.
- `keep` Do not overwrite existing files.  In particular, if a file
  appears more than once in an archive, later copies will not
  overwrite earlier copies.
- `preservePaths` Allow absolute paths, paths containing `..`, and
  extracting through symbolic links.  By default, `/` is stripped from
  absolute paths, `..` paths are not extracted, and any file whose
  location would be modified by a symbolic link is not extracted.
- `unlink` Unlink files before creating them.  Without this option,
  tar overwrites existing files, which preserves existing hardlinks.
  With this option, existing hardlinks will be broken, as will any
  symlink that would affect the location of an extracted file.
- `strip` Remove the specified number of leading path elements.
  Pathnames with fewer elements will be silently skipped.  Note that
  the pathname is edited after applying the filter, but before
  security checks.
- `onwarn` A function that will get called with `(code, message, data)` for
  any warnings encountered.  (See "Warnings and Errors")
- `umask` Filter the modes of entries like `process.umask()`.
- `dmode` Default mode for directories
- `fmode` Default mode for files
- `dirCache` A Map object of which directories exist.
- `maxMetaEntrySize` The maximum size of meta entries that is
  supported.  Defaults to 1 MB.
- `preserveOwner` If true, tar will set the `uid` and `gid` of
  extracted entries to the `uid` and `gid` fields in the archive.
  This defaults to true when run as root, and false otherwise.  If
  false, then files and directories will be set with the owner and
  group of the user running the process.  This is similar to `-p` in
  `tar(1)`, but ACLs and other system-specific data is never unpacked
  in this implementation, and modes are set by default already.
- `win32` True if on a windows platform.  Causes behavior where
  filenames containing `<|>?` chars are converted to
  windows-compatible values while being unpacked.
- `uid` Set to a number to force ownership of all extracted files and
  folders, and all implicitly created directories, to be owned by the
  specified user id, regardless of the `uid` field in the archive.
  Cannot be used along with `preserveOwner`.  Requires also setting a
  `gid` option.
- `gid` Set to a number to force ownership of all extracted files and
  folders, and all implicitly created directories, to be owned by the
  specified group id, regardless of the `gid` field in the archive.
  Cannot be used along with `preserveOwner`.  Requires also setting a
  `uid` option.
- `noMtime` Set to true to omit writing `mtime` value for extracted
  entries.
- `transform` Provide a function that takes an `entry` object, and
  returns a stream, or any falsey value.  If a stream is provided,
  then that stream's data will be written instead of the contents of
  the archive entry.  If a falsey value is provided, then the entry is
  written to disk as normal.  (To exclude items from extraction, use
  the `filter` option described above.)
- `strict` Treat warnings as crash-worthy errors.  Default false.
- `onentry` A function that gets called with `(entry)` for each entry
  that passes the filter.
- `onwarn` A function that will get called with `(code, message, data)` for
  any warnings encountered.  (See "Warnings and Errors")

### class tar.Unpack.Sync

Synchronous version of `tar.Unpack`.

Note that using an asynchronous stream type with the `transform`
option will cause undefined behavior in sync unpack streams.
[MiniPass](http://npm.im/minipass)-based streams are designed for this
use case.

### class tar.Parse

A writable stream that parses a tar archive stream.  All the standard
writable stream stuff is supported.

If the archive is gzipped, then tar will detect this and unzip it.

Emits `'entry'` events with `tar.ReadEntry` objects, which are
themselves readable streams that you can pipe wherever.

Each `entry` will not emit until the one before it is flushed through,
so make sure to either consume the data (with `on('data', ...)` or
`.pipe(...)`) or throw it away with `.resume()` to keep the stream
flowing.

#### constructor(options)

Returns an event emitter that emits `entry` events with
`tar.ReadEntry` objects.

The following options are supported:

- `strict` Treat warnings as crash-worthy errors.  Default false.
- `filter` A function that gets called with `(path, entry)` for each
  entry being listed.  Return `true` to emit the entry from the
  archive, or `false` to skip it.
- `onentry` A function that gets called with `(entry)` for each entry
  that passes the filter.
- `onwarn` A function that will get called with `(code, message, data)` for
  any warnings encountered.  (See "Warnings and Errors")

#### abort(error)

Stop all parsing activities.  This is called when there are zlib
errors.  It also emits an unrecoverable warning with the error provided.

### class tar.ReadEntry extends [MiniPass](http://npm.im/minipass)

A representation of an entry that is being read out of a tar archive.

It has the following fields:

- `extended` The extended metadata object provided to the constructor.
- `globalExtended` The global extended metadata object provided to the
  constructor.
- `remain` The number of bytes remaining to be written into the
  stream.
- `blockRemain` The number of 512-byte blocks remaining to be written
  into the stream.
- `ignore` Whether this entry should be ignored.
- `meta` True if this represents metadata about the next entry, false
  if it represents a filesystem object.
- All the fields from the header, extended header, and global extended
  header are added to the ReadEntry object.  So it has `path`, `type`,
  `size, `mode`, and so on.

#### constructor(header, extended, globalExtended)

Create a new ReadEntry object with the specified header, extended
header, and global extended header values.

### class tar.WriteEntry extends [MiniPass](http://npm.im/minipass)

A representation of an entry that is being written from the file
system into a tar archive.

Emits data for the Header, and for the Pax Extended Header if one is
required, as well as any body data.

Creating a WriteEntry for a directory does not also create
WriteEntry objects for all of the directory contents.

It has the following fields:

- `path` The path field that will be written to the archive.  By
  default, this is also the path from the cwd to the file system
  object.
- `portable` Omit metadata that is system-specific: `ctime`, `atime`,
  `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`.  Note
  that `mtime` is still included, because this is necessary for other
  time-based operations.  Additionally, `mode` is set to a "reasonable
  default" for most unix systems, based on a `umask` value of `0o22`.
- `myuid` If supported, the uid of the user running the current
  process.
- `myuser` The `env.USER` string if set, or `''`.  Set as the entry
  `uname` field if the file's `uid` matches `this.myuid`.
- `maxReadSize` The maximum buffer size for `fs.read()` operations.
  Defaults to 1 MB.
- `linkCache` A Map object containing the device and inode value for
  any file whose nlink is > 1, to identify hard links.
- `statCache` A Map object that caches calls `lstat`.
- `preservePaths` Allow absolute paths.  By default, `/` is stripped
  from absolute paths.
- `cwd` The current working directory for creating the archive.
  Defaults to `process.cwd()`.
- `absolute` The absolute path to the entry on the filesystem.  By
  default, this is `path.resolve(this.cwd, this.path)`, but it can be
  overridden explicitly.
- `strict` Treat warnings as crash-worthy errors.  Default false.
- `win32` True if on a windows platform.  Causes behavior where paths
  replace `\` with `/` and filenames containing the windows-compatible
  forms of `<|>?:` characters are converted to actual `<|>?:` characters
  in the archive.
- `noPax` Suppress pax extended headers.  Note that this means that
  long paths and linkpaths will be truncated, and large or negative
  numeric values may be interpreted incorrectly.
- `noMtime` Set to true to omit writing `mtime` values for entries.
  Note that this prevents using other mtime-based features like
  `tar.update` or the `keepNewer` option with the resulting tar archive.

#### constructor(path, options)

`path` is the path of the entry as it is written in the archive.

The following options are supported:

- `portable` Omit metadata that is system-specific: `ctime`, `atime`,
  `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`.  Note
  that `mtime` is still included, because this is necessary for other
  time-based operations.  Additionally, `mode` is set to a "reasonable
  default" for most unix systems, based on a `umask` value of `0o22`.
- `maxReadSize` The maximum buffer size for `fs.read()` operations.
  Defaults to 1 MB.
- `linkCache` A Map object containing the device and inode value for
  any file whose nlink is > 1, to identify hard links.
- `statCache` A Map object that caches calls `lstat`.
- `preservePaths` Allow absolute paths.  By default, `/` is stripped
  from absolute paths.
- `cwd` The current working directory for creating the archive.
  Defaults to `process.cwd()`.
- `absolute` The absolute path to the entry on the filesystem.  By
  default, this is `path.resolve(this.cwd, this.path)`, but it can be
  overridden explicitly.
- `strict` Treat warnings as crash-worthy errors.  Default false.
- `win32` True if on a windows platform.  Causes behavior where paths
  replace `\` with `/`.
- `onwarn` A function that will get called with `(code, message, data)` for
  any warnings encountered.  (See "Warnings and Errors")
- `noMtime` Set to true to omit writing `mtime` values for entries.
  Note that this prevents using other mtime-based features like
  `tar.update` or the `keepNewer` option with the resulting tar archive.
- `umask` Set to restrict the modes on the entries in the archive,
  somewhat like how umask works on file creation.  Defaults to
  `process.umask()` on unix systems, or `0o22` on Windows.

#### warn(message, data)

If strict, emit an error with the provided message.

Othewise, emit a `'warn'` event with the provided message and data.

### class tar.WriteEntry.Sync

Synchronous version of tar.WriteEntry

### class tar.WriteEntry.Tar

A version of tar.WriteEntry that gets its data from a tar.ReadEntry
instead of from the filesystem.

#### constructor(readEntry, options)

`readEntry` is the entry being read out of another archive.

The following options are supported:

- `portable` Omit metadata that is system-specific: `ctime`, `atime`,
  `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`.  Note
  that `mtime` is still included, because this is necessary for other
  time-based operations.  Additionally, `mode` is set to a "reasonable
  default" for most unix systems, based on a `umask` value of `0o22`.
- `preservePaths` Allow absolute paths.  By default, `/` is stripped
  from absolute paths.
- `strict` Treat warnings as crash-worthy errors.  Default false.
- `onwarn` A function that will get called with `(code, message, data)` for
  any warnings encountered.  (See "Warnings and Errors")
- `noMtime` Set to true to omit writing `mtime` values for entries.
  Note that this prevents using other mtime-based features like
  `tar.update` or the `keepNewer` option with the resulting tar archive.

### class tar.Header

A class for reading and writing header blocks.

It has the following fields:

- `nullBlock` True if decoding a block which is entirely composed of
  `0x00` null bytes.  (Useful because tar files are terminated by
  at least 2 null blocks.)
- `cksumValid` True if the checksum in the header is valid, false
  otherwise.
- `needPax` True if the values, as encoded, will require a Pax
  extended header.
- `path` The path of the entry.
- `mode` The 4 lowest-order octal digits of the file mode.  That is,
  read/write/execute permissions for world, group, and owner, and the
  setuid, setgid, and sticky bits.
- `uid` Numeric user id of the file owner
- `gid` Numeric group id of the file owner
- `size` Size of the file in bytes
- `mtime` Modified time of the file
- `cksum` The checksum of the header.  This is generated by adding all
  the bytes of the header block, treating the checksum field itself as
  all ascii space characters (that is, `0x20`).
- `type` The human-readable name of the type of entry this represents,
  or the alphanumeric key if unknown.
- `typeKey` The alphanumeric key for the type of entry this header
  represents.
- `linkpath` The target of Link and SymbolicLink entries.
- `uname` Human-readable user name of the file owner
- `gname` Human-readable group name of the file owner
- `devmaj` The major portion of the device number.  Always `0` for
  files, directories, and links.
- `devmin` The minor portion of the device number.  Always `0` for
  files, directories, and links.
- `atime` File access time.
- `ctime` File change time.

#### constructor(data, [offset=0])

`data` is optional.  It is either a Buffer that should be interpreted
as a tar Header starting at the specified offset and continuing for
512 bytes, or a data object of keys and values to set on the header
object, and eventually encode as a tar Header.

#### decode(block, offset)

Decode the provided buffer starting at the specified offset.

Buffer length must be greater than 512 bytes.

#### set(data)

Set the fields in the data object.

#### encode(buffer, offset)

Encode the header fields into the buffer at the specified offset.

Returns `this.needPax` to indicate whether a Pax Extended Header is
required to properly encode the specified data.

### class tar.Pax

An object representing a set of key-value pairs in an Pax extended
header entry.

It has the following fields.  Where the same name is used, they have
the same semantics as the tar.Header field of the same name.

- `global` True if this represents a global extended header, or false
  if it is for a single entry.
- `atime`
- `charset`
- `comment`
- `ctime`
- `gid`
- `gname`
- `linkpath`
- `mtime`
- `path`
- `size`
- `uid`
- `uname`
- `dev`
- `ino`
- `nlink`

#### constructor(object, global)

Set the fields set in the object.  `global` is a boolean that defaults
to false.

#### encode()

Return a Buffer containing the header and body for the Pax extended
header entry, or `null` if there is nothing to encode.

#### encodeBody()

Return a string representing the body of the pax extended header
entry.

#### encodeField(fieldName)

Return a string representing the key/value encoding for the specified
fieldName, or `''` if the field is unset.

### tar.Pax.parse(string, extended, global)

Return a new Pax object created by parsing the contents of the string
provided.

If the `extended` object is set, then also add the fields from that
object.  (This is necessary because multiple metadata entries can
occur in sequence.)

### tar.types

A translation table for the `type` field in tar headers.

#### tar.types.name.get(code)

Get the human-readable name for a given alphanumeric code.

#### tar.types.code.get(name)

Get the alphanumeric code for a given human-readable name.
<p align="center">
  <a href="https://assemblyscript.org" target="_blank" rel="noopener"><img width="100" src="https://avatars1.githubusercontent.com/u/28916798?s=200&v=4" alt="AssemblyScript logo"></a>
</p>

<p align="center">
  <a href="https://github.com/AssemblyScript/assemblyscript/actions?query=workflow%3ATest"><img src="https://img.shields.io/github/workflow/status/AssemblyScript/assemblyscript/Test/master?label=test&logo=github" alt="Test status" /></a>
  <a href="https://github.com/AssemblyScript/assemblyscript/actions?query=workflow%3APublish"><img src="https://img.shields.io/github/workflow/status/AssemblyScript/assemblyscript/Publish/master?label=publish&logo=github" alt="Publish status" /></a>
  <a href="https://www.npmjs.com/package/assemblyscript"><img src="https://img.shields.io/npm/v/assemblyscript.svg?label=compiler&color=007acc&logo=npm" alt="npm compiler version" /></a>
  <a href="https://www.npmjs.com/package/@assemblyscript/loader"><img src="https://img.shields.io/npm/v/@assemblyscript/loader.svg?label=loader&color=007acc&logo=npm" alt="npm loader version" /></a>
  <a href="https://discord.gg/assemblyscript"><img src="https://img.shields.io/discord/721472913886281818.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2" alt="Discord online" /></a>
</p>

<p align="justify"><strong>AssemblyScript</strong> compiles a strict variant of <a href="http://www.typescriptlang.org">TypeScript</a> (basically JavaScript with types) to <a href="http://webassembly.org">WebAssembly</a> using <a href="https://github.com/WebAssembly/binaryen">Binaryen</a>. It generates lean and mean WebAssembly modules while being just an <code>npm install</code> away.</p>

<h3 align="center">
  <a href="https://assemblyscript.org">About</a> &nbsp;·&nbsp;
  <a href="https://assemblyscript.org/introduction.html">Introduction</a> &nbsp;·&nbsp;
  <a href="https://assemblyscript.org/quick-start.html">Quick&nbsp;start</a> &nbsp;·&nbsp;
  <a href="https://assemblyscript.org/examples.html">Examples</a> &nbsp;·&nbsp;
  <a href="https://assemblyscript.org/development.html">Development&nbsp;instructions</a>
</h3>
<br>

<h2 align="center">Contributors</h2>

<p align="center">
  <a href="https://assemblyscript.org/#contributors"><img src="https://assemblyscript.org/contributors.svg" alt="Contributor logos" width="720" /></a>
</p>

<h2 align="center">Thanks to our sponsors!</h2>

<p align="justify">Most of the core team members and most contributors do this open source work in their free time. If you use AssemblyScript for a serious task or plan to do so, and you'd like us to invest more time on it, <a href="https://opencollective.com/assemblyscript/donate" target="_blank" rel="noopener">please donate</a> to our <a href="https://opencollective.com/assemblyscript" target="_blank" rel="noopener">OpenCollective</a>. By sponsoring this project, your logo will show up below. Thank you so much for your support!</p>

<p align="center">
  <a href="https://assemblyscript.org/#sponsors"><img src="https://assemblyscript.org/sponsors.svg" alt="Sponsor logos" width="720" /></a>
</p>
# TenderBoxAfrica-NEAR
TenderBoxAfrica-NEAR is an implementation of Tenderbox on the NEAR Protocol.
# Web IDL Type Conversions on JavaScript Values

This package implements, in JavaScript, the algorithms to convert a given JavaScript value according to a given [Web IDL](http://heycam.github.io/webidl/) [type](http://heycam.github.io/webidl/#idl-types).

The goal is that you should be able to write code like

```js
"use strict";
const conversions = require("webidl-conversions");

function doStuff(x, y) {
    x = conversions["boolean"](x);
    y = conversions["unsigned long"](y);
    // actual algorithm code here
}
```

and your function `doStuff` will behave the same as a Web IDL operation declared as

```webidl
void doStuff(boolean x, unsigned long y);
```

## API

This package's main module's default export is an object with a variety of methods, each corresponding to a different Web IDL type. Each method, when invoked on a JavaScript value, will give back the new JavaScript value that results after passing through the Web IDL conversion rules. (See below for more details on what that means.) Alternately, the method could throw an error, if the Web IDL algorithm is specified to do so: for example `conversions["float"](NaN)` [will throw a `TypeError`](http://heycam.github.io/webidl/#es-float).

Each method also accepts a second, optional, parameter for miscellaneous options. For conversion methods that throw errors, a string option `{ context }` may be provided to provide more information in the error message. (For example, `conversions["float"](NaN, { context: "Argument 1 of Interface's operation" })` will throw an error with message `"Argument 1 of Interface's operation is not a finite floating-point value."`) Specific conversions may also accept other options, the details of which can be found below.

## Conversions implemented

Conversions for all of the basic types from the Web IDL specification are implemented:

- [`any`](https://heycam.github.io/webidl/#es-any)
- [`void`](https://heycam.github.io/webidl/#es-void)
- [`boolean`](https://heycam.github.io/webidl/#es-boolean)
- [Integer types](https://heycam.github.io/webidl/#es-integer-types), which can additionally be provided the boolean options `{ clamp, enforceRange }` as a second parameter
- [`float`](https://heycam.github.io/webidl/#es-float), [`unrestricted float`](https://heycam.github.io/webidl/#es-unrestricted-float)
- [`double`](https://heycam.github.io/webidl/#es-double), [`unrestricted double`](https://heycam.github.io/webidl/#es-unrestricted-double)
- [`DOMString`](https://heycam.github.io/webidl/#es-DOMString), which can additionally be provided the boolean option `{ treatNullAsEmptyString }` as a second parameter
- [`ByteString`](https://heycam.github.io/webidl/#es-ByteString), [`USVString`](https://heycam.github.io/webidl/#es-USVString)
- [`object`](https://heycam.github.io/webidl/#es-object)
- [`Error`](https://heycam.github.io/webidl/#es-Error)
- [Buffer source types](https://heycam.github.io/webidl/#es-buffer-source-types)

Additionally, for convenience, the following derived type definitions are implemented:

- [`ArrayBufferView`](https://heycam.github.io/webidl/#ArrayBufferView)
- [`BufferSource`](https://heycam.github.io/webidl/#BufferSource)
- [`DOMTimeStamp`](https://heycam.github.io/webidl/#DOMTimeStamp)
- [`Function`](https://heycam.github.io/webidl/#Function)
- [`VoidFunction`](https://heycam.github.io/webidl/#VoidFunction) (although it will not censor the return type)

Derived types, such as nullable types, promise types, sequences, records, etc. are not handled by this library. You may wish to investigate the [webidl2js](https://github.com/jsdom/webidl2js) project.

### A note on the `long long` types

The `long long` and `unsigned long long` Web IDL types can hold values that cannot be stored in JavaScript numbers, so the conversion is imperfect. For example, converting the JavaScript number `18446744073709552000` to a Web IDL `long long` is supposed to produce the Web IDL value `-18446744073709551232`. Since we are representing our Web IDL values in JavaScript, we can't represent `-18446744073709551232`, so we instead the best we could do is `-18446744073709552000` as the output.

This library actually doesn't even get that far. Producing those results would require doing accurate modular arithmetic on 64-bit intermediate values, but JavaScript does not make this easy. We could pull in a big-integer library as a dependency, but in lieu of that, we for now have decided to just produce inaccurate results if you pass in numbers that are not strictly between `Number.MIN_SAFE_INTEGER` and `Number.MAX_SAFE_INTEGER`.

## Background

What's actually going on here, conceptually, is pretty weird. Let's try to explain.

Web IDL, as part of its madness-inducing design, has its own type system. When people write algorithms in web platform specs, they usually operate on Web IDL values, i.e. instances of Web IDL types. For example, if they were specifying the algorithm for our `doStuff` operation above, they would treat `x` as a Web IDL value of [Web IDL type `boolean`](http://heycam.github.io/webidl/#idl-boolean). Crucially, they would _not_ treat `x` as a JavaScript variable whose value is either the JavaScript `true` or `false`. They're instead working in a different type system altogether, with its own rules.

Separately from its type system, Web IDL defines a ["binding"](http://heycam.github.io/webidl/#ecmascript-binding) of the type system into JavaScript. This contains rules like: when you pass a JavaScript value to the JavaScript method that manifests a given Web IDL operation, how does that get converted into a Web IDL value? For example, a JavaScript `true` passed in the position of a Web IDL `boolean` argument becomes a Web IDL `true`. But, a JavaScript `true` passed in the position of a [Web IDL `unsigned long`](http://heycam.github.io/webidl/#idl-unsigned-long) becomes a Web IDL `1`. And so on.

Finally, we have the actual implementation code. This is usually C++, although these days [some smart people are using Rust](https://github.com/servo/servo). The implementation, of course, has its own type system. So when they implement the Web IDL algorithms, they don't actually use Web IDL values, since those aren't "real" outside of specs. Instead, implementations apply the Web IDL binding rules in such a way as to convert incoming JavaScript values into C++ values. For example, if code in the browser called `doStuff(true, true)`, then the implementation code would eventually receive a C++ `bool` containing `true` and a C++ `uint32_t` containing `1`.

The upside of all this is that implementations can abstract all the conversion logic away, letting Web IDL handle it, and focus on implementing the relevant methods in C++ with values of the correct type already provided. That is payoff of Web IDL, in a nutshell.

And getting to that payoff is the goal of _this_ project—but for JavaScript implementations, instead of C++ ones. That is, this library is designed to make it easier for JavaScript developers to write functions that behave like a given Web IDL operation. So conceptually, the conversion pipeline, which in its general form is JavaScript values ↦ Web IDL values ↦ implementation-language values, in this case becomes JavaScript values ↦ Web IDL values ↦ JavaScript values. And that intermediate step is where all the logic is performed: a JavaScript `true` becomes a Web IDL `1` in an unsigned long context, which then becomes a JavaScript `1`.

## Don't use this

Seriously, why would you ever use this? You really shouldn't. Web IDL is … strange, and you shouldn't be emulating its semantics. If you're looking for a generic argument-processing library, you should find one with better rules than those from Web IDL. In general, your JavaScript should not be trying to become more like Web IDL; if anything, we should fix Web IDL to make it more like JavaScript.

The _only_ people who should use this are those trying to create faithful implementations (or polyfills) of web platform interfaces defined in Web IDL. Its main consumer is the [jsdom](https://github.com/tmpvar/jsdom) project.
# get-caller-file

[![Build Status](https://travis-ci.org/stefanpenner/get-caller-file.svg?branch=master)](https://travis-ci.org/stefanpenner/get-caller-file)
[![Build status](https://ci.appveyor.com/api/projects/status/ol2q94g1932cy14a/branch/master?svg=true)](https://ci.appveyor.com/project/embercli/get-caller-file/branch/master)

This is a utility, which allows a function to figure out from which file it was invoked. It does so by inspecting v8's stack trace at the time it is invoked.

Inspired by http://stackoverflow.com/questions/13227489

*note: this relies on Node/V8 specific APIs, as such other runtimes may not work*

## Installation

```bash
yarn add get-caller-file
```

## Usage

Given:

```js
// ./foo.js
const getCallerFile = require('get-caller-file');

module.exports = function() {
  return getCallerFile(); // figures out who called it
};
```

```js
// index.js
const foo = require('./foo');

foo() // => /full/path/to/this/file/index.js
```

## Options:

* `getCallerFile(position = 2)`: where position is stack frame whos fileName we want.
# axios // core

The modules found in `core/` should be modules that are specific to the domain logic of axios. These modules would most likely not make sense to be consumed outside of the axios module, as their logic is too specific. Some examples of core modules are:

- Dispatching requests
- Managing interceptors
- Handling config
# assemblyscript-json

![npm version](https://img.shields.io/npm/v/assemblyscript-json) ![npm downloads per month](https://img.shields.io/npm/dm/assemblyscript-json)

JSON encoder / decoder for AssemblyScript.

Special thanks to https://github.com/MaxGraey/bignum.wasm for basic unit testing infra for AssemblyScript.

## Installation

`assemblyscript-json` is available as a [npm package](https://www.npmjs.com/package/assemblyscript-json). You can install `assemblyscript-json` in your AssemblyScript project by running:

`npm install --save assemblyscript-json`

## Usage

### Parsing JSON

```typescript
import { JSON } from "assemblyscript-json"; 

// Parse an object using the JSON object
let jsonObj: JSON.Obj = <JSON.Obj>(JSON.parse('{"hello": "world", "value": 24}'));

// We can then use the .getX functions to read from the object if you know it's type
// This will return the appropriate JSON.X value if the key exists, or null if the key does not exist
let worldOrNull: JSON.Str | null = jsonObj.getString("hello"); // This will return a JSON.Str or null
if (worldOrNull != null) {
  // use .valueOf() to turn the high level JSON.Str type into a string
  let world: string = worldOrNull.valueOf();
}

let numOrNull: JSON.Num | null = jsonObj.getNum("value");
if (numOrNull != null) {
  // use .valueOf() to turn the high level JSON.Num type into a f64
  let value: f64 = numOrNull.valueOf();
}

// If you don't know the value type, get the parent JSON.Value
let valueOrNull: JSON.Value | null = jsonObj.getValue("hello");
  if (valueOrNull != null) {
  let value: JSON.Value = changetype<JSON.Value>(valueOrNull);

  // Next we could figure out what type we are
  if(value.isString) { 
    // value.isString would be true, so we can cast to a string
    let stringValue: string = changetype<JSON.Str>(value).toString();

    // Do something with string value
  }
}
```

### Encoding JSON

```typescript
import { JSONEncoder } from "assemblyscript-json";

// Create encoder
let encoder = new JSONEncoder();

// Construct necessary object
encoder.pushObject("obj");
encoder.setInteger("int", 10);
encoder.setString("str", "");
encoder.popObject();

// Get serialized data
let json: Uint8Array = encoder.serialize();

// Or get serialized data as string
let jsonString: string = encoder.toString();

assert(jsonString, '"obj": {"int": 10, "str": ""}'); // True!
```

### Custom JSON Deserializers

```typescript
import { JSONDecoder, JSONHandler } from "assemblyscript-json";

// Events need to be received by custom object extending JSONHandler.
// NOTE: All methods are optional to implement.
class MyJSONEventsHandler extends JSONHandler {
  setString(name: string, value: string): void {
    // Handle field
  }

  setBoolean(name: string, value: bool): void {
    // Handle field
  }

  setNull(name: string): void {
    // Handle field
  }

  setInteger(name: string, value: i64): void {
    // Handle field
  }

  setFloat(name: string, value: f64): void {
    // Handle field
  }

  pushArray(name: string): bool {
    // Handle array start
    // true means that nested object needs to be traversed, false otherwise
    // Note that returning false means JSONDecoder.startIndex need to be updated by handler
    return true;
  }

  popArray(): void {
    // Handle array end
  }

  pushObject(name: string): bool {
    // Handle object start
    // true means that nested object needs to be traversed, false otherwise
    // Note that returning false means JSONDecoder.startIndex need to be updated by handler
    return true;
  }

  popObject(): void {
    // Handle object end
  }
}

// Create decoder
let decoder = new JSONDecoder<MyJSONEventsHandler>(new MyJSONEventsHandler());

// Create a byte buffer of our JSON. NOTE: Deserializers work on UTF8 string buffers.
let jsonString = '{"hello": "world"}';
let jsonBuffer = Uint8Array.wrap(String.UTF8.encode(jsonString));

// Parse JSON
decoder.deserialize(jsonBuffer); // This will send events to MyJSONEventsHandler
```

Feel free to look through the [tests](https://github.com/nearprotocol/assemblyscript-json/tree/master/assembly/__tests__) for more usage examples.

## Reference Documentation

Reference API Documentation can be found in the [docs directory](./docs).

## License

[MIT](./LICENSE)
bs58
====

[![build status](https://travis-ci.org/cryptocoinjs/bs58.svg)](https://travis-ci.org/cryptocoinjs/bs58)

JavaScript component to compute base 58 encoding. This encoding is typically used for crypto currencies such as Bitcoin.

**Note:** If you're looking for **base 58 check** encoding, see: [https://github.com/bitcoinjs/bs58check](https://github.com/bitcoinjs/bs58check), which depends upon this library.

Install
-------

    npm i --save bs58

API
---

### encode(input)

`input` must be a [Buffer](https://nodejs.org/api/buffer.html) or an `Array`. It returns a `string`.

**example**:

```js
const bs58 = require('bs58')

const bytes = Buffer.from('003c176e659bea0f29a3e9bf7880c112b1b31b4dc826268187', 'hex')
const address = bs58.encode(bytes)
console.log(address)
// => 16UjcYNBG9GTK4uq2f7yYEbuifqCzoLMGS
```

### decode(input)

`input` must be a base 58 encoded string. Returns a [Buffer](https://nodejs.org/api/buffer.html).

**example**:

```js
const bs58 = require('bs58')

const address = '16UjcYNBG9GTK4uq2f7yYEbuifqCzoLMGS'
const bytes = bs58.decode(address)
console.log(out.toString('hex'))
// => 003c176e659bea0f29a3e9bf7880c112b1b31b4dc826268187
```

Hack / Test
-----------

Uses JavaScript standard style. Read more:

[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)

Credits
-------
- [Mike Hearn](https://github.com/mikehearn) for original Java implementation
- [Stefan Thomas](https://github.com/justmoon) for porting to JavaScript
- [Stephan Pair](https://github.com/gasteve) for buffer improvements
- [Daniel Cousens](https://github.com/dcousens) for cleanup and merging improvements from bitcoinjs-lib
- [Jared Deckard](https://github.com/deckar01) for killing `bigi` as a dependency

License
-------

MIT
<p align="center">
  <img width="250" src="/yargs-logo.png">
</p>
<h1 align="center"> Yargs </h1>
<p align="center">
  <b >Yargs be a node.js library fer hearties tryin' ter parse optstrings</b>
</p>

<br>

[![Build Status][travis-image]][travis-url]
[![NPM version][npm-image]][npm-url]
[![js-standard-style][standard-image]][standard-url]
[![Coverage][coverage-image]][coverage-url]
[![Conventional Commits][conventional-commits-image]][conventional-commits-url]
[![Slack][slack-image]][slack-url]

## Description :
Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface.

It gives you:

* commands and (grouped) options (`my-program.js serve --port=5000`).
* a dynamically generated help menu based on your arguments.

> <img width="400" src="/screen.png">

* bash-completion shortcuts for commands and options.
* and [tons more](/docs/api.md).

## Installation

Stable version:
```bash
npm i yargs
```

Bleeding edge version with the most recent features:
```bash
npm i yargs@next
```

## Usage :

### Simple Example

```javascript
#!/usr/bin/env node
const {argv} = require('yargs')

if (argv.ships > 3 && argv.distance < 53.5) {
  console.log('Plunder more riffiwobbles!')
} else {
  console.log('Retreat from the xupptumblers!')
}
```

```bash
$ ./plunder.js --ships=4 --distance=22
Plunder more riffiwobbles!

$ ./plunder.js --ships 12 --distance 98.7
Retreat from the xupptumblers!
```

### Complex Example

```javascript
#!/usr/bin/env node
require('yargs') // eslint-disable-line
  .command('serve [port]', 'start the server', (yargs) => {
    yargs
      .positional('port', {
        describe: 'port to bind on',
        default: 5000
      })
  }, (argv) => {
    if (argv.verbose) console.info(`start server on :${argv.port}`)
    serve(argv.port)
  })
  .option('verbose', {
    alias: 'v',
    type: 'boolean',
    description: 'Run with verbose logging'
  })
  .argv
```

Run the example above with `--help` to see the help for the application.

## TypeScript

yargs has type definitions at [@types/yargs][type-definitions].

```
npm i @types/yargs --save-dev
```

See usage examples in [docs](/docs/typescript.md).

## Webpack

See usage examples of yargs with webpack in [docs](/docs/webpack.md).

## Community :

Having problems? want to contribute? join our [community slack](http://devtoolscommunity.herokuapp.com).

## Documentation :

### Table of Contents

* [Yargs' API](/docs/api.md)
* [Examples](/docs/examples.md)
* [Parsing Tricks](/docs/tricks.md)
  * [Stop the Parser](/docs/tricks.md#stop)
  * [Negating Boolean Arguments](/docs/tricks.md#negate)
  * [Numbers](/docs/tricks.md#numbers)
  * [Arrays](/docs/tricks.md#arrays)
  * [Objects](/docs/tricks.md#objects)
  * [Quotes](/docs/tricks.md#quotes)
* [Advanced Topics](/docs/advanced.md)
  * [Composing Your App Using Commands](/docs/advanced.md#commands)
  * [Building Configurable CLI Apps](/docs/advanced.md#configuration)
  * [Customizing Yargs' Parser](/docs/advanced.md#customizing)
* [Contributing](/contributing.md)

[travis-url]: https://travis-ci.org/yargs/yargs
[travis-image]: https://img.shields.io/travis/yargs/yargs/master.svg
[npm-url]: https://www.npmjs.com/package/yargs
[npm-image]: https://img.shields.io/npm/v/yargs.svg
[standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg
[standard-url]: http://standardjs.com/
[conventional-commits-image]: https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg
[conventional-commits-url]: https://conventionalcommits.org/
[slack-image]: http://devtoolscommunity.herokuapp.com/badge.svg
[slack-url]: http://devtoolscommunity.herokuapp.com
[type-definitions]: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yargs
[coverage-image]: https://img.shields.io/nycrc/yargs/yargs
[coverage-url]: https://github.com/yargs/yargs/blob/master/.nycrc
# yallist

Yet Another Linked List

There are many doubly-linked list implementations like it, but this
one is mine.

For when an array would be too big, and a Map can't be iterated in
reverse order.

[![Build Status](https://travis-ci.org/isaacs/yallist.svg?branch=master)](https://travis-ci.org/isaacs/yallist) [![Coverage Status](https://coveralls.io/repos/isaacs/yallist/badge.svg?service=github)](https://coveralls.io/github/isaacs/yallist)

## basic usage

```javascript
var yallist = require('yallist')
var myList = yallist.create([1, 2, 3])
myList.push('foo')
myList.unshift('bar')
// of course pop() and shift() are there, too
console.log(myList.toArray()) // ['bar', 1, 2, 3, 'foo']
myList.forEach(function (k) {
  // walk the list head to tail
})
myList.forEachReverse(function (k, index, list) {
  // walk the list tail to head
})
var myDoubledList = myList.map(function (k) {
  return k + k
})
// now myDoubledList contains ['barbar', 2, 4, 6, 'foofoo']
// mapReverse is also a thing
var myDoubledListReverse = myList.mapReverse(function (k) {
  return k + k
}) // ['foofoo', 6, 4, 2, 'barbar']

var reduced = myList.reduce(function (set, entry) {
  set += entry
  return set
}, 'start')
console.log(reduced) // 'startfoo123bar'
```

## api

The whole API is considered "public".

Functions with the same name as an Array method work more or less the
same way.

There's reverse versions of most things because that's the point.

### Yallist

Default export, the class that holds and manages a list.

Call it with either a forEach-able (like an array) or a set of
arguments, to initialize the list.

The Array-ish methods all act like you'd expect.  No magic length,
though, so if you change that it won't automatically prune or add
empty spots.

### Yallist.create(..)

Alias for Yallist function.  Some people like factories.

#### yallist.head

The first node in the list

#### yallist.tail

The last node in the list

#### yallist.length

The number of nodes in the list.  (Change this at your peril.  It is
not magic like Array length.)

#### yallist.toArray()

Convert the list to an array.

#### yallist.forEach(fn, [thisp])

Call a function on each item in the list.

#### yallist.forEachReverse(fn, [thisp])

Call a function on each item in the list, in reverse order.

#### yallist.get(n)

Get the data at position `n` in the list.  If you use this a lot,
probably better off just using an Array.

#### yallist.getReverse(n)

Get the data at position `n`, counting from the tail.

#### yallist.map(fn, thisp)

Create a new Yallist with the result of calling the function on each
item.

#### yallist.mapReverse(fn, thisp)

Same as `map`, but in reverse.

#### yallist.pop()

Get the data from the list tail, and remove the tail from the list.

#### yallist.push(item, ...)

Insert one or more items to the tail of the list.

#### yallist.reduce(fn, initialValue)

Like Array.reduce.

#### yallist.reduceReverse

Like Array.reduce, but in reverse.

#### yallist.reverse

Reverse the list in place.

#### yallist.shift()

Get the data from the list head, and remove the head from the list.

#### yallist.slice([from], [to])

Just like Array.slice, but returns a new Yallist.

#### yallist.sliceReverse([from], [to])

Just like yallist.slice, but the result is returned in reverse.

#### yallist.toArray()

Create an array representation of the list.

#### yallist.toArrayReverse()

Create a reversed array representation of the list.

#### yallist.unshift(item, ...)

Insert one or more items to the head of the list.

#### yallist.unshiftNode(node)

Move a Node object to the front of the list.  (That is, pull it out of
wherever it lives, and make it the new head.)

If the node belongs to a different list, then that list will remove it
first.

#### yallist.pushNode(node)

Move a Node object to the end of the list.  (That is, pull it out of
wherever it lives, and make it the new tail.)

If the node belongs to a list already, then that list will remove it
first.

#### yallist.removeNode(node)

Remove a node from the list, preserving referential integrity of head
and tail and other nodes.

Will throw an error if you try to have a list remove a node that
doesn't belong to it.

### Yallist.Node

The class that holds the data and is actually the list.

Call with `var n = new Node(value, previousNode, nextNode)`

Note that if you do direct operations on Nodes themselves, it's very
easy to get into weird states where the list is broken.  Be careful :)

#### node.next

The next node in the list.

#### node.prev

The previous node in the list.

#### node.value

The data the node contains.

#### node.list

The list to which this node belongs.  (Null if it does not belong to
any list.)
# require-main-filename

[![Build Status](https://travis-ci.org/yargs/require-main-filename.png)](https://travis-ci.org/yargs/require-main-filename)
[![Coverage Status](https://coveralls.io/repos/yargs/require-main-filename/badge.svg?branch=master)](https://coveralls.io/r/yargs/require-main-filename?branch=master)
[![NPM version](https://img.shields.io/npm/v/require-main-filename.svg)](https://www.npmjs.com/package/require-main-filename)

`require.main.filename` is great for figuring out the entry
point for the current application. This can be combined with a module like
[pkg-conf](https://www.npmjs.com/package/pkg-conf) to, _as if by magic_, load
top-level configuration.

Unfortunately, `require.main.filename` sometimes fails when an application is
executed with an alternative process manager, e.g., [iisnode](https://github.com/tjanczuk/iisnode).

`require-main-filename` is a shim that addresses this problem.

## Usage

```js
var main = require('require-main-filename')()
// use main as an alternative to require.main.filename.
```

## License

ISC
discontinuous-range
===================

```
DiscontinuousRange(1, 10).subtract(4, 6); // [ 1-3, 7-10 ]
```

  [![Build Status](https://travis-ci.org/dtudury/discontinuous-range.png)](https://travis-ci.org/dtudury/discontinuous-range)

this is a pretty simple module, but it exists to service another project
so this'll be pretty lacking documentation. 
reading the test to see how this works may help.  otherwise, here's an example
that I think pretty much sums it up

###Example
```
var all_numbers = new DiscontinuousRange(1, 100);
var bad_numbers = DiscontinuousRange(13).add(8).add(60,80);
var good_numbers = all_numbers.clone().subtract(bad_numbers);
console.log(good_numbers.toString()); //[ 1-7, 9-12, 14-59, 81-100 ]
var random_good_number = good_numbers.index(Math.floor(Math.random() * good_numbers.length));
```
## Follow Redirects

Drop-in replacement for Nodes `http` and `https` that automatically follows redirects.

[![npm version](https://img.shields.io/npm/v/follow-redirects.svg)](https://www.npmjs.com/package/follow-redirects)
[![Build Status](https://travis-ci.org/follow-redirects/follow-redirects.svg?branch=master)](https://travis-ci.org/follow-redirects/follow-redirects)
[![Coverage Status](https://coveralls.io/repos/follow-redirects/follow-redirects/badge.svg?branch=master)](https://coveralls.io/r/follow-redirects/follow-redirects?branch=master)
[![Dependency Status](https://david-dm.org/follow-redirects/follow-redirects.svg)](https://david-dm.org/follow-redirects/follow-redirects)
[![npm downloads](https://img.shields.io/npm/dm/follow-redirects.svg)](https://www.npmjs.com/package/follow-redirects)

`follow-redirects` provides [request](https://nodejs.org/api/http.html#http_http_request_options_callback) and [get](https://nodejs.org/api/http.html#http_http_get_options_callback)
 methods that behave identically to those found on the native [http](https://nodejs.org/api/http.html#http_http_request_options_callback) and [https](https://nodejs.org/api/https.html#https_https_request_options_callback)
 modules, with the exception that they will seamlessly follow redirects.

```javascript
var http = require('follow-redirects').http;
var https = require('follow-redirects').https;

http.get('http://bit.ly/900913', function (response) {
  response.on('data', function (chunk) {
    console.log(chunk);
  });
}).on('error', function (err) {
  console.error(err);
});
```

You can inspect the final redirected URL through the `responseUrl` property on the `response`.
If no redirection happened, `responseUrl` is the original request URL.

```javascript
https.request({
  host: 'bitly.com',
  path: '/UHfDGO',
}, function (response) {
  console.log(response.responseUrl);
  // 'http://duckduckgo.com/robots.txt'
});
```

## Options
### Global options
Global options are set directly on the `follow-redirects` module:

```javascript
var followRedirects = require('follow-redirects');
followRedirects.maxRedirects = 10;
followRedirects.maxBodyLength = 20 * 1024 * 1024; // 20 MB
```

The following global options are supported:

- `maxRedirects` (default: `21`) – sets the maximum number of allowed redirects; if exceeded, an error will be emitted.

- `maxBodyLength` (default: 10MB) – sets the maximum size of the request body; if exceeded, an error will be emitted.

### Per-request options
Per-request options are set by passing an `options` object:

```javascript
var url = require('url');
var followRedirects = require('follow-redirects');

var options = url.parse('http://bit.ly/900913');
options.maxRedirects = 10;
http.request(options);
```

In addition to the [standard HTTP](https://nodejs.org/api/http.html#http_http_request_options_callback) and [HTTPS options](https://nodejs.org/api/https.html#https_https_request_options_callback),
the following per-request options are supported:
- `followRedirects` (default: `true`) – whether redirects should be followed.

- `maxRedirects` (default: `21`) – sets the maximum number of allowed redirects; if exceeded, an error will be emitted.

- `maxBodyLength` (default: 10MB) – sets the maximum size of the request body; if exceeded, an error will be emitted.

- `agents` (default: `undefined`) – sets the `agent` option per protocol, since HTTP and HTTPS use different agents. Example value: `{ http: new http.Agent(), https: new https.Agent() }`

- `trackRedirects` (default: `false`) – whether to store the redirected response details into the `redirects` array on the response object.

### Advanced usage
By default, `follow-redirects` will use the Node.js default implementations
of [`http`](https://nodejs.org/api/http.html)
and [`https`](https://nodejs.org/api/https.html).
To enable features such as caching and/or intermediate request tracking,
you might instead want to wrap `follow-redirects` around custom protocol implementations:

```javascript
var followRedirects = require('follow-redirects').wrap({
  http: require('your-custom-http'),
  https: require('your-custom-https'),
});
```

Such custom protocols only need an implementation of the `request` method.

## Browserify Usage

Due to the way `XMLHttpRequest` works, the `browserify` versions of `http` and `https` already follow redirects.
 If you are *only* targeting the browser, then this library has little value for you. If you want to write cross
 platform code for node and the browser, `follow-redirects` provides a great solution for making the native node
 modules behave the same as they do in browserified builds in the browser. To avoid bundling unnecessary code
 you should tell browserify to swap out `follow-redirects` with the standard modules when bundling.
 To make this easier, you need to change how you require the modules:

```javascript
var http = require('follow-redirects/http');
var https = require('follow-redirects/https');
```

You can then replace `follow-redirects` in your browserify configuration like so:

```javascript
"browser": {
  "follow-redirects/http"  : "http",
  "follow-redirects/https" : "https"
}
```

The `browserify-http` module has not kept pace with node development, and no long behaves identically to the native
 module when running in the browser. If you are experiencing problems, you may want to check out
 [browserify-http-2](https://www.npmjs.com/package/http-browserify-2). It is more actively maintained and
 attempts to address a few of the shortcomings of `browserify-http`. In that case, your browserify config should
 look something like this:

```javascript
"browser": {
  "follow-redirects/http"  : "browserify-http-2/http",
  "follow-redirects/https" : "browserify-http-2/https"
}
```

## Contributing

Pull Requests are always welcome. Please [file an issue](https://github.com/follow-redirects/follow-redirects/issues)
 detailing your proposal before you invest your valuable time. Additional features and bug fixes should be accompanied
 by tests. You can run the test suite locally with a simple `npm test` command.

## Debug Logging

`follow-redirects` uses the excellent [debug](https://www.npmjs.com/package/debug) for logging. To turn on logging
 set the environment variable `DEBUG=follow-redirects` for debug output from just this module. When running the test
 suite it is sometimes advantageous to set `DEBUG=*` to see output from the express server as well.

## Authors

- Olivier Lalonde (olalonde@gmail.com)
- James Talmage (james@talmage.io)
- [Ruben Verborgh](https://ruben.verborgh.org/)

## License

[https://github.com/follow-redirects/follow-redirects/blob/master/LICENSE](MIT License)
# yargs-parser

[![Build Status](https://travis-ci.org/yargs/yargs-parser.svg)](https://travis-ci.org/yargs/yargs-parser)
[![NPM version](https://img.shields.io/npm/v/yargs-parser.svg)](https://www.npmjs.com/package/yargs-parser)
[![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version)

The mighty option parser used by [yargs](https://github.com/yargs/yargs).

visit the [yargs website](http://yargs.js.org/) for more examples, and thorough usage instructions.

<img width="250" src="https://raw.githubusercontent.com/yargs/yargs-parser/master/yargs-logo.png">

## Example

```sh
npm i yargs-parser --save
```

```js
var argv = require('yargs-parser')(process.argv.slice(2))
console.log(argv)
```

```sh
node example.js --foo=33 --bar hello
{ _: [], foo: 33, bar: 'hello' }
```

_or parse a string!_

```js
var argv = require('yargs-parser')('--foo=99 --bar=33')
console.log(argv)
```

```sh
{ _: [], foo: 99, bar: 33 }
```

Convert an array of mixed types before passing to `yargs-parser`:

```js
var parse = require('yargs-parser')
parse(['-f', 11, '--zoom', 55].join(' '))   // <-- array to string
parse(['-f', 11, '--zoom', 55].map(String)) // <-- array of strings
```

## API

### require('yargs-parser')(args, opts={})

Parses command line arguments returning a simple mapping of keys and values.

**expects:**

* `args`: a string or array of strings representing the options to parse.
* `opts`: provide a set of hints indicating how `args` should be parsed:
  * `opts.alias`: an object representing the set of aliases for a key: `{alias: {foo: ['f']}}`.
  * `opts.array`: indicate that keys should be parsed as an array: `{array: ['foo', 'bar']}`.<br>
    Indicate that keys should be parsed as an array and coerced to booleans / numbers:<br>
    `{array: [{ key: 'foo', boolean: true }, {key: 'bar', number: true}]}`.
  * `opts.boolean`: arguments should be parsed as booleans: `{boolean: ['x', 'y']}`.
  * `opts.coerce`: provide a custom synchronous function that returns a coerced value from the argument provided
    (or throws an error). For arrays the function is called only once for the entire array:<br>
    `{coerce: {foo: function (arg) {return modifiedArg}}}`.
  * `opts.config`: indicate a key that represents a path to a configuration file (this file will be loaded and parsed).
  * `opts.configObjects`: configuration objects to parse, their properties will be set as arguments:<br>
    `{configObjects: [{'x': 5, 'y': 33}, {'z': 44}]}`.
  * `opts.configuration`: provide configuration options to the yargs-parser (see: [configuration](#configuration)).
  * `opts.count`: indicate a key that should be used as a counter, e.g., `-vvv` = `{v: 3}`.
  * `opts.default`: provide default values for keys: `{default: {x: 33, y: 'hello world!'}}`.
  * `opts.envPrefix`: environment variables (`process.env`) with the prefix provided should be parsed.
  * `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`.
  * `opts.normalize`: `path.normalize()` will be applied to values set to this key.
  * `opts.number`: keys should be treated as numbers.
  * `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`).

**returns:**

* `obj`: an object representing the parsed value of `args`
  * `key/value`: key value pairs for each argument and their aliases.
  * `_`: an array representing the positional arguments.
  * [optional] `--`:  an array with arguments after the end-of-options flag `--`.

### require('yargs-parser').detailed(args, opts={})

Parses a command line string, returning detailed information required by the
yargs engine.

**expects:**

* `args`: a string or array of strings representing options to parse.
* `opts`: provide a set of hints indicating how `args`, inputs are identical to `require('yargs-parser')(args, opts={})`.

**returns:**

* `argv`: an object representing the parsed value of `args`
  * `key/value`: key value pairs for each argument and their aliases.
  * `_`: an array representing the positional arguments.
  * [optional] `--`:  an array with arguments after the end-of-options flag `--`.
* `error`: populated with an error object if an exception occurred during parsing.
* `aliases`: the inferred list of aliases built by combining lists in `opts.alias`.
* `newAliases`: any new aliases added via camel-case expansion:
  * `boolean`: `{ fooBar: true }`
* `defaulted`: any new argument created by `opts.default`, no aliases included.
  * `boolean`: `{ foo: true }`
* `configuration`: given by default settings and `opts.configuration`.

<a name="configuration"></a>

### Configuration

The yargs-parser applies several automated transformations on the keys provided
in `args`. These features can be turned on and off using the `configuration` field
of `opts`.

```js
var parsed = parser(['--no-dice'], {
  configuration: {
    'boolean-negation': false
  }
})
```

### short option groups

* default: `true`.
* key: `short-option-groups`.

Should a group of short-options be treated as boolean flags?

```sh
node example.js -abc
{ _: [], a: true, b: true, c: true }
```

_if disabled:_

```sh
node example.js -abc
{ _: [], abc: true }
```

### camel-case expansion

* default: `true`.
* key: `camel-case-expansion`.

Should hyphenated arguments be expanded into camel-case aliases?

```sh
node example.js --foo-bar
{ _: [], 'foo-bar': true, fooBar: true }
```

_if disabled:_

```sh
node example.js --foo-bar
{ _: [], 'foo-bar': true }
```

### dot-notation

* default: `true`
* key: `dot-notation`

Should keys that contain `.` be treated as objects?

```sh
node example.js --foo.bar
{ _: [], foo: { bar: true } }
```

_if disabled:_

```sh
node example.js --foo.bar
{ _: [], "foo.bar": true }
```

### parse numbers

* default: `true`
* key: `parse-numbers`

Should keys that look like numbers be treated as such?

```sh
node example.js --foo=99.3
{ _: [], foo: 99.3 }
```

_if disabled:_

```sh
node example.js --foo=99.3
{ _: [], foo: "99.3" }
```

### boolean negation

* default: `true`
* key: `boolean-negation`

Should variables prefixed with `--no` be treated as negations?

```sh
node example.js --no-foo
{ _: [], foo: false }
```

_if disabled:_

```sh
node example.js --no-foo
{ _: [], "no-foo": true }
```

### combine arrays

* default: `false`
* key: `combine-arrays`

Should arrays be combined when provided by both command line arguments and
a configuration file.

### duplicate arguments array

* default: `true`
* key: `duplicate-arguments-array`

Should arguments be coerced into an array when duplicated:

```sh
node example.js -x 1 -x 2
{ _: [], x: [1, 2] }
```

_if disabled:_

```sh
node example.js -x 1 -x 2
{ _: [], x: 2 }
```

### flatten duplicate arrays

* default: `true`
* key: `flatten-duplicate-arrays`

Should array arguments be coerced into a single array when duplicated:

```sh
node example.js -x 1 2 -x 3 4
{ _: [], x: [1, 2, 3, 4] }
```

_if disabled:_

```sh
node example.js -x 1 2 -x 3 4
{ _: [], x: [[1, 2], [3, 4]] }
```

### greedy arrays

* default: `true`
* key: `greedy-arrays`

Should arrays consume more than one positional argument following their flag.

```sh
node example --arr 1 2
{ _[], arr: [1, 2] }
```

_if disabled:_

```sh
node example --arr 1 2
{ _[2], arr: [1] }
```

**Note: in `v18.0.0` we are considering defaulting greedy arrays to `false`.**

### nargs eats options

* default: `false`
* key: `nargs-eats-options`

Should nargs consume dash options as well as positional arguments.

### negation prefix

* default: `no-`
* key: `negation-prefix`

The prefix to use for negated boolean variables.

```sh
node example.js --no-foo
{ _: [], foo: false }
```

_if set to `quux`:_

```sh
node example.js --quuxfoo
{ _: [], foo: false }
```

### populate --

* default: `false`.
* key: `populate--`

Should unparsed flags be stored in `--` or `_`.

_If disabled:_

```sh
node example.js a -b -- x y
{ _: [ 'a', 'x', 'y' ], b: true }
```

_If enabled:_

```sh
node example.js a -b -- x y
{ _: [ 'a' ], '--': [ 'x', 'y' ], b: true }
```

### set placeholder key

* default: `false`.
* key: `set-placeholder-key`.

Should a placeholder be added for keys not set via the corresponding CLI argument?

_If disabled:_

```sh
node example.js -a 1 -c 2
{ _: [], a: 1, c: 2 }
```

_If enabled:_

```sh
node example.js -a 1 -c 2
{ _: [], a: 1, b: undefined, c: 2 }
```

### halt at non-option

* default: `false`.
* key: `halt-at-non-option`.

Should parsing stop at the first positional argument? This is similar to how e.g. `ssh` parses its command line.

_If disabled:_

```sh
node example.js -a run b -x y
{ _: [ 'b' ], a: 'run', x: 'y' }
```

_If enabled:_

```sh
node example.js -a run b -x y
{ _: [ 'b', '-x', 'y' ], a: 'run' }
```

### strip aliased

* default: `false`
* key: `strip-aliased`

Should aliases be removed before returning results?

_If disabled:_

```sh
node example.js --test-field 1
{ _: [], 'test-field': 1, testField: 1, 'test-alias': 1, testAlias: 1 }
```

_If enabled:_

```sh
node example.js --test-field 1
{ _: [], 'test-field': 1, testField: 1 }
```

### strip dashed

* default: `false`
* key: `strip-dashed`

Should dashed keys be removed before returning results?  This option has no effect if
`camel-case-expansion` is disabled.

_If disabled:_

```sh
node example.js --test-field 1
{ _: [], 'test-field': 1, testField: 1 }
```

_If enabled:_

```sh
node example.js --test-field 1
{ _: [], testField: 1 }
```

### unknown options as args

* default: `false`
* key: `unknown-options-as-args`

Should unknown options be treated like regular arguments?  An unknown option is one that is not
configured in `opts`.

_If disabled_

```sh
node example.js --unknown-option --known-option 2 --string-option --unknown-option2
{ _: [], unknownOption: true, knownOption: 2, stringOption: '', unknownOption2: true }
```

_If enabled_

```sh
node example.js --unknown-option --known-option 2 --string-option --unknown-option2
{ _: ['--unknown-option'], knownOption: 2, stringOption: '--unknown-option2' }
```

## Special Thanks

The yargs project evolves from optimist and minimist. It owes its
existence to a lot of James Halliday's hard work. Thanks [substack](https://github.com/substack) **beep** **boop** \o/

## License

ISC
# 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)
# minipass

A _very_ minimal implementation of a [PassThrough
stream](https://nodejs.org/api/stream.html#stream_class_stream_passthrough)

[It's very
fast](https://docs.google.com/spreadsheets/d/1oObKSrVwLX_7Ut4Z6g3fZW-AX1j1-k6w-cDsrkaSbHM/edit#gid=0)
for objects, strings, and buffers.

Supports pipe()ing (including multi-pipe() and backpressure transmission),
buffering data until either a `data` event handler or `pipe()` is added (so
you don't lose the first chunk), and most other cases where PassThrough is
a good idea.

There is a `read()` method, but it's much more efficient to consume data
from this stream via `'data'` events or by calling `pipe()` into some other
stream.  Calling `read()` requires the buffer to be flattened in some
cases, which requires copying memory.

There is also no `unpipe()` method.  Once you start piping, there is no
stopping it!

If you set `objectMode: true` in the options, then whatever is written will
be emitted.  Otherwise, it'll do a minimal amount of Buffer copying to
ensure proper Streams semantics when `read(n)` is called.

`objectMode` can also be set by doing `stream.objectMode = true`, or by
writing any non-string/non-buffer data.  `objectMode` cannot be set to
false once it is set.

This is not a `through` or `through2` stream.  It doesn't transform the
data, it just passes it right through.  If you want to transform the data,
extend the class, and override the `write()` method.  Once you're done
transforming the data however you want, call `super.write()` with the
transform output.

For some examples of streams that extend Minipass in various ways, check
out:

- [minizlib](http://npm.im/minizlib)
- [fs-minipass](http://npm.im/fs-minipass)
- [tar](http://npm.im/tar)
- [minipass-collect](http://npm.im/minipass-collect)
- [minipass-flush](http://npm.im/minipass-flush)
- [minipass-pipeline](http://npm.im/minipass-pipeline)
- [tap](http://npm.im/tap)
- [tap-parser](http://npm.im/tap)
- [treport](http://npm.im/tap)
- [minipass-fetch](http://npm.im/minipass-fetch)
- [pacote](http://npm.im/pacote)
- [make-fetch-happen](http://npm.im/make-fetch-happen)
- [cacache](http://npm.im/cacache)
- [ssri](http://npm.im/ssri)
- [npm-registry-fetch](http://npm.im/npm-registry-fetch)
- [minipass-json-stream](http://npm.im/minipass-json-stream)
- [minipass-sized](http://npm.im/minipass-sized)

## Differences from Node.js Streams

There are several things that make Minipass streams different from (and in
some ways superior to) Node.js core streams.

Please read these caveats if you are familiar with noode-core streams and
intend to use Minipass streams in your programs.

### Timing

Minipass streams are designed to support synchronous use-cases.  Thus, data
is emitted as soon as it is available, always.  It is buffered until read,
but no longer.  Another way to look at it is that Minipass streams are
exactly as synchronous as the logic that writes into them.

This can be surprising if your code relies on `PassThrough.write()` always
providing data on the next tick rather than the current one, or being able
to call `resume()` and not have the entire buffer disappear immediately.

However, without this synchronicity guarantee, there would be no way for
Minipass to achieve the speeds it does, or support the synchronous use
cases that it does.  Simply put, waiting takes time.

This non-deferring approach makes Minipass streams much easier to reason
about, especially in the context of Promises and other flow-control
mechanisms.

### No High/Low Water Marks

Node.js core streams will optimistically fill up a buffer, returning `true`
on all writes until the limit is hit, even if the data has nowhere to go.
Then, they will not attempt to draw more data in until the buffer size dips
below a minimum value.

Minipass streams are much simpler.  The `write()` method will return `true`
if the data has somewhere to go (which is to say, given the timing
guarantees, that the data is already there by the time `write()` returns).

If the data has nowhere to go, then `write()` returns false, and the data
sits in a buffer, to be drained out immediately as soon as anyone consumes
it.

### Hazards of Buffering (or: Why Minipass Is So Fast)

Since data written to a Minipass stream is immediately written all the way
through the pipeline, and `write()` always returns true/false based on
whether the data was fully flushed, backpressure is communicated
immediately to the upstream caller.  This minimizes buffering.

Consider this case:

```js
const {PassThrough} = require('stream')
const p1 = new PassThrough({ highWaterMark: 1024 })
const p2 = new PassThrough({ highWaterMark: 1024 })
const p3 = new PassThrough({ highWaterMark: 1024 })
const p4 = new PassThrough({ highWaterMark: 1024 })

p1.pipe(p2).pipe(p3).pipe(p4)
p4.on('data', () => console.log('made it through'))

// this returns false and buffers, then writes to p2 on next tick (1)
// p2 returns false and buffers, pausing p1, then writes to p3 on next tick (2)
// p3 returns false and buffers, pausing p2, then writes to p4 on next tick (3)
// p4 returns false and buffers, pausing p3, then emits 'data' and 'drain'
// on next tick (4)
// p3 sees p4's 'drain' event, and calls resume(), emitting 'resume' and
// 'drain' on next tick (5)
// p2 sees p3's 'drain', calls resume(), emits 'resume' and 'drain' on next tick (6)
// p1 sees p2's 'drain', calls resume(), emits 'resume' and 'drain' on next
// tick (7)

p1.write(Buffer.alloc(2048)) // returns false
```

Along the way, the data was buffered and deferred at each stage, and
multiple event deferrals happened, for an unblocked pipeline where it was
perfectly safe to write all the way through!

Furthermore, setting a `highWaterMark` of `1024` might lead someone reading
the code to think an advisory maximum of 1KiB is being set for the
pipeline.  However, the actual advisory buffering level is the _sum_ of
`highWaterMark` values, since each one has its own bucket.

Consider the Minipass case:

```js
const m1 = new Minipass()
const m2 = new Minipass()
const m3 = new Minipass()
const m4 = new Minipass()

m1.pipe(m2).pipe(m3).pipe(m4)
m4.on('data', () => console.log('made it through'))

// m1 is flowing, so it writes the data to m2 immediately
// m2 is flowing, so it writes the data to m3 immediately
// m3 is flowing, so it writes the data to m4 immediately
// m4 is flowing, so it fires the 'data' event immediately, returns true
// m4's write returned true, so m3 is still flowing, returns true
// m3's write returned true, so m2 is still flowing, returns true
// m2's write returned true, so m1 is still flowing, returns true
// No event deferrals or buffering along the way!

m1.write(Buffer.alloc(2048)) // returns true
```

It is extremely unlikely that you _don't_ want to buffer any data written,
or _ever_ buffer data that can be flushed all the way through.  Neither
node-core streams nor Minipass ever fail to buffer written data, but
node-core streams do a lot of unnecessary buffering and pausing.

As always, the faster implementation is the one that does less stuff and
waits less time to do it.

### Immediately emit `end` for empty streams (when not paused)

If a stream is not paused, and `end()` is called before writing any data
into it, then it will emit `end` immediately.

If you have logic that occurs on the `end` event which you don't want to
potentially happen immediately (for example, closing file descriptors,
moving on to the next entry in an archive parse stream, etc.) then be sure
to call `stream.pause()` on creation, and then `stream.resume()` once you
are ready to respond to the `end` event.

### Emit `end` When Asked

One hazard of immediately emitting `'end'` is that you may not yet have had
a chance to add a listener.  In order to avoid this hazard, Minipass
streams safely re-emit the `'end'` event if a new listener is added after
`'end'` has been emitted.

Ie, if you do `stream.on('end', someFunction)`, and the stream has already
emitted `end`, then it will call the handler right away.  (You can think of
this somewhat like attaching a new `.then(fn)` to a previously-resolved
Promise.)

To prevent calling handlers multiple times who would not expect multiple
ends to occur, all listeners are removed from the `'end'` event whenever it
is emitted.

### Impact of "immediate flow" on Tee-streams

A "tee stream" is a stream piping to multiple destinations:

```js
const tee = new Minipass()
t.pipe(dest1)
t.pipe(dest2)
t.write('foo') // goes to both destinations
```

Since Minipass streams _immediately_ process any pending data through the
pipeline when a new pipe destination is added, this can have surprising
effects, especially when a stream comes in from some other function and may
or may not have data in its buffer.

```js
// WARNING! WILL LOSE DATA!
const src = new Minipass()
src.write('foo')
src.pipe(dest1) // 'foo' chunk flows to dest1 immediately, and is gone
src.pipe(dest2) // gets nothing!
```

The solution is to create a dedicated tee-stream junction that pipes to
both locations, and then pipe to _that_ instead.

```js
// Safe example: tee to both places
const src = new Minipass()
src.write('foo')
const tee = new Minipass()
tee.pipe(dest1)
tee.pipe(dest2)
src.pipe(tee) // tee gets 'foo', pipes to both locations
```

The same caveat applies to `on('data')` event listeners.  The first one
added will _immediately_ receive all of the data, leaving nothing for the
second:

```js
// WARNING! WILL LOSE DATA!
const src = new Minipass()
src.write('foo')
src.on('data', handler1) // receives 'foo' right away
src.on('data', handler2) // nothing to see here!
```

Using a dedicated tee-stream can be used in this case as well:

```js
// Safe example: tee to both data handlers
const src = new Minipass()
src.write('foo')
const tee = new Minipass()
tee.on('data', handler1)
tee.on('data', handler2)
src.pipe(tee)
```

## USAGE

It's a stream!  Use it like a stream and it'll most likely do what you
want.

```js
const Minipass = require('minipass')
const mp = new Minipass(options) // optional: { encoding, objectMode }
mp.write('foo')
mp.pipe(someOtherStream)
mp.end('bar')
```

### OPTIONS

* `encoding` How would you like the data coming _out_ of the stream to be
  encoded?  Accepts any values that can be passed to `Buffer.toString()`.
* `objectMode` Emit data exactly as it comes in.  This will be flipped on
  by default if you write() something other than a string or Buffer at any
  point.  Setting `objectMode: true` will prevent setting any encoding
  value.

### API

Implements the user-facing portions of Node.js's `Readable` and `Writable`
streams.

### Methods

* `write(chunk, [encoding], [callback])` - Put data in.  (Note that, in the
  base Minipass class, the same data will come out.)  Returns `false` if
  the stream will buffer the next write, or true if it's still in "flowing"
  mode.
* `end([chunk, [encoding]], [callback])` - Signal that you have no more
  data to write.  This will queue an `end` event to be fired when all the
  data has been consumed.
* `setEncoding(encoding)` - Set the encoding for data coming of the stream.
  This can only be done once.
* `pause()` - No more data for a while, please.  This also prevents `end`
  from being emitted for empty streams until the stream is resumed.
* `resume()` - Resume the stream.  If there's data in the buffer, it is all
  discarded.  Any buffered events are immediately emitted.
* `pipe(dest)` - Send all output to the stream provided.  There is no way
  to unpipe.  When data is emitted, it is immediately written to any and
  all pipe destinations.
* `on(ev, fn)`, `emit(ev, fn)` - Minipass streams are EventEmitters.  Some
  events are given special treatment, however.  (See below under "events".)
* `promise()` - Returns a Promise that resolves when the stream emits
  `end`, or rejects if the stream emits `error`.
* `collect()` - Return a Promise that resolves on `end` with an array
  containing each chunk of data that was emitted, or rejects if the stream
  emits `error`.  Note that this consumes the stream data.
* `concat()` - Same as `collect()`, but concatenates the data into a single
  Buffer object.  Will reject the returned promise if the stream is in
  objectMode, or if it goes into objectMode by the end of the data.
* `read(n)` - Consume `n` bytes of data out of the buffer.  If `n` is not
  provided, then consume all of it.  If `n` bytes are not available, then
  it returns null.  **Note** consuming streams in this way is less
  efficient, and can lead to unnecessary Buffer copying.
* `destroy([er])` - Destroy the stream.  If an error is provided, then an
  `'error'` event is emitted.  If the stream has a `close()` method, and
  has not emitted a `'close'` event yet, then `stream.close()` will be
  called.  Any Promises returned by `.promise()`, `.collect()` or
  `.concat()` will be rejected.  After being destroyed, writing to the
  stream will emit an error.  No more data will be emitted if the stream is
  destroyed, even if it was previously buffered.

### Properties

* `bufferLength` Read-only.  Total number of bytes buffered, or in the case
  of objectMode, the total number of objects.
* `encoding` The encoding that has been set.  (Setting this is equivalent
  to calling `setEncoding(enc)` and has the same prohibition against
  setting multiple times.)
* `flowing` Read-only.  Boolean indicating whether a chunk written to the
  stream will be immediately emitted.
* `emittedEnd` Read-only.  Boolean indicating whether the end-ish events
  (ie, `end`, `prefinish`, `finish`) have been emitted.  Note that
  listening on any end-ish event will immediateyl re-emit it if it has
  already been emitted.
* `writable` Whether the stream is writable.  Default `true`.  Set to
  `false` when `end()`
* `readable` Whether the stream is readable.  Default `true`.
* `buffer` A [yallist](http://npm.im/yallist) linked list of chunks written
  to the stream that have not yet been emitted.  (It's probably a bad idea
  to mess with this.)
* `pipes` A [yallist](http://npm.im/yallist) linked list of streams that
  this stream is piping into.  (It's probably a bad idea to mess with
  this.)
* `destroyed` A getter that indicates whether the stream was destroyed.
* `paused` True if the stream has been explicitly paused, otherwise false.
* `objectMode` Indicates whether the stream is in `objectMode`.  Once set
  to `true`, it cannot be set to `false`.

### Events

* `data` Emitted when there's data to read.  Argument is the data to read.
  This is never emitted while not flowing.  If a listener is attached, that
  will resume the stream.
* `end` Emitted when there's no more data to read.  This will be emitted
  immediately for empty streams when `end()` is called.  If a listener is
  attached, and `end` was already emitted, then it will be emitted again.
  All listeners are removed when `end` is emitted.
* `prefinish` An end-ish event that follows the same logic as `end` and is
  emitted in the same conditions where `end` is emitted.  Emitted after
  `'end'`.
* `finish` An end-ish event that follows the same logic as `end` and is
  emitted in the same conditions where `end` is emitted.  Emitted after
  `'prefinish'`.
* `close` An indication that an underlying resource has been released.
  Minipass does not emit this event, but will defer it until after `end`
  has been emitted, since it throws off some stream libraries otherwise.
* `drain` Emitted when the internal buffer empties, and it is again
  suitable to `write()` into the stream.
* `readable` Emitted when data is buffered and ready to be read by a
  consumer.
* `resume` Emitted when stream changes state from buffering to flowing
  mode.  (Ie, when `resume` is called, `pipe` is called, or a `data` event
  listener is added.)

### Static Methods

* `Minipass.isStream(stream)` Returns `true` if the argument is a stream,
  and false otherwise.  To be considered a stream, the object must be
  either an instance of Minipass, or an EventEmitter that has either a
  `pipe()` method, or both `write()` and `end()` methods.  (Pretty much any
  stream in node-land will return `true` for this.)

## EXAMPLES

Here are some examples of things you can do with Minipass streams.

### simple "are you done yet" promise

```js
mp.promise().then(() => {
  // stream is finished
}, er => {
  // stream emitted an error
})
```

### collecting

```js
mp.collect().then(all => {
  // all is an array of all the data emitted
  // encoding is supported in this case, so
  // so the result will be a collection of strings if
  // an encoding is specified, or buffers/objects if not.
  //
  // In an async function, you may do
  // const data = await stream.collect()
})
```

### collecting into a single blob

This is a bit slower because it concatenates the data into one chunk for
you, but if you're going to do it yourself anyway, it's convenient this
way:

```js
mp.concat().then(onebigchunk => {
  // onebigchunk is a string if the stream
  // had an encoding set, or a buffer otherwise.
})
```

### iteration

You can iterate over streams synchronously or asynchronously in platforms
that support it.

Synchronous iteration will end when the currently available data is
consumed, even if the `end` event has not been reached.  In string and
buffer mode, the data is concatenated, so unless multiple writes are
occurring in the same tick as the `read()`, sync iteration loops will
generally only have a single iteration.

To consume chunks in this way exactly as they have been written, with no
flattening, create the stream with the `{ objectMode: true }` option.

```js
const mp = new Minipass({ objectMode: true })
mp.write('a')
mp.write('b')
for (let letter of mp) {
  console.log(letter) // a, b
}
mp.write('c')
mp.write('d')
for (let letter of mp) {
  console.log(letter) // c, d
}
mp.write('e')
mp.end()
for (let letter of mp) {
  console.log(letter) // e
}
for (let letter of mp) {
  console.log(letter) // nothing
}
```

Asynchronous iteration will continue until the end event is reached,
consuming all of the data.

```js
const mp = new Minipass({ encoding: 'utf8' })

// some source of some data
let i = 5
const inter = setInterval(() => {
  if (i --> 0)
    mp.write(Buffer.from('foo\n', 'utf8'))
  else {
    mp.end()
    clearInterval(inter)
  }
}, 100)

// consume the data with asynchronous iteration
async function consume () {
  for await (let chunk of mp) {
    console.log(chunk)
  }
  return 'ok'
}

consume().then(res => console.log(res))
// logs `foo\n` 5 times, and then `ok`
```

### subclass that `console.log()`s everything written into it

```js
class Logger extends Minipass {
  write (chunk, encoding, callback) {
    console.log('WRITE', chunk, encoding)
    return super.write(chunk, encoding, callback)
  }
  end (chunk, encoding, callback) {
    console.log('END', chunk, encoding)
    return super.end(chunk, encoding, callback)
  }
}

someSource.pipe(new Logger()).pipe(someDest)
```

### same thing, but using an inline anonymous class

```js
// js classes are fun
someSource
  .pipe(new (class extends Minipass {
    emit (ev, ...data) {
      // let's also log events, because debugging some weird thing
      console.log('EMIT', ev)
      return super.emit(ev, ...data)
    }
    write (chunk, encoding, callback) {
      console.log('WRITE', chunk, encoding)
      return super.write(chunk, encoding, callback)
    }
    end (chunk, encoding, callback) {
      console.log('END', chunk, encoding)
      return super.end(chunk, encoding, callback)
    }
  }))
  .pipe(someDest)
```

### subclass that defers 'end' for some reason

```js
class SlowEnd extends Minipass {
  emit (ev, ...args) {
    if (ev === 'end') {
      console.log('going to end, hold on a sec')
      setTimeout(() => {
        console.log('ok, ready to end now')
        super.emit('end', ...args)
      }, 100)
    } else {
      return super.emit(ev, ...args)
    }
  }
}
```

### transform that creates newline-delimited JSON

```js
class NDJSONEncode extends Minipass {
  write (obj, cb) {
    try {
      // JSON.stringify can throw, emit an error on that
      return super.write(JSON.stringify(obj) + '\n', 'utf8', cb)
    } catch (er) {
      this.emit('error', er)
    }
  }
  end (obj, cb) {
    if (typeof obj === 'function') {
      cb = obj
      obj = undefined
    }
    if (obj !== undefined) {
      this.write(obj)
    }
    return super.end(cb)
  }
}
```

### transform that parses newline-delimited JSON

```js
class NDJSONDecode extends Minipass {
  constructor (options) {
    // always be in object mode, as far as Minipass is concerned
    super({ objectMode: true })
    this._jsonBuffer = ''
  }
  write (chunk, encoding, cb) {
    if (typeof chunk === 'string' &&
        typeof encoding === 'string' &&
        encoding !== 'utf8') {
      chunk = Buffer.from(chunk, encoding).toString()
    } else if (Buffer.isBuffer(chunk))
      chunk = chunk.toString()
    }
    if (typeof encoding === 'function') {
      cb = encoding
    }
    const jsonData = (this._jsonBuffer + chunk).split('\n')
    this._jsonBuffer = jsonData.pop()
    for (let i = 0; i < jsonData.length; i++) {
      let parsed
      try {
        super.write(parsed)
      } catch (er) {
        this.emit('error', er)
        continue
      }
    }
    if (cb)
      cb()
  }
}
```
![](cow.png)

Moo!
====

Moo is a highly-optimised tokenizer/lexer generator. Use it to tokenize your strings, before parsing 'em with a parser like [nearley](https://github.com/hardmath123/nearley) or whatever else you're into.

* [Fast](#is-it-fast)
* [Convenient](#usage)
* uses [Regular Expressions](#on-regular-expressions)
* tracks [Line Numbers](#line-numbers)
* handles [Keywords](#keywords)
* supports [States](#states)
* custom [Errors](#errors)
* is even [Iterable](#iteration)
* has no dependencies
* 4KB minified + gzipped
* Moo!

Is it fast?
-----------

Yup! Flying-cows-and-singed-steak fast.

Moo is the fastest JS tokenizer around. It's **~2–10x** faster than most other tokenizers; it's a **couple orders of magnitude** faster than some of the slower ones.

Define your tokens **using regular expressions**. Moo will compile 'em down to a **single RegExp for performance**. It uses the new ES6 **sticky flag** where possible to make things faster; otherwise it falls back to an almost-as-efficient workaround. (For more than you ever wanted to know about this, read [adventures in the land of substrings and RegExps](http://mrale.ph/blog/2016/11/23/making-less-dart-faster.html).)

You _might_ be able to go faster still by writing your lexer by hand rather than using RegExps, but that's icky.

Oh, and it [avoids parsing RegExps by itself](https://hackernoon.com/the-madness-of-parsing-real-world-javascript-regexps-d9ee336df983#.2l8qu3l76). Because that would be horrible.

Usage
-----

First, you need to do the needful: `$ npm install moo`, or whatever will ship this code to your computer. Alternatively, grab the `moo.js` file by itself and slap it into your web page via a `<script>` tag; moo is completely standalone.

Then you can start roasting your very own lexer/tokenizer:

```js
    const moo = require('moo')

    let lexer = moo.compile({
      WS:      /[ \t]+/,
      comment: /\/\/.*?$/,
      number:  /0|[1-9][0-9]*/,
      string:  /"(?:\\["\\]|[^\n"\\])*"/,
      lparen:  '(',
      rparen:  ')',
      keyword: ['while', 'if', 'else', 'moo', 'cows'],
      NL:      { match: /\n/, lineBreaks: true },
    })
```

And now throw some text at it:

```js
    lexer.reset('while (10) cows\nmoo')
    lexer.next() // -> { type: 'keyword', value: 'while' }
    lexer.next() // -> { type: 'WS', value: ' ' }
    lexer.next() // -> { type: 'lparen', value: '(' }
    lexer.next() // -> { type: 'number', value: '10' }
    // ...
```

When you reach the end of Moo's internal buffer, next() will return `undefined`. You can always `reset()` it and feed it more data when that happens.

On Regular Expressions
----------------------

RegExps are nifty for making tokenizers, but they can be a bit of a pain. Here are some things to be aware of:

* You often want to use **non-greedy quantifiers**: e.g. `*?` instead of `*`. Otherwise your tokens will be longer than you expect:

    ```js
    let lexer = moo.compile({
      string: /".*"/,   // greedy quantifier *
      // ...
    })

    lexer.reset('"foo" "bar"')
    lexer.next() // -> { type: 'string', value: 'foo" "bar' }
    ```

    Better:

    ```js
    let lexer = moo.compile({
      string: /".*?"/,   // non-greedy quantifier *?
      // ...
    })

    lexer.reset('"foo" "bar"')
    lexer.next() // -> { type: 'string', value: 'foo' }
    lexer.next() // -> { type: 'space', value: ' ' }
    lexer.next() // -> { type: 'string', value: 'bar' }
    ```

* The **order of your rules** matters. Earlier ones will take precedence.

    ```js
    moo.compile({
        identifier:  /[a-z0-9]+/,
        number:  /[0-9]+/,
    }).reset('42').next() // -> { type: 'identifier', value: '42' }

    moo.compile({
        number:  /[0-9]+/,
        identifier:  /[a-z0-9]+/,
    }).reset('42').next() // -> { type: 'number', value: '42' }
    ```

* Moo uses **multiline RegExps**. This has a few quirks: for example, the **dot `/./` doesn't include newlines**. Use `[^]` instead if you want to match newlines too.

* Since an excluding character ranges like `/[^ ]/` (which matches anything but a space) _will_ include newlines, you have to be careful not to include them by accident! In particular, the whitespace metacharacter `\s` includes newlines.

Line Numbers
------------

Moo tracks detailed information about the input for you.

It will track line numbers, as long as you **apply the `lineBreaks: true` option to any rules which might contain newlines**. Moo will try to warn you if you forget to do this.

Note that this is `false` by default, for performance reasons: counting the number of lines in a matched token has a small cost. For optimal performance, only match newlines inside a dedicated token:

```js
    newline: {match: '\n', lineBreaks: true},
```

### Token Info ###

Token objects (returned from `next()`) have the following attributes:

* **`type`**: the name of the group, as passed to compile.
* **`text`**: the string that was matched.
* **`value`**: the string that was matched, transformed by your `value` function (if any).
* **`offset`**: the number of bytes from the start of the buffer where the match starts.
* **`lineBreaks`**: the number of line breaks found in the match. (Always zero if this rule has `lineBreaks: false`.)
* **`line`**: the line number of the beginning of the match, starting from 1.
* **`col`**: the column where the match begins, starting from 1.

### Value vs. Text ###

The `value` is the same as the `text`, unless you provide a [value transform](#transform).

```js
const moo = require('moo')

const lexer = moo.compile({
  ws: /[ \t]+/,
  string: {match: /"(?:\\["\\]|[^\n"\\])*"/, value: s => s.slice(1, -1)},
})

lexer.reset('"test"')
lexer.next() /* { value: 'test', text: '"test"', ... } */
```

### Reset ###

Calling `reset()` on your lexer will empty its internal buffer, and set the line, column, and offset counts back to their initial value.

If you don't want this, you can `save()` the state, and later pass it as the second argument to `reset()` to explicitly control the internal state of the lexer.

```js
    lexer.reset('some line\n')
    let info = lexer.save() // -> { line: 10 }
    lexer.next() // -> { line: 10 }
    lexer.next() // -> { line: 11 }
    // ...
    lexer.reset('a different line\n', info)
    lexer.next() // -> { line: 10 }
```

Keywords
--------

Moo makes it convenient to define literals.

```js
    moo.compile({
      lparen:  '(',
      rparen:  ')',
      keyword: ['while', 'if', 'else', 'moo', 'cows'],
    })
```

It'll automatically compile them into regular expressions, escaping them where necessary.

**Keywords** should be written using the `keywords` transform.

```js
    moo.compile({
      IDEN: {match: /[a-zA-Z]+/, type: moo.keywords({
        KW: ['while', 'if', 'else', 'moo', 'cows'],
      })},
      SPACE: {match: /\s+/, lineBreaks: true},
    })
```

### Why? ###

You need to do this to ensure the **longest match** principle applies, even in edge cases.

Imagine trying to parse the input `className` with the following rules:

```js
    keyword: ['class'],
    identifier: /[a-zA-Z]+/,
```

You'll get _two_ tokens — `['class', 'Name']` -- which is _not_ what you want! If you swap the order of the rules, you'll fix this example; but now you'll lex `class` wrong (as an `identifier`).

The keywords helper checks matches against the list of keywords; if any of them match, it uses the type `'keyword'` instead of `'identifier'` (for this example).

### Keyword Types ###

Keywords can also have **individual types**.

```js
    let lexer = moo.compile({
      name: {match: /[a-zA-Z]+/, type: moo.keywords({
        'kw-class': 'class',
        'kw-def': 'def',
        'kw-if': 'if',
      })},
      // ...
    })
    lexer.reset('def foo')
    lexer.next() // -> { type: 'kw-def', value: 'def' }
    lexer.next() // space
    lexer.next() // -> { type: 'name', value: 'foo' }
```

You can use [itt](https://github.com/nathan/itt)'s iterator adapters to make constructing keyword objects easier:

```js
    itt(['class', 'def', 'if'])
    .map(k => ['kw-' + k, k])
    .toObject()
```

States
------

Moo allows you to define multiple lexer **states**. Each state defines its own separate set of token rules. Your lexer will start off in the first state given to `moo.states({})`.

Rules can be annotated with `next`, `push`, and `pop`, to change the current state after that token is matched. A "stack" of past states is kept, which is used by `push` and `pop`.

* **`next: 'bar'`** moves to the state named `bar`. (The stack is not changed.)
* **`push: 'bar'`** moves to the state named `bar`, and pushes the old state onto the stack.
* **`pop: 1`** removes one state from the top of the stack, and moves to that state. (Only `1` is supported.)

Only rules from the current state can be matched. You need to copy your rule into all the states you want it to be matched in.

For example, to tokenize JS-style string interpolation such as `a${{c: d}}e`, you might use:

```js
    let lexer = moo.states({
      main: {
        strstart: {match: '`', push: 'lit'},
        ident:    /\w+/,
        lbrace:   {match: '{', push: 'main'},
        rbrace:   {match: '}', pop: true},
        colon:    ':',
        space:    {match: /\s+/, lineBreaks: true},
      },
      lit: {
        interp:   {match: '${', push: 'main'},
        escape:   /\\./,
        strend:   {match: '`', pop: true},
        const:    {match: /(?:[^$`]|\$(?!\{))+/, lineBreaks: true},
      },
    })
    // <= `a${{c: d}}e`
    // => strstart const interp lbrace ident colon space ident rbrace rbrace const strend
```

The `rbrace` rule is annotated with `pop`, so it moves from the `main` state into either `lit` or `main`, depending on the stack.

Errors
------

If none of your rules match, Moo will throw an Error; since it doesn't know what else to do.

If you prefer, you can have moo return an error token instead of throwing an exception. The error token will contain the whole of the rest of the buffer.

```js
    moo.compile({
      // ...
      myError: moo.error,
    })

    moo.reset('invalid')
    moo.next() // -> { type: 'myError', value: 'invalid', text: 'invalid', offset: 0, lineBreaks: 0, line: 1, col: 1 }
    moo.next() // -> undefined
```

You can have a token type that both matches tokens _and_ contains error values.

```js
    moo.compile({
      // ...
      myError: {match: /[\$?`]/, error: true},
    })
```

### Formatting errors ###

If you want to throw an error from your parser, you might find `formatError` helpful. Call it with the offending token:

```js
throw new Error(lexer.formatError(token, "invalid syntax"))
```

It returns a string with a pretty error message.

```
Error: invalid syntax at line 2 col 15:

  totally valid `syntax`
                ^
```

Iteration
---------

Iterators: we got 'em.

```js
    for (let here of lexer) {
      // here = { type: 'number', value: '123', ... }
    }
```

Create an array of tokens.

```js
    let tokens = Array.from(lexer);
```

Use [itt](https://github.com/nathan/itt)'s iteration tools with Moo.

```js
    for (let [here, next] = itt(lexer).lookahead()) { // pass a number if you need more tokens
      // enjoy!
    }
```

Transform
---------

Moo doesn't allow capturing groups, but you can supply a transform function, `value()`, which will be called on the value before storing it in the Token object.

```js
    moo.compile({
      STRING: [
        {match: /"""[^]*?"""/, lineBreaks: true, value: x => x.slice(3, -3)},
        {match: /"(?:\\["\\rn]|[^"\\])*?"/, lineBreaks: true, value: x => x.slice(1, -1)},
        {match: /'(?:\\['\\rn]|[^'\\])*?'/, lineBreaks: true, value: x => x.slice(1, -1)},
      ],
      // ...
    })
```

Contributing
------------

Do check the [FAQ](https://github.com/tjvr/moo/issues?q=label%3Aquestion).

Before submitting an issue, [remember...](https://github.com/tjvr/moo/blob/master/.github/CONTRIBUTING.md)
Like `chown -R`.

Takes the same arguments as `fs.chown()`
# 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)
```
# Punycode.js [![Build status](https://travis-ci.org/bestiejs/punycode.js.svg?branch=master)](https://travis-ci.org/bestiejs/punycode.js) [![Code coverage status](http://img.shields.io/codecov/c/github/bestiejs/punycode.js.svg)](https://codecov.io/gh/bestiejs/punycode.js) [![Dependency status](https://gemnasium.com/bestiejs/punycode.js.svg)](https://gemnasium.com/bestiejs/punycode.js)

Punycode.js is a robust Punycode converter that fully complies to [RFC 3492](https://tools.ietf.org/html/rfc3492) and [RFC 5891](https://tools.ietf.org/html/rfc5891).

This JavaScript library is the result of comparing, optimizing and documenting different open-source implementations of the Punycode algorithm:

* [The C example code from RFC 3492](https://tools.ietf.org/html/rfc3492#appendix-C)
* [`punycode.c` by _Markus W. Scherer_ (IBM)](http://opensource.apple.com/source/ICU/ICU-400.42/icuSources/common/punycode.c)
* [`punycode.c` by _Ben Noordhuis_](https://github.com/bnoordhuis/punycode/blob/master/punycode.c)
* [JavaScript implementation by _some_](http://stackoverflow.com/questions/183485/can-anyone-recommend-a-good-free-javascript-for-punycode-to-unicode-conversion/301287#301287)
* [`punycode.js` by _Ben Noordhuis_](https://github.com/joyent/node/blob/426298c8c1c0d5b5224ac3658c41e7c2a3fe9377/lib/punycode.js) (note: [not fully compliant](https://github.com/joyent/node/issues/2072))

This project was [bundled](https://github.com/joyent/node/blob/master/lib/punycode.js) with Node.js from [v0.6.2+](https://github.com/joyent/node/compare/975f1930b1...61e796decc) until [v7](https://github.com/nodejs/node/pull/7941) (soft-deprecated).

The current version supports recent versions of Node.js only. It provides a CommonJS module and an ES6 module. For the old version that offers the same functionality with broader support, including Rhino, Ringo, Narwhal, and web browsers, see [v1.4.1](https://github.com/bestiejs/punycode.js/releases/tag/v1.4.1).

## Installation

Via [npm](https://www.npmjs.com/):

```bash
npm install punycode --save
```

In [Node.js](https://nodejs.org/):

```js
const punycode = require('punycode');
```

## API

### `punycode.decode(string)`

Converts a Punycode string of ASCII symbols to a string of Unicode symbols.

```js
// decode domain name parts
punycode.decode('maana-pta'); // 'mañana'
punycode.decode('--dqo34k'); // '☃-⌘'
```

### `punycode.encode(string)`

Converts a string of Unicode symbols to a Punycode string of ASCII symbols.

```js
// encode domain name parts
punycode.encode('mañana'); // 'maana-pta'
punycode.encode('☃-⌘'); // '--dqo34k'
```

### `punycode.toUnicode(input)`

Converts a Punycode string representing a domain name or an email address to Unicode. Only the Punycoded parts of the input will be converted, i.e. it doesn’t matter if you call it on a string that has already been converted to Unicode.

```js
// decode domain names
punycode.toUnicode('xn--maana-pta.com');
// → 'mañana.com'
punycode.toUnicode('xn----dqo34k.com');
// → '☃-⌘.com'

// decode email addresses
punycode.toUnicode('джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq');
// → 'джумла@джpумлатест.bрфa'
```

### `punycode.toASCII(input)`

Converts a lowercased Unicode string representing a domain name or an email address to Punycode. Only the non-ASCII parts of the input will be converted, i.e. it doesn’t matter if you call it with a domain that’s already in ASCII.

```js
// encode domain names
punycode.toASCII('mañana.com');
// → 'xn--maana-pta.com'
punycode.toASCII('☃-⌘.com');
// → 'xn----dqo34k.com'

// encode email addresses
punycode.toASCII('джумла@джpумлатест.bрфa');
// → 'джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq'
```

### `punycode.ucs2`

#### `punycode.ucs2.decode(string)`

Creates an array containing the numeric code point values of each Unicode symbol in the string. While [JavaScript uses UCS-2 internally](https://mathiasbynens.be/notes/javascript-encoding), this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16.

```js
punycode.ucs2.decode('abc');
// → [0x61, 0x62, 0x63]
// surrogate pair for U+1D306 TETRAGRAM FOR CENTRE:
punycode.ucs2.decode('\uD834\uDF06');
// → [0x1D306]
```

#### `punycode.ucs2.encode(codePoints)`

Creates a string based on an array of numeric code point values.

```js
punycode.ucs2.encode([0x61, 0x62, 0x63]);
// → 'abc'
punycode.ucs2.encode([0x1D306]);
// → '\uD834\uDF06'
```

### `punycode.version`

A string representing the current Punycode.js version number.

## Author

| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") |
|---|
| [Mathias Bynens](https://mathiasbynens.be/) |

## License

Punycode.js is available under the [MIT](https://mths.be/mit) license.
# minimatch

A minimal matching utility.

[![Build Status](https://secure.travis-ci.org/isaacs/minimatch.svg)](http://travis-ci.org/isaacs/minimatch)

This is the matching library used internally by npm.

It works by converting glob expressions into JavaScript `RegExp`
objects.

## Usage

```javascript
var minimatch = require("minimatch")

minimatch("bar.foo", "*.foo") // true!
minimatch("bar.foo", "*.bar") // false!
minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy!
```

## Features

Supports these glob features:

* Brace Expansion
* Extended glob matching
* "Globstar" `**` matching

See:

* `man sh`
* `man bash`
* `man 3 fnmatch`
* `man 5 gitignore`

## Minimatch Class

Create a minimatch object by instantiating the `minimatch.Minimatch` class.

```javascript
var Minimatch = require("minimatch").Minimatch
var mm = new Minimatch(pattern, options)
```

### Properties

* `pattern` The original pattern the minimatch object represents.
* `options` The options supplied to the constructor.
* `set` A 2-dimensional array of regexp or string expressions.
  Each row in the
  array corresponds to a brace-expanded pattern.  Each item in the row
  corresponds to a single path-part.  For example, the pattern
  `{a,b/c}/d` would expand to a set of patterns like:

        [ [ a, d ]
        , [ b, c, d ] ]

    If a portion of the pattern doesn't have any "magic" in it
    (that is, it's something like `"foo"` rather than `fo*o?`), then it
    will be left as a string rather than converted to a regular
    expression.

* `regexp` Created by the `makeRe` method.  A single regular expression
  expressing the entire pattern.  This is useful in cases where you wish
  to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled.
* `negate` True if the pattern is negated.
* `comment` True if the pattern is a comment.
* `empty` True if the pattern is `""`.

### Methods

* `makeRe` Generate the `regexp` member if necessary, and return it.
  Will return `false` if the pattern is invalid.
* `match(fname)` Return true if the filename matches the pattern, or
  false otherwise.
* `matchOne(fileArray, patternArray, partial)` Take a `/`-split
  filename, and match it against a single row in the `regExpSet`.  This
  method is mainly for internal use, but is exposed so that it can be
  used by a glob-walker that needs to avoid excessive filesystem calls.

All other methods are internal, and will be called as necessary.

### minimatch(path, pattern, options)

Main export.  Tests a path against the pattern using the options.

```javascript
var isJS = minimatch(file, "*.js", { matchBase: true })
```

### minimatch.filter(pattern, options)

Returns a function that tests its
supplied argument, suitable for use with `Array.filter`.  Example:

```javascript
var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true}))
```

### minimatch.match(list, pattern, options)

Match against the list of
files, in the style of fnmatch or glob.  If nothing is matched, and
options.nonull is set, then return a list containing the pattern itself.

```javascript
var javascripts = minimatch.match(fileList, "*.js", {matchBase: true}))
```

### minimatch.makeRe(pattern, options)

Make a regular expression object from the pattern.

## Options

All options are `false` by default.

### debug

Dump a ton of stuff to stderr.

### nobrace

Do not expand `{a,b}` and `{1..3}` brace sets.

### noglobstar

Disable `**` matching against multiple folder names.

### dot

Allow patterns to match filenames starting with a period, even if
the pattern does not explicitly have a period in that spot.

Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot`
is set.

### noext

Disable "extglob" style patterns like `+(a|b)`.

### nocase

Perform a case-insensitive match.

### nonull

When a match is not found by `minimatch.match`, return a list containing
the pattern itself if this option is set.  When not set, an empty list
is returned if there are no matches.

### matchBase

If set, then patterns without slashes will be matched
against the basename of the path if it contains slashes.  For example,
`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`.

### nocomment

Suppress the behavior of treating `#` at the start of a pattern as a
comment.

### nonegate

Suppress the behavior of treating a leading `!` character as negation.

### flipNegate

Returns from negate expressions the same as if they were not negated.
(Ie, true on a hit, false on a miss.)

## Comparisons to other fnmatch/glob implementations

While strict compliance with the existing standards is a worthwhile
goal, some discrepancies exist between minimatch and other
implementations, and are intentional.

If the pattern starts with a `!` character, then it is negated.  Set the
`nonegate` flag to suppress this behavior, and treat leading `!`
characters normally.  This is perhaps relevant if you wish to start the
pattern with a negative extglob pattern like `!(a|B)`.  Multiple `!`
characters at the start of a pattern will negate the pattern multiple
times.

If a pattern starts with `#`, then it is treated as a comment, and
will not match anything.  Use `\#` to match a literal `#` at the
start of a line, or set the `nocomment` flag to suppress this behavior.

The double-star character `**` is supported by default, unless the
`noglobstar` flag is set.  This is supported in the manner of bsdglob
and bash 4.1, where `**` only has special significance if it is the only
thing in a path part.  That is, `a/**/b` will match `a/x/y/b`, but
`a/**b` will not.

If an escaped pattern has no matches, and the `nonull` flag is set,
then minimatch.match returns the pattern as-provided, rather than
interpreting the character escapes.  For example,
`minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than
`"*a?"`.  This is akin to setting the `nullglob` option in bash, except
that it does not resolve escaped pattern characters.

If brace expansion is not disabled, then it is performed before any
other interpretation of the glob pattern.  Thus, a pattern like
`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded
**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are
checked for validity.  Since those two are valid, matching proceeds.
# brace-expansion

[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), 
as known from sh/bash, in JavaScript.

[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion)
[![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion)
[![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/)

[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion)

## Example

```js
var expand = require('brace-expansion');

expand('file-{a,b,c}.jpg')
// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg']

expand('-v{,,}')
// => ['-v', '-v', '-v']

expand('file{0..2}.jpg')
// => ['file0.jpg', 'file1.jpg', 'file2.jpg']

expand('file-{a..c}.jpg')
// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg']

expand('file{2..0}.jpg')
// => ['file2.jpg', 'file1.jpg', 'file0.jpg']

expand('file{0..4..2}.jpg')
// => ['file0.jpg', 'file2.jpg', 'file4.jpg']

expand('file-{a..e..2}.jpg')
// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg']

expand('file{00..10..5}.jpg')
// => ['file00.jpg', 'file05.jpg', 'file10.jpg']

expand('{{A..C},{a..c}}')
// => ['A', 'B', 'C', 'a', 'b', 'c']

expand('ppp{,config,oe{,conf}}')
// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf']
```

## API

```js
var expand = require('brace-expansion');
```

### var expanded = expand(str)

Return an array of all possible and valid expansions of `str`. If none are
found, `[str]` is returned.

Valid expansions are:

```js
/^(.*,)+(.+)?$/
// {a,b,...}
```

A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`.

```js
/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/
// {x..y[..incr]}
```

A numeric sequence from `x` to `y` inclusive, with optional increment.
If `x` or `y` start with a leading `0`, all the numbers will be padded
to have equal length. Negative numbers and backwards iteration work too.

```js
/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/
// {x..y[..incr]}
```

An alphabetic sequence from `x` to `y` inclusive, with optional increment.
`x` and `y` must be exactly one character, and if given, `incr` must be a
number.

For compatibility reasons, the string `${` is not eligible for brace expansion.

## Installation

With [npm](https://npmjs.org) do:

```bash
npm install brace-expansion
```

## Contributors

- [Julian Gruber](https://github.com/juliangruber)
- [Isaac Z. Schlueter](https://github.com/isaacs)

## Sponsors

This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)!

Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)!

## License

(MIT)

Copyright (c) 2013 Julian Gruber &lt;julian@juliangruber.com&gt;

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# axios

[![npm version](https://img.shields.io/npm/v/axios.svg?style=flat-square)](https://www.npmjs.org/package/axios)
[![build status](https://img.shields.io/travis/axios/axios/master.svg?style=flat-square)](https://travis-ci.org/axios/axios)
[![code coverage](https://img.shields.io/coveralls/mzabriskie/axios.svg?style=flat-square)](https://coveralls.io/r/mzabriskie/axios)
[![install size](https://packagephobia.now.sh/badge?p=axios)](https://packagephobia.now.sh/result?p=axios)
[![npm downloads](https://img.shields.io/npm/dm/axios.svg?style=flat-square)](http://npm-stat.com/charts.html?package=axios)
[![gitter chat](https://img.shields.io/gitter/room/mzabriskie/axios.svg?style=flat-square)](https://gitter.im/mzabriskie/axios)
[![code helpers](https://www.codetriage.com/axios/axios/badges/users.svg)](https://www.codetriage.com/axios/axios)

Promise based HTTP client for the browser and node.js

## Features

- Make [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) from the browser
- Make [http](http://nodejs.org/api/http.html) requests from node.js
- Supports the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API
- Intercept request and response
- Transform request and response data
- Cancel requests
- Automatic transforms for JSON data
- Client side support for protecting against [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)

## Browser Support

![Chrome](https://raw.github.com/alrra/browser-logos/master/src/chrome/chrome_48x48.png) | ![Firefox](https://raw.github.com/alrra/browser-logos/master/src/firefox/firefox_48x48.png) | ![Safari](https://raw.github.com/alrra/browser-logos/master/src/safari/safari_48x48.png) | ![Opera](https://raw.github.com/alrra/browser-logos/master/src/opera/opera_48x48.png) | ![Edge](https://raw.github.com/alrra/browser-logos/master/src/edge/edge_48x48.png) | ![IE](https://raw.github.com/alrra/browser-logos/master/src/archive/internet-explorer_9-11/internet-explorer_9-11_48x48.png) |
--- | --- | --- | --- | --- | --- |
Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 11 ✔ |

[![Browser Matrix](https://saucelabs.com/open_sauce/build_matrix/axios.svg)](https://saucelabs.com/u/axios)

## Installing

Using npm:

```bash
$ npm install axios
```

Using bower:

```bash
$ bower install axios
```

Using yarn:

```bash
$ yarn add axios
```

Using cdn:

```html
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
```

## Example

### note: CommonJS usage
In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with `require()` use the following approach:

```js
const axios = require('axios').default;

// axios.<method> will now provide autocomplete and parameter typings
```

Performing a `GET` request

```js
const axios = require('axios');

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .finally(function () {
    // always executed
  });

// Optionally the request above could also be done as
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .finally(function () {
    // always executed
  });  

// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}
```

> **NOTE:** `async/await` is part of ECMAScript 2017 and is not supported in Internet
> Explorer and older browsers, so use with caution.

Performing a `POST` request

```js
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
```

Performing multiple concurrent requests

```js
function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // Both requests are now complete
  }));
```

## axios API

Requests can be made by passing the relevant config to `axios`.

##### axios(config)

```js
// Send a POST request
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});
```

```js
// GET request for remote image
axios({
  method: 'get',
  url: 'http://bit.ly/2mTM3nY',
  responseType: 'stream'
})
  .then(function (response) {
    response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
  });
```

##### axios(url[, config])

```js
// Send a GET request (default method)
axios('/user/12345');
```

### Request method aliases

For convenience aliases have been provided for all supported request methods.

##### axios.request(config)
##### axios.get(url[, config])
##### axios.delete(url[, config])
##### axios.head(url[, config])
##### axios.options(url[, config])
##### axios.post(url[, data[, config]])
##### axios.put(url[, data[, config]])
##### axios.patch(url[, data[, config]])

###### NOTE
When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config.

### Concurrency

Helper functions for dealing with concurrent requests.

##### axios.all(iterable)
##### axios.spread(callback)

### Creating an instance

You can create a new instance of axios with a custom config.

##### axios.create([config])

```js
const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});
```

### Instance methods

The available instance methods are listed below. The specified config will be merged with the instance config.

##### axios#request(config)
##### axios#get(url[, config])
##### axios#delete(url[, config])
##### axios#head(url[, config])
##### axios#options(url[, config])
##### axios#post(url[, data[, config]])
##### axios#put(url[, data[, config]])
##### axios#patch(url[, data[, config]])
##### axios#getUri([config])

## Request Config

These are the available config options for making requests. Only the `url` is required. Requests will default to `GET` if `method` is not specified.

```js
{
  // `url` is the server URL that will be used for the request
  url: '/user',

  // `method` is the request method to be used when making the request
  method: 'get', // default

  // `baseURL` will be prepended to `url` unless `url` is absolute.
  // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
  // to methods of that instance.
  baseURL: 'https://some-domain.com/api/',

  // `transformRequest` allows changes to the request data before it is sent to the server
  // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'
  // The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
  // FormData or Stream
  // You may modify the headers object.
  transformRequest: [function (data, headers) {
    // Do whatever you want to transform the data

    return data;
  }],

  // `transformResponse` allows changes to the response data to be made before
  // it is passed to then/catch
  transformResponse: [function (data) {
    // Do whatever you want to transform the data

    return data;
  }],

  // `headers` are custom headers to be sent
  headers: {'X-Requested-With': 'XMLHttpRequest'},

  // `params` are the URL parameters to be sent with the request
  // Must be a plain object or a URLSearchParams object
  params: {
    ID: 12345
  },

  // `paramsSerializer` is an optional function in charge of serializing `params`
  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  paramsSerializer: function (params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },

  // `data` is the data to be sent as the request body
  // Only applicable for request methods 'PUT', 'POST', and 'PATCH'
  // When no `transformRequest` is set, must be of one of the following types:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - Browser only: FormData, File, Blob
  // - Node only: Stream, Buffer
  data: {
    firstName: 'Fred'
  },
  
  // syntax alternative to send data into the body
  // method post
  // only the value is sent, not the key
  data: 'Country=Brasil&City=Belo Horizonte',

  // `timeout` specifies the number of milliseconds before the request times out.
  // If the request takes longer than `timeout`, the request will be aborted.
  timeout: 1000, // default is `0` (no timeout)

  // `withCredentials` indicates whether or not cross-site Access-Control requests
  // should be made using credentials
  withCredentials: false, // default

  // `adapter` allows custom handling of requests which makes testing easier.
  // Return a promise and supply a valid response (see lib/adapters/README.md).
  adapter: function (config) {
    /* ... */
  },

  // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
  // This will set an `Authorization` header, overwriting any existing
  // `Authorization` custom headers you have set using `headers`.
  // Please note that only HTTP Basic auth is configurable through this parameter.
  // For Bearer tokens and such, use `Authorization` custom headers instead.
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

  // `responseType` indicates the type of data that the server will respond with
  // options are: 'arraybuffer', 'document', 'json', 'text', 'stream'
  //   browser only: 'blob'
  responseType: 'json', // default

  // `responseEncoding` indicates encoding to use for decoding responses
  // Note: Ignored for `responseType` of 'stream' or client-side requests
  responseEncoding: 'utf8', // default

  // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
  xsrfCookieName: 'XSRF-TOKEN', // default

  // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
  xsrfHeaderName: 'X-XSRF-TOKEN', // default

  // `onUploadProgress` allows handling of progress events for uploads
  onUploadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },

  // `onDownloadProgress` allows handling of progress events for downloads
  onDownloadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },

  // `maxContentLength` defines the max size of the http response content in bytes allowed
  maxContentLength: 2000,

  // `validateStatus` defines whether to resolve or reject the promise for a given
  // HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
  // or `undefined`), the promise will be resolved; otherwise, the promise will be
  // rejected.
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },

  // `maxRedirects` defines the maximum number of redirects to follow in node.js.
  // If set to 0, no redirects will be followed.
  maxRedirects: 5, // default

  // `socketPath` defines a UNIX Socket to be used in node.js.
  // e.g. '/var/run/docker.sock' to send requests to the docker daemon.
  // Only either `socketPath` or `proxy` can be specified.
  // If both are specified, `socketPath` is used.
  socketPath: null, // default

  // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
  // and https requests, respectively, in node.js. This allows options to be added like
  // `keepAlive` that are not enabled by default.
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),

  // 'proxy' defines the hostname and port of the proxy server.
  // You can also define your proxy using the conventional `http_proxy` and
  // `https_proxy` environment variables. If you are using environment variables
  // for your proxy configuration, you can also define a `no_proxy` environment
  // variable as a comma-separated list of domains that should not be proxied.
  // Use `false` to disable proxies, ignoring environment variables.
  // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
  // supplies credentials.
  // This will set an `Proxy-Authorization` header, overwriting any existing
  // `Proxy-Authorization` custom headers you have set using `headers`.
  proxy: {
    host: '127.0.0.1',
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },

  // `cancelToken` specifies a cancel token that can be used to cancel the request
  // (see Cancellation section below for details)
  cancelToken: new CancelToken(function (cancel) {
  })
}
```

## Response Schema

The response for a request contains the following information.

```js
{
  // `data` is the response that was provided by the server
  data: {},

  // `status` is the HTTP status code from the server response
  status: 200,

  // `statusText` is the HTTP status message from the server response
  statusText: 'OK',

  // `headers` the headers that the server responded with
  // All header names are lower cased
  headers: {},

  // `config` is the config that was provided to `axios` for the request
  config: {},

  // `request` is the request that generated this response
  // It is the last ClientRequest instance in node.js (in redirects)
  // and an XMLHttpRequest instance in the browser
  request: {}
}
```

When using `then`, you will receive the response as follows:

```js
axios.get('/user/12345')
  .then(function (response) {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
  });
```

When using `catch`, or passing a [rejection callback](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) as second parameter of `then`, the response will be available through the `error` object as explained in the [Handling Errors](#handling-errors) section.

## Config Defaults

You can specify config defaults that will be applied to every request.

### Global axios defaults

```js
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
```

### Custom instance defaults

```js
// Set config defaults when creating the instance
const instance = axios.create({
  baseURL: 'https://api.example.com'
});

// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
```

### Config order of precedence

Config will be merged with an order of precedence. The order is library defaults found in [lib/defaults.js](https://github.com/axios/axios/blob/master/lib/defaults.js#L28), then `defaults` property of the instance, and finally `config` argument for the request. The latter will take precedence over the former. Here's an example.

```js
// Create an instance using the config defaults provided by the library
// At this point the timeout config value is `0` as is the default for the library
const instance = axios.create();

// Override timeout default for the library
// Now all requests using this instance will wait 2.5 seconds before timing out
instance.defaults.timeout = 2500;

// Override timeout for this request as it's known to take a long time
instance.get('/longRequest', {
  timeout: 5000
});
```

## Interceptors

You can intercept requests or responses before they are handled by `then` or `catch`.

```js
// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  }, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  });
```

If you need to remove an interceptor later you can.

```js
const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
```

You can add interceptors to a custom instance of axios.

```js
const instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
```

## Handling Errors

```js
axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });
```

Using the `validateStatus` config option, you can define HTTP code(s) that should throw an error.

```js
axios.get('/user/12345', {
  validateStatus: function (status) {
    return status < 500; // Reject only if the status code is greater than or equal to 500
  }
})
```

Using `toJSON` you get an object with more information about the HTTP error.

```js
axios.get('/user/12345')
  .catch(function (error) {
    console.log(error.toJSON());
  });
```

## Cancellation

You can cancel a request using a *cancel token*.

> The axios cancel token API is based on the withdrawn [cancelable promises proposal](https://github.com/tc39/proposal-cancelable-promises).

You can create a cancel token using the `CancelToken.source` factory as shown below:

```js
const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function (thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // handle error
  }
});

axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: source.token
})

// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');
```

You can also create a cancel token by passing an executor function to the `CancelToken` constructor:

```js
const CancelToken = axios.CancelToken;
let cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // An executor function receives a cancel function as a parameter
    cancel = c;
  })
});

// cancel the request
cancel();
```

> Note: you can cancel several requests with the same cancel token.

## Using application/x-www-form-urlencoded format

By default, axios serializes JavaScript objects to `JSON`. To send data in the `application/x-www-form-urlencoded` format instead, you can use one of the following options.

### Browser

In a browser, you can use the [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) API as follows:

```js
const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);
```

> Note that `URLSearchParams` is not supported by all browsers (see [caniuse.com](http://www.caniuse.com/#feat=urlsearchparams)), but there is a [polyfill](https://github.com/WebReflection/url-search-params) available (make sure to polyfill the global environment).

Alternatively, you can encode data using the [`qs`](https://github.com/ljharb/qs) library:

```js
const qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));
```

Or in another way (ES6),

```js
import qs from 'qs';
const data = { 'bar': 123 };
const options = {
  method: 'POST',
  headers: { 'content-type': 'application/x-www-form-urlencoded' },
  data: qs.stringify(data),
  url,
};
axios(options);
```

### Node.js

In node.js, you can use the [`querystring`](https://nodejs.org/api/querystring.html) module as follows:

```js
const querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
```

You can also use the [`qs`](https://github.com/ljharb/qs) library.

###### NOTE
The `qs` library is preferable if you need to stringify nested objects, as the `querystring` method has known issues with that use case (https://github.com/nodejs/node-v0.x-archive/issues/1665).

## Semver

Until axios reaches a `1.0` release, breaking changes will be released with a new minor version. For example `0.5.1`, and `0.5.4` will have the same API, but `0.6.0` will have breaking changes.

## Promises

axios depends on a native ES6 Promise implementation to be [supported](http://caniuse.com/promises).
If your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise).

## TypeScript
axios includes [TypeScript](http://typescriptlang.org) definitions.
```typescript
import axios from 'axios';
axios.get('/user?ID=12345');
```

## Resources

* [Changelog](https://github.com/axios/axios/blob/master/CHANGELOG.md)
* [Upgrade Guide](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md)
* [Ecosystem](https://github.com/axios/axios/blob/master/ECOSYSTEM.md)
* [Contributing Guide](https://github.com/axios/axios/blob/master/CONTRIBUTING.md)
* [Code of Conduct](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md)

## Credits

axios is heavily inspired by the [$http service](https://docs.angularjs.org/api/ng/service/$http) provided in [Angular](https://angularjs.org/). Ultimately axios is an effort to provide a standalone `$http`-like service for use outside of Angular.

## License

[MIT](LICENSE)
# y18n

[![NPM version][npm-image]][npm-url]
[![js-standard-style][standard-image]][standard-url]
[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org)

The bare-bones internationalization library used by yargs.

Inspired by [i18n](https://www.npmjs.com/package/i18n).

## Examples

_simple string translation:_

```js
const __ = require('y18n')().__;

console.log(__('my awesome string %s', 'foo'));
```

output:

`my awesome string foo`

_using tagged template literals_

```js
const __ = require('y18n')().__;

const str = 'foo';

console.log(__`my awesome string ${str}`);
```

output:

`my awesome string foo`

_pluralization support:_

```js
const __n = require('y18n')().__n;

console.log(__n('one fish %s', '%d fishes %s', 2, 'foo'));
```

output:

`2 fishes foo`

## Deno Example

As of `v5` `y18n` supports [Deno](https://github.com/denoland/deno):

```typescript
import y18n from "https://deno.land/x/y18n/deno.ts";

const __ = y18n({
  locale: 'pirate',
  directory: './test/locales'
}).__

console.info(__`Hi, ${'Ben'} ${'Coe'}!`)
```

You will need to run with `--allow-read` to load alternative locales.

## JSON Language Files

The JSON language files should be stored in a `./locales` folder.
File names correspond to locales, e.g., `en.json`, `pirate.json`.

When strings are observed for the first time they will be
added to the JSON file corresponding to the current locale.

## Methods

### require('y18n')(config)

Create an instance of y18n with the config provided, options include:

* `directory`: the locale directory, default `./locales`.
* `updateFiles`: should newly observed strings be updated in file, default `true`.
* `locale`: what locale should be used.
* `fallbackToLanguage`: should fallback to a language-only file (e.g. `en.json`)
  be allowed if a file matching the locale does not exist (e.g. `en_US.json`),
  default `true`.

### y18n.\_\_(str, arg, arg, arg)

Print a localized string, `%s` will be replaced with `arg`s.

This function can also be used as a tag for a template literal. You can use it
like this: <code>__&#96;hello ${'world'}&#96;</code>. This will be equivalent to
`__('hello %s', 'world')`.

### y18n.\_\_n(singularString, pluralString, count, arg, arg, arg)

Print a localized string with appropriate pluralization. If `%d` is provided
in the string, the `count` will replace this placeholder.

### y18n.setLocale(str)

Set the current locale being used.

### y18n.getLocale()

What locale is currently being used?

### y18n.updateLocale(obj)

Update the current locale with the key value pairs in `obj`.

## Supported Node.js Versions

Libraries in this ecosystem make a best effort to track
[Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a
post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a).

## License

ISC

[npm-url]: https://npmjs.org/package/y18n
[npm-image]: https://img.shields.io/npm/v/y18n.svg
[standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg
[standard-url]: https://github.com/feross/standard
# balanced-match

Match balanced string pairs, like `{` and `}` or `<b>` and `</b>`. Supports regular expressions as well!

[![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match)
[![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match)

[![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match)

## Example

Get the first matching pair of braces:

```js
var balanced = require('balanced-match');

console.log(balanced('{', '}', 'pre{in{nested}}post'));
console.log(balanced('{', '}', 'pre{first}between{second}post'));
console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre  {   in{nest}   }  post'));
```

The matches are:

```bash
$ node example.js
{ start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' }
{ start: 3,
  end: 9,
  pre: 'pre',
  body: 'first',
  post: 'between{second}post' }
{ start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' }
```

## API

### var m = balanced(a, b, str)

For the first non-nested matching pair of `a` and `b` in `str`, return an
object with those keys:

* **start** the index of the first match of `a`
* **end** the index of the matching `b`
* **pre** the preamble, `a` and `b` not included
* **body** the match, `a` and `b` not included
* **post** the postscript, `a` and `b` not included

If there's no match, `undefined` will be returned.

If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`.

### var r = balanced.range(a, b, str)

For the first non-nested matching pair of `a` and `b` in `str`, return an
array with indexes: `[ <a index>, <b index> ]`.

If there's no match, `undefined` will be returned.

If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`.

## Installation

With [npm](https://npmjs.org) do:

```bash
npm install balanced-match
```

## Security contact information

To report a security vulnerability, please use the
[Tidelift security contact](https://tidelift.com/security).
Tidelift will coordinate the fix and disclosure.

## License

(MIT)

Copyright (c) 2013 Julian Gruber &lt;julian@juliangruber.com&gt;

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# jsdiff

[![Build Status](https://secure.travis-ci.org/kpdecker/jsdiff.svg)](http://travis-ci.org/kpdecker/jsdiff)
[![Sauce Test Status](https://saucelabs.com/buildstatus/jsdiff)](https://saucelabs.com/u/jsdiff)

A javascript text differencing implementation.

Based on the algorithm proposed in
["An O(ND) Difference Algorithm and its Variations" (Myers, 1986)](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927).

## Installation
```bash
npm install diff --save
```

## API

* `Diff.diffChars(oldStr, newStr[, options])` - diffs two blocks of text, comparing character by character.

    Returns a list of change objects (See below).

    Options
    * `ignoreCase`: `true` to ignore casing difference. Defaults to `false`.

* `Diff.diffWords(oldStr, newStr[, options])` - diffs two blocks of text, comparing word by word, ignoring whitespace.

    Returns a list of change objects (See below).

    Options
    * `ignoreCase`: Same as in `diffChars`.

* `Diff.diffWordsWithSpace(oldStr, newStr[, options])` - diffs two blocks of text, comparing word by word, treating whitespace as significant.

    Returns a list of change objects (See below).

* `Diff.diffLines(oldStr, newStr[, options])` - diffs two blocks of text, comparing line by line.

    Options
    * `ignoreWhitespace`: `true` to ignore leading and trailing whitespace. This is the same as `diffTrimmedLines`
    * `newlineIsToken`: `true` to treat newline characters as separate tokens.  This allows for changes to the newline structure to occur independently of the line content and to be treated as such. In general this is the more human friendly form of `diffLines` and `diffLines` is better suited for patches and other computer friendly output.

    Returns a list of change objects (See below).

* `Diff.diffTrimmedLines(oldStr, newStr[, options])` - diffs two blocks of text, comparing line by line, ignoring leading and trailing whitespace.

    Returns a list of change objects (See below).

* `Diff.diffSentences(oldStr, newStr[, options])` - diffs two blocks of text, comparing sentence by sentence.

    Returns a list of change objects (See below).

* `Diff.diffCss(oldStr, newStr[, options])` - diffs two blocks of text, comparing CSS tokens.

    Returns a list of change objects (See below).

* `Diff.diffJson(oldObj, newObj[, options])` - diffs two JSON objects, comparing the fields defined on each. The order of fields, etc does not matter in this comparison.

    Returns a list of change objects (See below).

* `Diff.diffArrays(oldArr, newArr[, options])` - diffs two arrays, comparing each item for strict equality (===).

    Options
    * `comparator`: `function(left, right)` for custom equality checks

    Returns a list of change objects (See below).

* `Diff.createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader)` - creates a unified diff patch.

    Parameters:
    * `oldFileName` : String to be output in the filename section of the patch for the removals
    * `newFileName` : String to be output in the filename section of the patch for the additions
    * `oldStr` : Original string value
    * `newStr` : New string value
    * `oldHeader` : Additional information to include in the old file header
    * `newHeader` : Additional information to include in the new file header
    * `options` : An object with options. Currently, only `context` is supported and describes how many lines of context should be included.

* `Diff.createPatch(fileName, oldStr, newStr, oldHeader, newHeader)` - creates a unified diff patch.

    Just like Diff.createTwoFilesPatch, but with oldFileName being equal to newFileName.

* `Diff.structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options)` - returns an object with an array of hunk objects.

    This method is similar to createTwoFilesPatch, but returns a data structure
    suitable for further processing. Parameters are the same as createTwoFilesPatch. The data structure returned may look like this:

    ```js
    {
      oldFileName: 'oldfile', newFileName: 'newfile',
      oldHeader: 'header1', newHeader: 'header2',
      hunks: [{
        oldStart: 1, oldLines: 3, newStart: 1, newLines: 3,
        lines: [' line2', ' line3', '-line4', '+line5', '\\ No newline at end of file'],
      }]
    }
    ```

* `Diff.applyPatch(source, patch[, options])` - applies a unified diff patch.

    Return a string containing new version of provided data. `patch` may be a string diff or the output from the `parsePatch` or `structuredPatch` methods.

    The optional `options` object may have the following keys:

    - `fuzzFactor`: Number of lines that are allowed to differ before rejecting a patch. Defaults to 0.
    - `compareLine(lineNumber, line, operation, patchContent)`: Callback used to compare to given lines to determine if they should be considered equal when patching. Defaults to strict equality but may be overridden to provide fuzzier comparison. Should return false if the lines should be rejected.

* `Diff.applyPatches(patch, options)` - applies one or more patches.

    This method will iterate over the contents of the patch and apply to data provided through callbacks. The general flow for each patch index is:

    - `options.loadFile(index, callback)` is called. The caller should then load the contents of the file and then pass that to the `callback(err, data)` callback. Passing an `err` will terminate further patch execution.
    - `options.patched(index, content, callback)` is called once the patch has been applied. `content` will be the return value from `applyPatch`. When it's ready, the caller should call `callback(err)` callback. Passing an `err` will terminate further patch execution.

    Once all patches have been applied or an error occurs, the `options.complete(err)` callback is made.

* `Diff.parsePatch(diffStr)` - Parses a patch into structured data

    Return a JSON object representation of the a patch, suitable for use with the `applyPatch` method. This parses to the same structure returned by `Diff.structuredPatch`.

* `convertChangesToXML(changes)` - converts a list of changes to a serialized XML format

All methods above which accept the optional `callback` method will run in sync mode when that parameter is omitted and in async mode when supplied. This allows for larger diffs without blocking the event loop. This may be passed either directly as the final parameter or as the `callback` field in the `options` object.

### Change Objects
Many of the methods above return change objects. These objects consist of the following fields:

* `value`: Text content
* `added`: True if the value was inserted into the new string
* `removed`: True if the value was removed from the old string

Note that some cases may omit a particular flag field. Comparison on the flag fields should always be done in a truthy or falsy manner.

## Examples

Basic example in Node

```js
require('colors');
const Diff = require('diff');

const one = 'beep boop';
const other = 'beep boob blah';

const diff = Diff.diffChars(one, other);

diff.forEach((part) => {
  // green for additions, red for deletions
  // grey for common parts
  const color = part.added ? 'green' :
    part.removed ? 'red' : 'grey';
  process.stderr.write(part.value[color]);
});

console.log();
```
Running the above program should yield

<img src="images/node_example.png" alt="Node Example">

Basic example in a web page

```html
<pre id="display"></pre>
<script src="diff.js"></script>
<script>
const one = 'beep boop',
    other = 'beep boob blah',
    color = '';
    
let span = null;

const diff = Diff.diffChars(one, other),
    display = document.getElementById('display'),
    fragment = document.createDocumentFragment();

diff.forEach((part) => {
  // green for additions, red for deletions
  // grey for common parts
  const color = part.added ? 'green' :
    part.removed ? 'red' : 'grey';
  span = document.createElement('span');
  span.style.color = color;
  span.appendChild(document
    .createTextNode(part.value));
  fragment.appendChild(span);
});

display.appendChild(fragment);
</script>
```

Open the above .html file in a browser and you should see

<img src="images/web_example.png" alt="Node Example">

**[Full online demo](http://kpdecker.github.com/jsdiff)**

## Compatibility

[![Sauce Test Status](https://saucelabs.com/browser-matrix/jsdiff.svg)](https://saucelabs.com/u/jsdiff)

jsdiff supports all ES3 environments with some known issues on IE8 and below. Under these browsers some diff algorithms such as word diff and others may fail due to lack of support for capturing groups in the `split` operation.

## License

See [LICENSE](https://github.com/kpdecker/jsdiff/blob/master/LICENSE).
# fs-minipass

Filesystem streams based on [minipass](http://npm.im/minipass).

4 classes are exported:

- ReadStream
- ReadStreamSync
- WriteStream
- WriteStreamSync

When using `ReadStreamSync`, all of the data is made available
immediately upon consuming the stream.  Nothing is buffered in memory
when the stream is constructed.  If the stream is piped to a writer,
then it will synchronously `read()` and emit data into the writer as
fast as the writer can consume it.  (That is, it will respect
backpressure.)  If you call `stream.read()` then it will read the
entire file and return the contents.

When using `WriteStreamSync`, every write is flushed to the file
synchronously.  If your writes all come in a single tick, then it'll
write it all out in a single tick.  It's as synchronous as you are.

The async versions work much like their node builtin counterparts,
with the exception of introducing significantly less Stream machinery
overhead.

## USAGE

It's just streams, you pipe them or read() them or write() to them.

```js
const fsm = require('fs-minipass')
const readStream = new fsm.ReadStream('file.txt')
const writeStream = new fsm.WriteStream('output.txt')
writeStream.write('some file header or whatever\n')
readStream.pipe(writeStream)
```

## ReadStream(path, options)

Path string is required, but somewhat irrelevant if an open file
descriptor is passed in as an option.

Options:

- `fd` Pass in a numeric file descriptor, if the file is already open.
- `readSize` The size of reads to do, defaults to 16MB
- `size` The size of the file, if known.  Prevents zero-byte read()
  call at the end.
- `autoClose` Set to `false` to prevent the file descriptor from being
  closed when the file is done being read.

## WriteStream(path, options)

Path string is required, but somewhat irrelevant if an open file
descriptor is passed in as an option.

Options:

- `fd` Pass in a numeric file descriptor, if the file is already open.
- `mode` The mode to create the file with. Defaults to `0o666`.
- `start` The position in the file to start reading.  If not
  specified, then the file will start writing at position zero, and be
  truncated by default.
- `autoClose` Set to `false` to prevent the file descriptor from being
  closed when the stream is ended.
- `flags` Flags to use when opening the file.  Irrelevant if `fd` is
  passed in, since file won't be opened in that case.  Defaults to
  `'a'` if a `pos` is specified, or `'w'` otherwise.
# lodash.sortby v4.7.0

The [lodash](https://lodash.com/) method `_.sortBy` exported as a [Node.js](https://nodejs.org/) module.

## Installation

Using npm:
```bash
$ {sudo -H} npm i -g npm
$ npm i --save lodash.sortby
```

In Node.js:
```js
var sortBy = require('lodash.sortby');
```

See the [documentation](https://lodash.com/docs#sortBy) or [package source](https://github.com/lodash/lodash/blob/4.7.0-npm-packages/lodash.sortby) for more details.
# Near Bindings Generator 
Transforms the Assembyscript AST to serialize exported functions and add `encode` and `decode` functions for generating and parsing JSON strings.

## Using via CLI

After installling, `npm install nearprotocol/near-bindgen-as`, it can be added to the cli arguments of the assemblyscript compiler you must add the following:

```bash
asc <file> --transform near-bindgen-as ...
```

This module also adds a binary `near-asc` which adds the default arguments required to build near contracts as well as the transformer.

```bash
near-asc <input file> <output file>
```

## Using a script to compile

Another way is to add a file such as `asconfig.js` such as:

```js
const compile = require("near-bindgen-as/compiler").compile;

compile("assembly/index.ts", // input file
        "out/index.wasm",    // output file
        [
        //   "-O1",            // Optional arguments
        "--debug",
        "--measure"
        ],
        // Prints out the final cli arguments passed to compiler.
        {verbose: true}
        );
```

It can then be built with `node asconfig.js`.  There is an example of this in the test directory.
﻿# whatwg-url

whatwg-url is a full implementation of the WHATWG [URL Standard](https://url.spec.whatwg.org/). It can be used standalone, but it also exposes a lot of the internal algorithms that are useful for integrating a URL parser into a project like [jsdom](https://github.com/tmpvar/jsdom).

## Specification conformance

whatwg-url is currently up to date with the URL spec up to commit [7ae1c69](https://github.com/whatwg/url/commit/7ae1c691c96f0d82fafa24c33aa1e8df9ffbf2bc).

For `file:` URLs, whose [origin is left unspecified](https://url.spec.whatwg.org/#concept-url-origin), whatwg-url chooses to use a new opaque origin (which serializes to `"null"`).

## API

### The `URL` and `URLSearchParams` classes

The main API is provided by the [`URL`](https://url.spec.whatwg.org/#url-class) and [`URLSearchParams`](https://url.spec.whatwg.org/#interface-urlsearchparams) exports, which follows the spec's behavior in all ways (including e.g. `USVString` conversion). Most consumers of this library will want to use these.

### Low-level URL Standard API

The following methods are exported for use by places like jsdom that need to implement things like [`HTMLHyperlinkElementUtils`](https://html.spec.whatwg.org/#htmlhyperlinkelementutils). They mostly operate on or return an "internal URL" or ["URL record"](https://url.spec.whatwg.org/#concept-url) type.

- [URL parser](https://url.spec.whatwg.org/#concept-url-parser): `parseURL(input, { baseURL, encodingOverride })`
- [Basic URL parser](https://url.spec.whatwg.org/#concept-basic-url-parser): `basicURLParse(input, { baseURL, encodingOverride, url, stateOverride })`
- [URL serializer](https://url.spec.whatwg.org/#concept-url-serializer): `serializeURL(urlRecord, excludeFragment)`
- [Host serializer](https://url.spec.whatwg.org/#concept-host-serializer): `serializeHost(hostFromURLRecord)`
- [Serialize an integer](https://url.spec.whatwg.org/#serialize-an-integer): `serializeInteger(number)`
- [Origin](https://url.spec.whatwg.org/#concept-url-origin) [serializer](https://html.spec.whatwg.org/multipage/origin.html#ascii-serialisation-of-an-origin): `serializeURLOrigin(urlRecord)`
- [Set the username](https://url.spec.whatwg.org/#set-the-username): `setTheUsername(urlRecord, usernameString)`
- [Set the password](https://url.spec.whatwg.org/#set-the-password): `setThePassword(urlRecord, passwordString)`
- [Cannot have a username/password/port](https://url.spec.whatwg.org/#cannot-have-a-username-password-port): `cannotHaveAUsernamePasswordPort(urlRecord)`
- [Percent decode](https://url.spec.whatwg.org/#percent-decode): `percentDecode(buffer)`

The `stateOverride` parameter is one of the following strings:

- [`"scheme start"`](https://url.spec.whatwg.org/#scheme-start-state)
- [`"scheme"`](https://url.spec.whatwg.org/#scheme-state)
- [`"no scheme"`](https://url.spec.whatwg.org/#no-scheme-state)
- [`"special relative or authority"`](https://url.spec.whatwg.org/#special-relative-or-authority-state)
- [`"path or authority"`](https://url.spec.whatwg.org/#path-or-authority-state)
- [`"relative"`](https://url.spec.whatwg.org/#relative-state)
- [`"relative slash"`](https://url.spec.whatwg.org/#relative-slash-state)
- [`"special authority slashes"`](https://url.spec.whatwg.org/#special-authority-slashes-state)
- [`"special authority ignore slashes"`](https://url.spec.whatwg.org/#special-authority-ignore-slashes-state)
- [`"authority"`](https://url.spec.whatwg.org/#authority-state)
- [`"host"`](https://url.spec.whatwg.org/#host-state)
- [`"hostname"`](https://url.spec.whatwg.org/#hostname-state)
- [`"port"`](https://url.spec.whatwg.org/#port-state)
- [`"file"`](https://url.spec.whatwg.org/#file-state)
- [`"file slash"`](https://url.spec.whatwg.org/#file-slash-state)
- [`"file host"`](https://url.spec.whatwg.org/#file-host-state)
- [`"path start"`](https://url.spec.whatwg.org/#path-start-state)
- [`"path"`](https://url.spec.whatwg.org/#path-state)
- [`"cannot-be-a-base-URL path"`](https://url.spec.whatwg.org/#cannot-be-a-base-url-path-state)
- [`"query"`](https://url.spec.whatwg.org/#query-state)
- [`"fragment"`](https://url.spec.whatwg.org/#fragment-state)

The URL record type has the following API:

- [`scheme`](https://url.spec.whatwg.org/#concept-url-scheme)
- [`username`](https://url.spec.whatwg.org/#concept-url-username)
- [`password`](https://url.spec.whatwg.org/#concept-url-password)
- [`host`](https://url.spec.whatwg.org/#concept-url-host)
- [`port`](https://url.spec.whatwg.org/#concept-url-port)
- [`path`](https://url.spec.whatwg.org/#concept-url-path) (as an array)
- [`query`](https://url.spec.whatwg.org/#concept-url-query)
- [`fragment`](https://url.spec.whatwg.org/#concept-url-fragment)
- [`cannotBeABaseURL`](https://url.spec.whatwg.org/#url-cannot-be-a-base-url-flag) (as a boolean)

These properties should be treated with care, as in general changing them will cause the URL record to be in an inconsistent state until the appropriate invocation of `basicURLParse` is used to fix it up. You can see examples of this in the URL Standard, where there are many step sequences like "4. Set context object’s url’s fragment to the empty string. 5. Basic URL parse _input_ with context object’s url as _url_ and fragment state as _state override_." In between those two steps, a URL record is in an unusable state.

The return value of "failure" in the spec is represented by `null`. That is, functions like `parseURL` and `basicURLParse` can return _either_ a URL record _or_ `null`.

## Development instructions

First, install [Node.js](https://nodejs.org/). Then, fetch the dependencies of whatwg-url, by running from this directory:

    npm install

To run tests:

    npm test

To generate a coverage report:

    npm run coverage

To build and run the live viewer:

    npm run build
    npm run build-live-viewer

Serve the contents of the `live-viewer` directory using any web server.

## Supporting whatwg-url

The jsdom project (including whatwg-url) is a community-driven project maintained by a team of [volunteers](https://github.com/orgs/jsdom/people). You could support us by:

- [Getting professional support for whatwg-url](https://tidelift.com/subscription/pkg/npm-whatwg-url?utm_source=npm-whatwg-url&utm_medium=referral&utm_campaign=readme) as part of a Tidelift subscription. Tidelift helps making open source sustainable for us while giving teams assurances for maintenance, licensing, and security.
- Contributing directly to the project.
# yargs-parser

![ci](https://github.com/yargs/yargs-parser/workflows/ci/badge.svg)
[![NPM version](https://img.shields.io/npm/v/yargs-parser.svg)](https://www.npmjs.com/package/yargs-parser)
[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org)
![nycrc config on GitHub](https://img.shields.io/nycrc/yargs/yargs-parser)

The mighty option parser used by [yargs](https://github.com/yargs/yargs).

visit the [yargs website](http://yargs.js.org/) for more examples, and thorough usage instructions.

<img width="250" src="https://raw.githubusercontent.com/yargs/yargs-parser/master/yargs-logo.png">

## Example

```sh
npm i yargs-parser --save
```

```js
const argv = require('yargs-parser')(process.argv.slice(2))
console.log(argv)
```

```console
$ node example.js --foo=33 --bar hello
{ _: [], foo: 33, bar: 'hello' }
```

_or parse a string!_

```js
const argv = require('yargs-parser')('--foo=99 --bar=33')
console.log(argv)
```

```console
{ _: [], foo: 99, bar: 33 }
```

Convert an array of mixed types before passing to `yargs-parser`:

```js
const parse = require('yargs-parser')
parse(['-f', 11, '--zoom', 55].join(' '))   // <-- array to string
parse(['-f', 11, '--zoom', 55].map(String)) // <-- array of strings
```

## Deno Example

As of `v19` `yargs-parser` supports [Deno](https://github.com/denoland/deno):

```typescript
import parser from "https://deno.land/x/yargs_parser/deno.ts";

const argv = parser('--foo=99 --bar=9987930', {
  string: ['bar']
})
console.log(argv)
```

## ESM Example

As of `v19` `yargs-parser` supports ESM (_both in Node.js and in the browser_):

**Node.js:**

```js
import parser from 'yargs-parser'

const argv = parser('--foo=99 --bar=9987930', {
  string: ['bar']
})
console.log(argv)
```

**Browsers:**

```html
<!doctype html>
<body>
  <script type="module">
    import parser from "https://unpkg.com/yargs-parser@19.0.0/browser.js";

    const argv = parser('--foo=99 --bar=9987930', {
      string: ['bar']
    })
    console.log(argv)
  </script>
</body>
```

## API

### parser(args, opts={})

Parses command line arguments returning a simple mapping of keys and values.

**expects:**

* `args`: a string or array of strings representing the options to parse.
* `opts`: provide a set of hints indicating how `args` should be parsed:
  * `opts.alias`: an object representing the set of aliases for a key: `{alias: {foo: ['f']}}`.
  * `opts.array`: indicate that keys should be parsed as an array: `{array: ['foo', 'bar']}`.<br>
    Indicate that keys should be parsed as an array and coerced to booleans / numbers:<br>
    `{array: [{ key: 'foo', boolean: true }, {key: 'bar', number: true}]}`.
  * `opts.boolean`: arguments should be parsed as booleans: `{boolean: ['x', 'y']}`.
  * `opts.coerce`: provide a custom synchronous function that returns a coerced value from the argument provided
    (or throws an error). For arrays the function is called only once for the entire array:<br>
    `{coerce: {foo: function (arg) {return modifiedArg}}}`.
  * `opts.config`: indicate a key that represents a path to a configuration file (this file will be loaded and parsed).
  * `opts.configObjects`: configuration objects to parse, their properties will be set as arguments:<br>
    `{configObjects: [{'x': 5, 'y': 33}, {'z': 44}]}`.
  * `opts.configuration`: provide configuration options to the yargs-parser (see: [configuration](#configuration)).
  * `opts.count`: indicate a key that should be used as a counter, e.g., `-vvv` = `{v: 3}`.
  * `opts.default`: provide default values for keys: `{default: {x: 33, y: 'hello world!'}}`.
  * `opts.envPrefix`: environment variables (`process.env`) with the prefix provided should be parsed.
  * `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`.
  * `opts.normalize`: `path.normalize()` will be applied to values set to this key.
  * `opts.number`: keys should be treated as numbers.
  * `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`).

**returns:**

* `obj`: an object representing the parsed value of `args`
  * `key/value`: key value pairs for each argument and their aliases.
  * `_`: an array representing the positional arguments.
  * [optional] `--`:  an array with arguments after the end-of-options flag `--`.

### require('yargs-parser').detailed(args, opts={})

Parses a command line string, returning detailed information required by the
yargs engine.

**expects:**

* `args`: a string or array of strings representing options to parse.
* `opts`: provide a set of hints indicating how `args`, inputs are identical to `require('yargs-parser')(args, opts={})`.

**returns:**

* `argv`: an object representing the parsed value of `args`
  * `key/value`: key value pairs for each argument and their aliases.
  * `_`: an array representing the positional arguments.
  * [optional] `--`:  an array with arguments after the end-of-options flag `--`.
* `error`: populated with an error object if an exception occurred during parsing.
* `aliases`: the inferred list of aliases built by combining lists in `opts.alias`.
* `newAliases`: any new aliases added via camel-case expansion:
  * `boolean`: `{ fooBar: true }`
* `defaulted`: any new argument created by `opts.default`, no aliases included.
  * `boolean`: `{ foo: true }`
* `configuration`: given by default settings and `opts.configuration`.

<a name="configuration"></a>

### Configuration

The yargs-parser applies several automated transformations on the keys provided
in `args`. These features can be turned on and off using the `configuration` field
of `opts`.

```js
var parsed = parser(['--no-dice'], {
  configuration: {
    'boolean-negation': false
  }
})
```

### short option groups

* default: `true`.
* key: `short-option-groups`.

Should a group of short-options be treated as boolean flags?

```console
$ node example.js -abc
{ _: [], a: true, b: true, c: true }
```

_if disabled:_

```console
$ node example.js -abc
{ _: [], abc: true }
```

### camel-case expansion

* default: `true`.
* key: `camel-case-expansion`.

Should hyphenated arguments be expanded into camel-case aliases?

```console
$ node example.js --foo-bar
{ _: [], 'foo-bar': true, fooBar: true }
```

_if disabled:_

```console
$ node example.js --foo-bar
{ _: [], 'foo-bar': true }
```

### dot-notation

* default: `true`
* key: `dot-notation`

Should keys that contain `.` be treated as objects?

```console
$ node example.js --foo.bar
{ _: [], foo: { bar: true } }
```

_if disabled:_

```console
$ node example.js --foo.bar
{ _: [], "foo.bar": true }
```

### parse numbers

* default: `true`
* key: `parse-numbers`

Should keys that look like numbers be treated as such?

```console
$ node example.js --foo=99.3
{ _: [], foo: 99.3 }
```

_if disabled:_

```console
$ node example.js --foo=99.3
{ _: [], foo: "99.3" }
```

### parse positional numbers

* default: `true`
* key: `parse-positional-numbers`

Should positional keys that look like numbers be treated as such.

```console
$ node example.js 99.3
{ _: [99.3] }
```

_if disabled:_

```console
$ node example.js 99.3
{ _: ['99.3'] }
```

### boolean negation

* default: `true`
* key: `boolean-negation`

Should variables prefixed with `--no` be treated as negations?

```console
$ node example.js --no-foo
{ _: [], foo: false }
```

_if disabled:_

```console
$ node example.js --no-foo
{ _: [], "no-foo": true }
```

### combine arrays

* default: `false`
* key: `combine-arrays`

Should arrays be combined when provided by both command line arguments and
a configuration file.

### duplicate arguments array

* default: `true`
* key: `duplicate-arguments-array`

Should arguments be coerced into an array when duplicated:

```console
$ node example.js -x 1 -x 2
{ _: [], x: [1, 2] }
```

_if disabled:_

```console
$ node example.js -x 1 -x 2
{ _: [], x: 2 }
```

### flatten duplicate arrays

* default: `true`
* key: `flatten-duplicate-arrays`

Should array arguments be coerced into a single array when duplicated:

```console
$ node example.js -x 1 2 -x 3 4
{ _: [], x: [1, 2, 3, 4] }
```

_if disabled:_

```console
$ node example.js -x 1 2 -x 3 4
{ _: [], x: [[1, 2], [3, 4]] }
```

### greedy arrays

* default: `true`
* key: `greedy-arrays`

Should arrays consume more than one positional argument following their flag.

```console
$ node example --arr 1 2
{ _[], arr: [1, 2] }
```

_if disabled:_

```console
$ node example --arr 1 2
{ _[2], arr: [1] }
```

**Note: in `v18.0.0` we are considering defaulting greedy arrays to `false`.**

### nargs eats options

* default: `false`
* key: `nargs-eats-options`

Should nargs consume dash options as well as positional arguments.

### negation prefix

* default: `no-`
* key: `negation-prefix`

The prefix to use for negated boolean variables.

```console
$ node example.js --no-foo
{ _: [], foo: false }
```

_if set to `quux`:_

```console
$ node example.js --quuxfoo
{ _: [], foo: false }
```

### populate --

* default: `false`.
* key: `populate--`

Should unparsed flags be stored in `--` or `_`.

_If disabled:_

```console
$ node example.js a -b -- x y
{ _: [ 'a', 'x', 'y' ], b: true }
```

_If enabled:_

```console
$ node example.js a -b -- x y
{ _: [ 'a' ], '--': [ 'x', 'y' ], b: true }
```

### set placeholder key

* default: `false`.
* key: `set-placeholder-key`.

Should a placeholder be added for keys not set via the corresponding CLI argument?

_If disabled:_

```console
$ node example.js -a 1 -c 2
{ _: [], a: 1, c: 2 }
```

_If enabled:_

```console
$ node example.js -a 1 -c 2
{ _: [], a: 1, b: undefined, c: 2 }
```

### halt at non-option

* default: `false`.
* key: `halt-at-non-option`.

Should parsing stop at the first positional argument? This is similar to how e.g. `ssh` parses its command line.

_If disabled:_

```console
$ node example.js -a run b -x y
{ _: [ 'b' ], a: 'run', x: 'y' }
```

_If enabled:_

```console
$ node example.js -a run b -x y
{ _: [ 'b', '-x', 'y' ], a: 'run' }
```

### strip aliased

* default: `false`
* key: `strip-aliased`

Should aliases be removed before returning results?

_If disabled:_

```console
$ node example.js --test-field 1
{ _: [], 'test-field': 1, testField: 1, 'test-alias': 1, testAlias: 1 }
```

_If enabled:_

```console
$ node example.js --test-field 1
{ _: [], 'test-field': 1, testField: 1 }
```

### strip dashed

* default: `false`
* key: `strip-dashed`

Should dashed keys be removed before returning results?  This option has no effect if
`camel-case-expansion` is disabled.

_If disabled:_

```console
$ node example.js --test-field 1
{ _: [], 'test-field': 1, testField: 1 }
```

_If enabled:_

```console
$ node example.js --test-field 1
{ _: [], testField: 1 }
```

### unknown options as args

* default: `false`
* key: `unknown-options-as-args`

Should unknown options be treated like regular arguments?  An unknown option is one that is not
configured in `opts`.

_If disabled_

```console
$ node example.js --unknown-option --known-option 2 --string-option --unknown-option2
{ _: [], unknownOption: true, knownOption: 2, stringOption: '', unknownOption2: true }
```

_If enabled_

```console
$ node example.js --unknown-option --known-option 2 --string-option --unknown-option2
{ _: ['--unknown-option'], knownOption: 2, stringOption: '--unknown-option2' }
```

## Supported Node.js Versions

Libraries in this ecosystem make a best effort to track
[Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a
post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a).

## Special Thanks

The yargs project evolves from optimist and minimist. It owes its
existence to a lot of James Halliday's hard work. Thanks [substack](https://github.com/substack) **beep** **boop** \o/

## License

ISC
# cliui

![ci](https://github.com/yargs/cliui/workflows/ci/badge.svg)
[![NPM version](https://img.shields.io/npm/v/cliui.svg)](https://www.npmjs.com/package/cliui)
[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org)
![nycrc config on GitHub](https://img.shields.io/nycrc/yargs/cliui)

easily create complex multi-column command-line-interfaces.

## Example

```js
const ui = require('cliui')()

ui.div('Usage: $0 [command] [options]')

ui.div({
  text: 'Options:',
  padding: [2, 0, 1, 0]
})

ui.div(
  {
    text: "-f, --file",
    width: 20,
    padding: [0, 4, 0, 4]
  },
  {
    text: "the file to load." +
      chalk.green("(if this description is long it wraps).")
    ,
    width: 20
  },
  {
    text: chalk.red("[required]"),
    align: 'right'
  }
)

console.log(ui.toString())
```

## Deno/ESM Support

As of `v7` `cliui` supports [Deno](https://github.com/denoland/deno) and
[ESM](https://nodejs.org/api/esm.html#esm_ecmascript_modules):

```typescript
import cliui from "https://deno.land/x/cliui/deno.ts";

const ui = cliui({})

ui.div('Usage: $0 [command] [options]')

ui.div({
  text: 'Options:',
  padding: [2, 0, 1, 0]
})

ui.div({
  text: "-f, --file",
  width: 20,
  padding: [0, 4, 0, 4]
})

console.log(ui.toString())
```

<img width="500" src="screenshot.png">

## Layout DSL

cliui exposes a simple layout DSL:

If you create a single `ui.div`, passing a string rather than an
object:

* `\n`: characters will be interpreted as new rows.
* `\t`: characters will be interpreted as new columns.
* `\s`: characters will be interpreted as padding.

**as an example...**

```js
var ui = require('./')({
  width: 60
})

ui.div(
  'Usage: node ./bin/foo.js\n' +
  '  <regex>\t  provide a regex\n' +
  '  <glob>\t  provide a glob\t [required]'
)

console.log(ui.toString())
```

**will output:**

```shell
Usage: node ./bin/foo.js
  <regex>  provide a regex
  <glob>   provide a glob          [required]
```

## Methods

```js
cliui = require('cliui')
```

### cliui({width: integer})

Specify the maximum width of the UI being generated.
If no width is provided, cliui will try to get the current window's width and use it, and if that doesn't work, width will be set to `80`.

### cliui({wrap: boolean})

Enable or disable the wrapping of text in a column.

### cliui.div(column, column, column)

Create a row with any number of columns, a column
can either be a string, or an object with the following
options:

* **text:** some text to place in the column.
* **width:** the width of a column.
* **align:** alignment, `right` or `center`.
* **padding:** `[top, right, bottom, left]`.
* **border:** should a border be placed around the div?

### cliui.span(column, column, column)

Similar to `div`, except the next row will be appended without
a new line being created.

### cliui.resetOutput()

Resets the UI elements of the current cliui instance, maintaining the values
set for `width` and `wrap`.
# ts-mixer
[version-badge]: https://badgen.net/npm/v/ts-mixer
[version-link]: https://npmjs.com/package/ts-mixer
[build-badge]: https://img.shields.io/github/workflow/status/tannerntannern/ts-mixer/ts-mixer%20CI
[build-link]: https://github.com/tannerntannern/ts-mixer/actions
[ts-versions]: https://badgen.net/badge/icon/3.8,3.9,4.0?icon=typescript&label&list=|
[node-versions]: https://badgen.net/badge/node/10%2C12%2C14/blue/?list=|
[![npm version][version-badge]][version-link]
[![github actions][build-badge]][build-link]
[![TS Versions][ts-versions]][build-link]
[![Node.js Versions][node-versions]][build-link]
[![Minified Size](https://badgen.net/bundlephobia/min/ts-mixer)](https://bundlephobia.com/result?p=ts-mixer)
[![Conventional Commits](https://badgen.net/badge/conventional%20commits/1.0.0/yellow)](https://conventionalcommits.org)

## Overview
`ts-mixer` brings mixins to TypeScript.  "Mixins" to `ts-mixer` are just classes, so you already know how to write them, and you can probably mix classes from your favorite library without trouble.

The mixin problem is more nuanced than it appears.  I've seen countless code snippets that work for certain situations, but fail in others.  `ts-mixer` tries to take the best from all these solutions while accounting for the situations you might not have considered.

[Quick start guide](#quick-start)

### Features
* mixes plain classes
* mixes classes that extend other classes
* mixes classes that were mixed with `ts-mixer`
* supports static properties
* supports protected/private properties (the popular function-that-returns-a-class solution does not)
* mixes abstract classes (with caveats [[1](#caveats)])
* mixes generic classes (with caveats [[2](#caveats)])
* supports class, method, and property decorators (with caveats [[3, 6](#caveats)])
* mostly supports the complexity presented by constructor functions (with caveats [[4](#caveats)])
* comes with an `instanceof`-like replacement (with caveats [[5, 6](#caveats)])
* [multiple mixing strategies](#settings) (ES6 proxies vs hard copy)

### Caveats
1. Mixing abstract classes requires a bit of a hack that may break in future versions of TypeScript.  See [mixing abstract classes](#mixing-abstract-classes) below.
2. Mixing generic classes requires a more cumbersome notation, but it's still possible.  See [mixing generic classes](#mixing-generic-classes) below.
3. Using decorators in mixed classes also requires a more cumbersome notation.  See [mixing with decorators](#mixing-with-decorators) below.
4. ES6 made it impossible to use `.apply(...)` on class constructors (or any means of calling them without `new`), which makes it impossible for `ts-mixer` to pass the proper `this` to your constructors.  This may or may not be an issue for your code, but there are options to work around it.  See [dealing with constructors](#dealing-with-constructors) below.
5. `ts-mixer` does not support `instanceof` for mixins, but it does offer a replacement.  See the [hasMixin function](#hasmixin) for more details.
6. Certain features (specifically, `@decorator` and `hasMixin`) make use of ES6 `Map`s, which means you must either use ES6+ or polyfill `Map` to use them.  If you don't need these features, you should be fine without.

## Quick Start
### Installation
```
$ npm install ts-mixer
```

or if you prefer [Yarn](https://yarnpkg.com):

```
$ yarn add ts-mixer
```

### Basic Example
```typescript
import { Mixin } from 'ts-mixer';

class Foo {
    protected makeFoo() {
        return 'foo';
    }
}

class Bar {
    protected makeBar() {
        return 'bar';
    }
}

class FooBar extends Mixin(Foo, Bar) {
    public makeFooBar() {
        return this.makeFoo() + this.makeBar();
    }
}

const fooBar = new FooBar();

console.log(fooBar.makeFooBar());  // "foobar"
```

## Special Cases
### Mixing Abstract Classes
Abstract classes, by definition, cannot be constructed, which means they cannot take on the type, `new(...args) => any`, and by extension, are incompatible with `ts-mixer`.  BUT, you can "trick" TypeScript into giving you all the benefits of an abstract class without making it technically abstract.  The trick is just some strategic `// @ts-ignore`'s:

```typescript
import { Mixin } from 'ts-mixer';

// note that Foo is not marked as an abstract class
class Foo {
    // @ts-ignore: "Abstract methods can only appear within an abstract class"
    public abstract makeFoo(): string;
}

class Bar {
    public makeBar() {
        return 'bar';
    }
}

class FooBar extends Mixin(Foo, Bar) {
    // we still get all the benefits of abstract classes here, because TypeScript
    // will still complain if this method isn't implemented
    public makeFoo() {
        return 'foo';
    }
}
```

Do note that while this does work quite well, it is a bit of a hack and I can't promise that it will continue to work in future TypeScript versions.

### Mixing Generic Classes
Frustratingly, it is _impossible_ for generic parameters to be referenced in base class expressions.  No matter what, you will eventually run into `Base class expressions cannot reference class type parameters.`

The way to get around this is to leverage [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html), and a slightly different mixing function from ts-mixer: `mix`.  It works exactly like `Mixin`, except it's a decorator, which means it doesn't affect the type information of the class being decorated.  See it in action below:

```typescript
import { mix } from 'ts-mixer';

class Foo<T> {
    public fooMethod(input: T): T {
        return input;
    }
}

class Bar<T> {
    public barMethod(input: T): T {
        return input;
    }
}

interface FooBar<T1, T2> extends Foo<T1>, Bar<T2> { }
@mix(Foo, Bar)
class FooBar<T1, T2> {
    public fooBarMethod(input1: T1, input2: T2) {
        return [this.fooMethod(input1), this.barMethod(input2)];
    }
}
```

Key takeaways from this example:
* `interface FooBar<T1, T2> extends Foo<T1>, Bar<T2> { }` makes sure `FooBar` has the typing we want, thanks to declaration merging
* `@mix(Foo, Bar)` wires things up "on the JavaScript side", since the interface declaration has nothing to do with runtime behavior.
* The reason we have to use the `mix` decorator is that the typing produced by `Mixin(Foo, Bar)` would conflict with the typing of the interface.  `mix` has no effect "on the TypeScript side," thus avoiding type conflicts.

### Mixing with Decorators
Popular libraries such as [class-validator](https://github.com/typestack/class-validator) and [TypeORM](https://github.com/typeorm/typeorm) use decorators to add functionality.  Unfortunately, `ts-mixer` has no way of knowing what these libraries do with the decorators behind the scenes.  So if you want these decorators to be "inherited" with classes you plan to mix, you first have to wrap them with a special `decorate` function exported by `ts-mixer`.  Here's an example using `class-validator`:

```typescript
import { IsBoolean, IsIn, validate } from 'class-validator';
import { Mixin, decorate } from 'ts-mixer';

class Disposable {
    @decorate(IsBoolean())  // instead of @IsBoolean()
    isDisposed: boolean = false;
}

class Statusable {
    @decorate(IsIn(['red', 'green']))  // instead of @IsIn(['red', 'green'])
    status: string = 'green';
}

class ExtendedObject extends Mixin(Disposable, Statusable) {}

const extendedObject = new ExtendedObject();
extendedObject.status = 'blue';

validate(extendedObject).then(errors => {
    console.log(errors);
});
```

### Dealing with Constructors
As mentioned in the [caveats section](#caveats), ES6 disallowed calling constructor functions without `new`.  This means that the only way for `ts-mixer` to mix instance properties is to instantiate each base class separately, then copy the instance properties into a common object.  The consequence of this is that constructors mixed by `ts-mixer` will _not_ receive the proper `this`.

**This very well may not be an issue for you!**  It only means that your constructors need to be "mostly pure" in terms of how they handle `this`.  Specifically, your constructors cannot produce [side effects](https://en.wikipedia.org/wiki/Side_effect_%28computer_science%29) involving `this`, _other than adding properties to `this`_ (the most common side effect in JavaScript constructors).

If you simply cannot eliminate `this` side effects from your constructor, there is a workaround available:  `ts-mixer` will automatically forward constructor parameters to a predesignated init function (`settings.initFunction`) if it's present on the class.  Unlike constructors, functions can be called with an arbitrary `this`, so this predesignated init function _will_ have the proper `this`.  Here's a basic example:

```typescript
import { Mixin, settings } from 'ts-mixer';

settings.initFunction = 'init';

class Person {
    public static allPeople: Set<Person> = new Set();
    
    protected init() {
        Person.allPeople.add(this);
    }
}

type PartyAffiliation = 'democrat' | 'republican';

class PoliticalParticipant {
    public static democrats: Set<PoliticalParticipant> = new Set();
    public static republicans: Set<PoliticalParticipant> = new Set();
    
    public party: PartyAffiliation;
    
    // note that these same args will also be passed to init function
    public constructor(party: PartyAffiliation) {
        this.party = party;
    }
    
    protected init(party: PartyAffiliation) {
        if (party === 'democrat')
            PoliticalParticipant.democrats.add(this);
        else
            PoliticalParticipant.republicans.add(this);
    }
}

class Voter extends Mixin(Person, PoliticalParticipant) {}

const v1 = new Voter('democrat');
const v2 = new Voter('democrat');
const v3 = new Voter('republican');
const v4 = new Voter('republican');
```

Note the above `.add(this)` statements.  These would not work as expected if they were placed in the constructor instead, since `this` is not the same between the constructor and `init`, as explained above.

## Other Features
### hasMixin
As mentioned above, `ts-mixer` does not support `instanceof` for mixins.  While it is possible to implement [custom `instanceof` behavior](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance), this library does not do so because it would require modifying the source classes, which is deliberately avoided.

You can fill this missing functionality with `hasMixin(instance, mixinClass)` instead.  See the below example:

```typescript
import { Mixin, hasMixin } from 'ts-mixer';

class Foo {}
class Bar {}
class FooBar extends Mixin(Foo, Bar) {}

const instance = new FooBar();

// doesn't work with instanceof...
console.log(instance instanceof FooBar)  // true
console.log(instance instanceof Foo)     // false
console.log(instance instanceof Bar)     // false

// but everything works nicely with hasMixin!
console.log(hasMixin(instance, FooBar))  // true
console.log(hasMixin(instance, Foo))     // true
console.log(hasMixin(instance, Bar))     // true
```

`hasMixin(instance, mixinClass)` will work anywhere that `instance instanceof mixinClass` works.  Additionally, like `instanceof`, you get the same [type narrowing benefits](https://www.typescriptlang.org/docs/handbook/advanced-types.html#instanceof-type-guards):

```typescript
if (hasMixin(instance, Foo)) {
    // inferred type of instance is "Foo"
}

if (hasMixin(instance, Bar)) {
    // inferred type of instance of "Bar"
}
```

## Settings
ts-mixer has multiple strategies for mixing classes which can be configured by modifying `settings` from ts-mixer.  For example:

```typescript
import { settings, Mixin } from 'ts-mixer';

settings.prototypeStrategy = 'proxy';

// then use `Mixin` as normal...
```

### `settings.prototypeStrategy`
* Determines how ts-mixer will mix class prototypes together
* Possible values:
    - `'copy'` (default) - Copies all methods from the classes being mixed into a new prototype object.  (This will include all methods up the prototype chains as well.)  This is the default for ES5 compatibility, but it has the downside of stale references.  For example, if you mix `Foo` and `Bar` to make `FooBar`, then redefine a method on `Foo`, `FooBar` will not have the latest methods from `Foo`.  If this is not a concern for you, `'copy'` is the best value for this setting.
    - `'proxy'` - Uses an ES6 Proxy to "soft mix" prototypes.  Unlike `'copy'`, updates to the base classes _will_ be reflected in the mixed class, which may be desirable.  The downside is that method access is not as performant, nor is it ES5 compatible.

### `settings.staticsStrategy`
* Determines how static properties are inherited
* Possible values:
    - `'copy'` (default) - Simply copies all properties (minus `prototype`) from the base classes/constructor functions onto the mixed class.  Like `settings.prototypeStrategy = 'copy'`, this strategy also suffers from stale references, but shouldn't be a concern if you don't redefine static methods after mixing.
    - `'proxy'` - Similar to `settings.prototypeStrategy`, proxy's static method access to base classes.  Has the same benefits/downsides.

### `settings.initFunction`
* If set, `ts-mixer` will automatically call the function with this name upon construction
* Possible values:
    - `null` (default) - disables the behavior
    - a string - function name to call upon construction
* Read more about why you would want this in [dealing with constructors](#dealing-with-constructors)

### `settings.decoratorInheritance`
* Determines how decorators are inherited from classes passed to `Mixin(...)`
* Possible values:
    - `'deep'` (default) - Deeply inherits decorators from all given classes and their ancestors
    - `'direct'` - Only inherits decorators defined directly on the given classes
    - `'none'` - Skips decorator inheritance

# Author
Tanner Nielsen <tannerntannern@gmail.com>
* Website - [tannernielsen.com](http://tannernielsen.com)
* Github - [tannerntannern](https://github.com/tannerntannern)
# randexp.js

randexp will generate a random string that matches a given RegExp Javascript object.

[![Build Status](https://secure.travis-ci.org/fent/randexp.js.svg)](http://travis-ci.org/fent/randexp.js)
[![Dependency Status](https://david-dm.org/fent/randexp.js.svg)](https://david-dm.org/fent/randexp.js)
[![codecov](https://codecov.io/gh/fent/randexp.js/branch/master/graph/badge.svg)](https://codecov.io/gh/fent/randexp.js)

# Usage

```js
var RandExp = require('randexp');

// supports grouping and piping
new RandExp(/hello+ (world|to you)/).gen();
// => hellooooooooooooooooooo world

// sets and ranges and references
new RandExp(/<([a-z]\w{0,20})>foo<\1>/).gen();
// => <m5xhdg>foo<m5xhdg>

// wildcard
new RandExp(/random stuff: .+/).gen();
// => random stuff: l3m;Hf9XYbI [YPaxV>U*4-_F!WXQh9>;rH3i l!8.zoh?[utt1OWFQrE ^~8zEQm]~tK

// ignore case
new RandExp(/xxx xtreme dragon warrior xxx/i).gen();
// => xxx xtReME dRAGON warRiOR xXX

// dynamic regexp shortcut
new RandExp('(sun|mon|tue|wednes|thurs|fri|satur)day', 'i');
// is the same as
new RandExp(new RegExp('(sun|mon|tue|wednes|thurs|fri|satur)day', 'i'));
```

If you're only going to use `gen()` once with a regexp and want slightly shorter syntax for it

```js
var randexp = require('randexp').randexp;

randexp(/[1-6]/); // 4
randexp('great|good( job)?|excellent'); // great
```

If you miss the old syntax

```js
require('randexp').sugar();

/yes|no|maybe|i don't know/.gen(); // maybe
```

# Motivation

Regular expressions are used in every language, every programmer is familiar with them. Regex can be used to easily express complex strings. What better way to generate a random string than with a language you can use to express the string you want?

Thanks to [String-Random](http://search.cpan.org/~steve/String-Random-0.22/lib/String/Random.pm) for giving me the idea to make this in the first place and [randexp](https://github.com/benburkert/randexp) for the sweet `.gen()` syntax.

# Default Range

The default generated character range includes printable ASCII.  In order to add or remove characters,
a `defaultRange` attribute is exposed. you can `subtract(from, to)` and `add(from, to)`
```js
var randexp = new RandExp(/random stuff: .+/);
randexp.defaultRange.subtract(32, 126);
randexp.defaultRange.add(0, 65535);
randexp.gen();
// => random stuff: 湐箻ໜ䫴␩⶛㳸長���邓蕲뤀쑡篷皇硬剈궦佔칗븛뀃匫鴔事좍ﯣ⭼ꝏ䭍詳蒂䥂뽭
```

# Custom PRNG

The default randomness is provided by `Math.random()`. If you need to use a seedable or cryptographic PRNG, you
can override `RandExp.prototype.randInt` or `randexp.randInt` (where `randexp` is an instance of `RandExp`). `randInt(from, to)` accepts an inclusive range and returns a randomly selected
number within that range.

# Infinite Repetitionals

Repetitional tokens such as `*`, `+`, and `{3,}` have an infinite max range. In this case, randexp looks at its min and adds 100 to it to get a useable max value. If you want to use another int other than 100 you can change the `max` property in `RandExp.prototype` or the RandExp instance.

```js
var randexp = new RandExp(/no{1,}/);
randexp.max = 1000000;
```

With `RandExp.sugar()`

```js
var regexp = /(hi)*/;
regexp.max = 1000000;
```

# Bad Regular Expressions

There are some regular expressions which can never match any string.

* Ones with badly placed positionals such as `/a^/` and `/$c/m`. Randexp will ignore positional tokens.

* Back references to non-existing groups like `/(a)\1\2/`. Randexp will ignore those references, returning an empty string for them. If the group exists only after the reference is used such as in `/\1 (hey)/`, it will too be ignored.

* Custom negated character sets with two sets inside that cancel each other out. Example: `/[^\w\W]/`. If you give this to randexp, it will return an empty string for this set since it can't match anything.

# Projects based on randexp.js

## JSON-Schema Faker

Use generators to populate JSON Schema samples. See: [jsf on github](https://github.com/json-schema-faker/json-schema-faker/) and [jsf demo page](http://json-schema-faker.js.org/).

# Install

### Node.js

    npm install randexp

### Browser

Download the [minified version](https://github.com/fent/randexp.js/releases) from the latest release.

# Tests

Tests are written with [mocha](https://mochajs.org)

```bash
npm test
```

# License

MIT
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`.
# ASBuild

A simple build tool for [AssemblyScript](https://assemblyscript.org) projects, similar to `cargo`, etc.

## Usage
```
asb [entry file] [options] -- [args passed to asc]
```

### Background

AssemblyScript greater than v0.14.4 provides a `asconfig.json` configuration file that can be used to describe the options for building a project. ASBuild uses this and some defaults to create an easier CLI interface.

### Defaults

#### Project structure

```
project/
  package.json   
  asconfig.json
  assembly/
    index.ts
  build/
    release/
      project.wasm
    debug/
      project.wasm
```
 - If no entry file passed and no `entry` field is in `asconfig.json`, `project/assembly/index.ts` is assumed.
 - `asconfig.json` allows for options for different compile targets, e.g. release, debug, etc.  `asc` defaults to the release target.
 - The default build directory is `./build`, and artifacts are placed at `./build/<target>/packageName.wasm`.

### Workspaces

If a `workspace` field is added to a top level `asconfig.json` file, then each path in the array is built and placed into the top level `outDir`.

For example,

`asconfig.json`:
```json
{
  "workspaces": ["a", "b"]
}
```

Running `asb` in the directory below will use the top level build directory to place all the binaries.

```
project/
  package.json
  asconfig.json
  a/
    asconfig.json
    assembly/
      index.ts
  b/
    asconfig.json
    assembly/
      index.ts
  build/
    release/
      a.wasm
      b.wasm
    debug/
      a.wasm
      b.wasm
```

To see an example in action check out the [test workspace](./test)
binaryen.js
===========

**binaryen.js** is a port of [Binaryen](https://github.com/WebAssembly/binaryen) to the Web, allowing you to generate [WebAssembly](https://webassembly.org) using a JavaScript API.

<a href="https://github.com/AssemblyScript/binaryen.js/actions?query=workflow%3ABuild"><img src="https://img.shields.io/github/workflow/status/AssemblyScript/binaryen.js/Build/master?label=build&logo=github" alt="Build status" /></a>
<a href="https://www.npmjs.com/package/binaryen"><img src="https://img.shields.io/npm/v/binaryen.svg?label=latest&color=007acc&logo=npm" alt="npm version" /></a>
<a href="https://www.npmjs.com/package/binaryen"><img src="https://img.shields.io/npm/v/binaryen/nightly.svg?label=nightly&color=007acc&logo=npm" alt="npm nightly version" /></a>

Usage
-----

```
$> npm install binaryen
```

```js
var binaryen = require("binaryen");

// Create a module with a single function
var myModule = new binaryen.Module();

myModule.addFunction("add", binaryen.createType([ binaryen.i32, binaryen.i32 ]), binaryen.i32, [ binaryen.i32 ],
  myModule.block(null, [
    myModule.local.set(2,
      myModule.i32.add(
        myModule.local.get(0, binaryen.i32),
        myModule.local.get(1, binaryen.i32)
      )
    ),
    myModule.return(
      myModule.local.get(2, binaryen.i32)
    )
  ])
);
myModule.addFunctionExport("add", "add");

// Optimize the module using default passes and levels
myModule.optimize();

// Validate the module
if (!myModule.validate())
  throw new Error("validation error");

// Generate text format and binary
var textData = myModule.emitText();
var wasmData = myModule.emitBinary();

// Example usage with the WebAssembly API
var compiled = new WebAssembly.Module(wasmData);
var instance = new WebAssembly.Instance(compiled, {});
console.log(instance.exports.add(41, 1));
```

The buildbot also publishes nightly versions once a day if there have been changes. The latest nightly can be installed through

```
$> npm install binaryen@nightly
```

or you can use one of the [previous versions](https://github.com/AssemblyScript/binaryen.js/tags) instead if necessary.

### Usage with a CDN

  * From GitHub via [jsDelivr](https://www.jsdelivr.com):<br />
    `https://cdn.jsdelivr.net/gh/AssemblyScript/binaryen.js@VERSION/index.js`
  * From npm via [jsDelivr](https://www.jsdelivr.com):<br />
    `https://cdn.jsdelivr.net/npm/binaryen@VERSION/index.js`
  * From npm via [unpkg](https://unpkg.com):<br />
    `https://unpkg.com/binaryen@VERSION/index.js`

  Replace `VERSION` with a [specific version](https://github.com/AssemblyScript/binaryen.js/releases) or omit it (not recommended in production) to use master/latest.

API
---

**Please note** that the Binaryen API is evolving fast and that definitions and documentation provided by the package tend to get out of sync despite our best efforts. It's a bot after all. If you rely on binaryen.js and spot an issue, please consider sending a PR our way by updating [index.d.ts](./index.d.ts) and [README.md](./README.md) to reflect the [current API](https://github.com/WebAssembly/binaryen/blob/master/src/js/binaryen.js-post.js).

<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
### Contents

- [Types](#types)
- [Module construction](#module-construction)
- [Module manipulation](#module-manipulation)
- [Module validation](#module-validation)
- [Module optimization](#module-optimization)
- [Module creation](#module-creation)
- [Expression construction](#expression-construction)
  - [Control flow](#control-flow)
  - [Variable accesses](#variable-accesses)
  - [Integer operations](#integer-operations)
  - [Floating point operations](#floating-point-operations)
  - [Datatype conversions](#datatype-conversions)
  - [Function calls](#function-calls)
  - [Linear memory accesses](#linear-memory-accesses)
  - [Host operations](#host-operations)
  - [Vector operations 🦄](#vector-operations-)
  - [Atomic memory accesses 🦄](#atomic-memory-accesses-)
  - [Atomic read-modify-write operations 🦄](#atomic-read-modify-write-operations-)
  - [Atomic wait and notify operations 🦄](#atomic-wait-and-notify-operations-)
  - [Sign extension operations 🦄](#sign-extension-operations-)
  - [Multi-value operations 🦄](#multi-value-operations-)
  - [Exception handling operations 🦄](#exception-handling-operations-)
  - [Reference types operations 🦄](#reference-types-operations-)
- [Expression manipulation](#expression-manipulation)
- [Relooper](#relooper)
- [Source maps](#source-maps)
- [Debugging](#debugging)

<!-- END doctoc generated TOC please keep comment here to allow auto update -->

[Future features](http://webassembly.org/docs/future-features/) 🦄 might not be supported by all runtimes.

### Types

 * **none**: `Type`<br />
   The none type, e.g., `void`.

 * **i32**: `Type`<br />
   32-bit integer type.

 * **i64**: `Type`<br />
   64-bit integer type.

 * **f32**: `Type`<br />
   32-bit float type.

 * **f64**: `Type`<br />
   64-bit float (double) type.

 * **v128**: `Type`<br />
   128-bit vector type. 🦄

 * **funcref**: `Type`<br />
   A function reference. 🦄

 * **anyref**: `Type`<br />
   Any host reference. 🦄

 * **nullref**: `Type`<br />
   A null reference. 🦄

 * **exnref**: `Type`<br />
   An exception reference. 🦄

 * **unreachable**: `Type`<br />
   Special type indicating unreachable code when obtaining information about an expression.

 * **auto**: `Type`<br />
   Special type used in **Module#block** exclusively. Lets the API figure out a block's result type automatically.

 * **createType**(types: `Type[]`): `Type`<br />
   Creates a multi-value type from an array of types.

 * **expandType**(type: `Type`): `Type[]`<br />
   Expands a multi-value type to an array of types.

### Module construction

 * new **Module**()<br />
   Constructs a new module.

 * **parseText**(text: `string`): `Module`<br />
   Creates a module from Binaryen's s-expression text format (not official stack-style text format).

 * **readBinary**(data: `Uint8Array`): `Module`<br />
   Creates a module from binary data.

### Module manipulation

* Module#**addFunction**(name: `string`, params: `Type`, results: `Type`, vars: `Type[]`, body: `ExpressionRef`): `FunctionRef`<br />
  Adds a function. `vars` indicate additional locals, in the given order.

* Module#**getFunction**(name: `string`): `FunctionRef`<br />
  Gets a function, by name,

* Module#**removeFunction**(name: `string`): `void`<br />
  Removes a function, by name.

* Module#**getNumFunctions**(): `number`<br />
  Gets the number of functions within the module.

* Module#**getFunctionByIndex**(index: `number`): `FunctionRef`<br />
  Gets the function at the specified index.

* Module#**addFunctionImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`, params: `Type`, results: `Type`): `void`<br />
  Adds a function import.

* Module#**addTableImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`): `void`<br />
  Adds a table import. There's just one table for now, using name `"0"`.

* Module#**addMemoryImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`): `void`<br />
  Adds a memory import. There's just one memory for now, using name `"0"`.

* Module#**addGlobalImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`, globalType: `Type`): `void`<br />
  Adds a global variable import. Imported globals must be immutable.

* Module#**addFunctionExport**(internalName: `string`, externalName: `string`): `ExportRef`<br />
  Adds a function export.

* Module#**addTableExport**(internalName: `string`, externalName: `string`): `ExportRef`<br />
  Adds a table export. There's just one table for now, using name `"0"`.

* Module#**addMemoryExport**(internalName: `string`, externalName: `string`): `ExportRef`<br />
  Adds a memory export. There's just one memory for now, using name `"0"`.

* Module#**addGlobalExport**(internalName: `string`, externalName: `string`): `ExportRef`<br />
  Adds a global variable export. Exported globals must be immutable.

* Module#**getNumExports**(): `number`<br />
  Gets the number of exports witin the module.

* Module#**getExportByIndex**(index: `number`): `ExportRef`<br />
  Gets the export at the specified index.

* Module#**removeExport**(externalName: `string`): `void`<br />
  Removes an export, by external name.

* Module#**addGlobal**(name: `string`, type: `Type`, mutable: `number`, value: `ExpressionRef`): `GlobalRef`<br />
  Adds a global instance variable.

* Module#**getGlobal**(name: `string`): `GlobalRef`<br />
  Gets a global, by name,

* Module#**removeGlobal**(name: `string`): `void`<br />
  Removes a global, by name.

* Module#**setFunctionTable**(initial: `number`, maximum: `number`, funcs: `string[]`, offset?: `ExpressionRef`): `void`<br />
  Sets the contents of the function table. There's just one table for now, using name `"0"`.

* Module#**getFunctionTable**(): `{ imported: boolean, segments: TableElement[] }`<br />
  Gets the contents of the function table.

  * TableElement#**offset**: `ExpressionRef`
  * TableElement#**names**: `string[]`

* Module#**setMemory**(initial: `number`, maximum: `number`, exportName: `string | null`, segments: `MemorySegment[]`, flags?: `number[]`, shared?: `boolean`): `void`<br />
  Sets the memory. There's just one memory for now, using name `"0"`. Providing `exportName` also creates a memory export.

  * MemorySegment#**offset**: `ExpressionRef`
  * MemorySegment#**data**: `Uint8Array`
  * MemorySegment#**passive**: `boolean`

* Module#**getNumMemorySegments**(): `number`<br />
  Gets the number of memory segments within the module.

* Module#**getMemorySegmentInfoByIndex**(index: `number`): `MemorySegmentInfo`<br />
  Gets information about the memory segment at the specified index.

  * MemorySegmentInfo#**offset**: `number`
  * MemorySegmentInfo#**data**: `Uint8Array`
  * MemorySegmentInfo#**passive**: `boolean`

* Module#**setStart**(start: `FunctionRef`): `void`<br />
  Sets the start function.

* Module#**getFeatures**(): `Features`<br />
  Gets the WebAssembly features enabled for this module.

  Note that the return value may be a bitmask indicating multiple features. Possible feature flags are:

  * Features.**MVP**: `Features`
  * Features.**Atomics**: `Features`
  * Features.**BulkMemory**: `Features`
  * Features.**MutableGlobals**: `Features`
  * Features.**NontrappingFPToInt**: `Features`
  * Features.**SignExt**: `Features`
  * Features.**SIMD128**: `Features`
  * Features.**ExceptionHandling**: `Features`
  * Features.**TailCall**: `Features`
  * Features.**ReferenceTypes**: `Features`
  * Features.**Multivalue**: `Features`
  * Features.**All**: `Features`

* Module#**setFeatures**(features: `Features`): `void`<br />
  Sets the WebAssembly features enabled for this module.

* Module#**addCustomSection**(name: `string`, contents: `Uint8Array`): `void`<br />
  Adds a custom section to the binary.

* Module#**autoDrop**(): `void`<br />
  Enables automatic insertion of `drop` operations where needed. Lets you not worry about dropping when creating your code.

* **getFunctionInfo**(ftype: `FunctionRef`: `FunctionInfo`<br />
  Obtains information about a function.

  * FunctionInfo#**name**: `string`
  * FunctionInfo#**module**: `string | null` (if imported)
  * FunctionInfo#**base**: `string | null` (if imported)
  * FunctionInfo#**params**: `Type`
  * FunctionInfo#**results**: `Type`
  * FunctionInfo#**vars**: `Type`
  * FunctionInfo#**body**: `ExpressionRef`

* **getGlobalInfo**(global: `GlobalRef`): `GlobalInfo`<br />
  Obtains information about a global.

  * GlobalInfo#**name**: `string`
  * GlobalInfo#**module**: `string | null` (if imported)
  * GlobalInfo#**base**: `string | null` (if imported)
  * GlobalInfo#**type**: `Type`
  * GlobalInfo#**mutable**: `boolean`
  * GlobalInfo#**init**: `ExpressionRef`

* **getExportInfo**(export_: `ExportRef`): `ExportInfo`<br />
  Obtains information about an export.

  * ExportInfo#**kind**: `ExternalKind`
  * ExportInfo#**name**: `string`
  * ExportInfo#**value**: `string`

  Possible `ExternalKind` values are:

  * **ExternalFunction**: `ExternalKind`
  * **ExternalTable**: `ExternalKind`
  * **ExternalMemory**: `ExternalKind`
  * **ExternalGlobal**: `ExternalKind`
  * **ExternalEvent**: `ExternalKind`

* **getEventInfo**(event: `EventRef`): `EventInfo`<br />
  Obtains information about an event.

  * EventInfo#**name**: `string`
  * EventInfo#**module**: `string | null` (if imported)
  * EventInfo#**base**: `string | null` (if imported)
  * EventInfo#**attribute**: `number`
  * EventInfo#**params**: `Type`
  * EventInfo#**results**: `Type`

* **getSideEffects**(expr: `ExpressionRef`, features: `FeatureFlags`): `SideEffects`<br />
  Gets the side effects of the specified expression.

  * SideEffects.**None**: `SideEffects`
  * SideEffects.**Branches**: `SideEffects`
  * SideEffects.**Calls**: `SideEffects`
  * SideEffects.**ReadsLocal**: `SideEffects`
  * SideEffects.**WritesLocal**: `SideEffects`
  * SideEffects.**ReadsGlobal**: `SideEffects`
  * SideEffects.**WritesGlobal**: `SideEffects`
  * SideEffects.**ReadsMemory**: `SideEffects`
  * SideEffects.**WritesMemory**: `SideEffects`
  * SideEffects.**ImplicitTrap**: `SideEffects`
  * SideEffects.**IsAtomic**: `SideEffects`
  * SideEffects.**Throws**: `SideEffects`
  * SideEffects.**Any**: `SideEffects`

### Module validation

* Module#**validate**(): `boolean`<br />
  Validates the module. Returns `true` if valid, otherwise prints validation errors and returns `false`.

### Module optimization

* Module#**optimize**(): `void`<br />
  Optimizes the module using the default optimization passes.

* Module#**optimizeFunction**(func: `FunctionRef | string`): `void`<br />
  Optimizes a single function using the default optimization passes.

* Module#**runPasses**(passes: `string[]`): `void`<br />
  Runs the specified passes on the module.

* Module#**runPassesOnFunction**(func: `FunctionRef | string`, passes: `string[]`): `void`<br />
  Runs the specified passes on a single function.

* **getOptimizeLevel**(): `number`<br />
  Gets the currently set optimize level. `0`, `1`, `2` correspond to `-O0`, `-O1`, `-O2` (default), etc.

* **setOptimizeLevel**(level: `number`): `void`<br />
  Sets the optimization level to use. `0`, `1`, `2` correspond to `-O0`, `-O1`, `-O2` (default), etc.

* **getShrinkLevel**(): `number`<br />
  Gets the currently set shrink level. `0`, `1`, `2` correspond to `-O0`, `-Os` (default), `-Oz`.

* **setShrinkLevel**(level: `number`): `void`<br />
  Sets the shrink level to use. `0`, `1`, `2` correspond to `-O0`, `-Os` (default), `-Oz`.

* **getDebugInfo**(): `boolean`<br />
  Gets whether generating debug information is currently enabled or not.

* **setDebugInfo**(on: `boolean`): `void`<br />
  Enables or disables debug information in emitted binaries.

* **getLowMemoryUnused**(): `boolean`<br />
  Gets whether the low 1K of memory can be considered unused when optimizing.

* **setLowMemoryUnused**(on: `boolean`): `void`<br />
  Enables or disables whether the low 1K of memory can be considered unused when optimizing.

* **getPassArgument**(key: `string`): `string | null`<br />
  Gets the value of the specified arbitrary pass argument.

* **setPassArgument**(key: `string`, value: `string | null`): `void`<br />
  Sets the value of the specified arbitrary pass argument. Removes the respective argument if `value` is `null`.

* **clearPassArguments**(): `void`<br />
  Clears all arbitrary pass arguments.

* **getAlwaysInlineMaxSize**(): `number`<br />
  Gets the function size at which we always inline.

* **setAlwaysInlineMaxSize**(size: `number`): `void`<br />
  Sets the function size at which we always inline.

* **getFlexibleInlineMaxSize**(): `number`<br />
  Gets the function size which we inline when functions are lightweight.

* **setFlexibleInlineMaxSize**(size: `number`): `void`<br />
  Sets the function size which we inline when functions are lightweight.

* **getOneCallerInlineMaxSize**(): `number`<br />
  Gets the function size which we inline when there is only one caller.

* **setOneCallerInlineMaxSize**(size: `number`): `void`<br />
  Sets the function size which we inline when there is only one caller.

### Module creation

* Module#**emitBinary**(): `Uint8Array`<br />
  Returns the module in binary format.

* Module#**emitBinary**(sourceMapUrl: `string | null`): `BinaryWithSourceMap`<br />
  Returns the module in binary format with its source map. If `sourceMapUrl` is `null`, source map generation is skipped.

  * BinaryWithSourceMap#**binary**: `Uint8Array`
  * BinaryWithSourceMap#**sourceMap**: `string | null`

* Module#**emitText**(): `string`<br />
  Returns the module in Binaryen's s-expression text format (not official stack-style text format).

* Module#**emitAsmjs**(): `string`<br />
  Returns the [asm.js](http://asmjs.org/) representation of the module.

* Module#**dispose**(): `void`<br />
  Releases the resources held by the module once it isn't needed anymore.

### Expression construction

#### [Control flow](http://webassembly.org/docs/semantics/#control-constructs-and-instructions)

* Module#**block**(label: `string | null`, children: `ExpressionRef[]`, resultType?: `Type`): `ExpressionRef`<br />
  Creates a block. `resultType` defaults to `none`.

* Module#**if**(condition: `ExpressionRef`, ifTrue: `ExpressionRef`, ifFalse?: `ExpressionRef`): `ExpressionRef`<br />
  Creates an if or if/else combination.

* Module#**loop**(label: `string | null`, body: `ExpressionRef`): `ExpressionRef`<br />
  Creates a loop.

* Module#**br**(label: `string`, condition?: `ExpressionRef`, value?: `ExpressionRef`): `ExpressionRef`<br />
  Creates a branch (br) to a label.

* Module#**switch**(labels: `string[]`, defaultLabel: `string`, condition: `ExpressionRef`, value?: `ExpressionRef`): `ExpressionRef`<br />
  Creates a switch (br_table).

* Module#**nop**(): `ExpressionRef`<br />
  Creates a no-operation (nop) instruction.

* Module#**return**(value?: `ExpressionRef`): `ExpressionRef`
  Creates a return.

* Module#**unreachable**(): `ExpressionRef`<br />
  Creates an [unreachable](http://webassembly.org/docs/semantics/#unreachable) instruction that will always trap.

* Module#**drop**(value: `ExpressionRef`): `ExpressionRef`<br />
  Creates a [drop](http://webassembly.org/docs/semantics/#type-parametric-operators) of a value.

* Module#**select**(condition: `ExpressionRef`, ifTrue: `ExpressionRef`, ifFalse: `ExpressionRef`, type?: `Type`): `ExpressionRef`<br />
  Creates a [select](http://webassembly.org/docs/semantics/#type-parametric-operators) of one of two values.

#### [Variable accesses](http://webassembly.org/docs/semantics/#local-variables)

* Module#**local.get**(index: `number`, type: `Type`): `ExpressionRef`<br />
  Creates a local.get for the local at the specified index. Note that we must specify the type here as we may not have created the local being accessed yet.

* Module#**local.set**(index: `number`, value: `ExpressionRef`): `ExpressionRef`<br />
  Creates a local.set for the local at the specified index.

* Module#**local.tee**(index: `number`, value: `ExpressionRef`, type: `Type`): `ExpressionRef`<br />
  Creates a local.tee for the local at the specified index. A tee differs from a set in that the value remains on the stack. Note that we must specify the type here as we may not have created the local being accessed yet.

* Module#**global.get**(name: `string`, type: `Type`): `ExpressionRef`<br />
  Creates a global.get for the global with the specified name. Note that we must specify the type here as we may not have created the global being accessed yet.

* Module#**global.set**(name: `string`, value: `ExpressionRef`): `ExpressionRef`<br />
  Creates a global.set for the global with the specified name.

#### [Integer operations](http://webassembly.org/docs/semantics/#32-bit-integer-operators)

* Module#i32.**const**(value: `number`): `ExpressionRef`
* Module#i32.**clz**(value: `ExpressionRef`): `ExpressionRef`
* Module#i32.**ctz**(value: `ExpressionRef`): `ExpressionRef`
* Module#i32.**popcnt**(value: `ExpressionRef`): `ExpressionRef`
* Module#i32.**eqz**(value: `ExpressionRef`): `ExpressionRef`
* Module#i32.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32.**div_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32.**div_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32.**rem_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32.**rem_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32.**and**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32.**or**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32.**xor**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32.**shl**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32.**shr_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32.**shr_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32.**rotl**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32.**rotr**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32.**le_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
>
* Module#i64.**const**(value: `number`): `ExpressionRef`
* Module#i64.**clz**(value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**ctz**(value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**popcnt**(value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**eqz**(value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i64.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i64.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i64.**div_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i64.**div_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i64.**rem_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i64.**rem_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i64.**and**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i64.**or**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i64.**xor**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i64.**shl**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i64.**shr_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i64.**shr_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i64.**rotl**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i64.**rotr**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i64.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i64.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i64.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i64.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i64.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i64.**le_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i64.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i64.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i64.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i64.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`

#### [Floating point operations](http://webassembly.org/docs/semantics/#floating-point-operators)

* Module#f32.**const**(value: `number`): `ExpressionRef`
* Module#f32.**const_bits**(value: `number`): `ExpressionRef`
* Module#f32.**neg**(value: `ExpressionRef`): `ExpressionRef`
* Module#f32.**abs**(value: `ExpressionRef`): `ExpressionRef`
* Module#f32.**ceil**(value: `ExpressionRef`): `ExpressionRef`
* Module#f32.**floor**(value: `ExpressionRef`): `ExpressionRef`
* Module#f32.**trunc**(value: `ExpressionRef`): `ExpressionRef`
* Module#f32.**nearest**(value: `ExpressionRef`): `ExpressionRef`
* Module#f32.**sqrt**(value: `ExpressionRef`): `ExpressionRef`
* Module#f32.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f32.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f32.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f32.**div**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f32.**copysign**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f32.**min**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f32.**max**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f32.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f32.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f32.**lt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f32.**le**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f32.**gt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f32.**ge**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
>
* Module#f64.**const**(value: `number`): `ExpressionRef`
* Module#f64.**const_bits**(value: `number`): `ExpressionRef`
* Module#f64.**neg**(value: `ExpressionRef`): `ExpressionRef`
* Module#f64.**abs**(value: `ExpressionRef`): `ExpressionRef`
* Module#f64.**ceil**(value: `ExpressionRef`): `ExpressionRef`
* Module#f64.**floor**(value: `ExpressionRef`): `ExpressionRef`
* Module#f64.**trunc**(value: `ExpressionRef`): `ExpressionRef`
* Module#f64.**nearest**(value: `ExpressionRef`): `ExpressionRef`
* Module#f64.**sqrt**(value: `ExpressionRef`): `ExpressionRef`
* Module#f64.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f64.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f64.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f64.**div**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f64.**copysign**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f64.**min**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f64.**max**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f64.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f64.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f64.**lt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f64.**le**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f64.**gt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f64.**ge**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`

#### [Datatype conversions](http://webassembly.org/docs/semantics/#datatype-conversions-truncations-reinterpretations-promotions-and-demotions)

* Module#i32.**trunc_s.f32**(value: `ExpressionRef`): `ExpressionRef`
* Module#i32.**trunc_s.f64**(value: `ExpressionRef`): `ExpressionRef`
* Module#i32.**trunc_u.f32**(value: `ExpressionRef`): `ExpressionRef`
* Module#i32.**trunc_u.f64**(value: `ExpressionRef`): `ExpressionRef`
* Module#i32.**reinterpret**(value: `ExpressionRef`): `ExpressionRef`
* Module#i32.**wrap**(value: `ExpressionRef`): `ExpressionRef`
>
* Module#i64.**trunc_s.f32**(value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**trunc_s.f64**(value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**trunc_u.f32**(value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**trunc_u.f64**(value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**reinterpret**(value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**extend_s**(value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**extend_u**(value: `ExpressionRef`): `ExpressionRef`
>
* Module#f32.**reinterpret**(value: `ExpressionRef`): `ExpressionRef`
* Module#f32.**convert_s.i32**(value: `ExpressionRef`): `ExpressionRef`
* Module#f32.**convert_s.i64**(value: `ExpressionRef`): `ExpressionRef`
* Module#f32.**convert_u.i32**(value: `ExpressionRef`): `ExpressionRef`
* Module#f32.**convert_u.i64**(value: `ExpressionRef`): `ExpressionRef`
* Module#f32.**demote**(value: `ExpressionRef`): `ExpressionRef`
>
* Module#f64.**reinterpret**(value: `ExpressionRef`): `ExpressionRef`
* Module#f64.**convert_s.i32**(value: `ExpressionRef`): `ExpressionRef`
* Module#f64.**convert_s.i64**(value: `ExpressionRef`): `ExpressionRef`
* Module#f64.**convert_u.i32**(value: `ExpressionRef`): `ExpressionRef`
* Module#f64.**convert_u.i64**(value: `ExpressionRef`): `ExpressionRef`
* Module#f64.**promote**(value: `ExpressionRef`): `ExpressionRef`

#### [Function calls](http://webassembly.org/docs/semantics/#calls)

* Module#**call**(name: `string`, operands: `ExpressionRef[]`, returnType: `Type`): `ExpressionRef`
Creates a call to a function. Note that we must specify the return type here as we may not have created the function being called yet.

* Module#**return_call**(name: `string`, operands: `ExpressionRef[]`, returnType: `Type`): `ExpressionRef`<br />
  Like **call**, but creates a tail-call. 🦄

* Module#**call_indirect**(target: `ExpressionRef`, operands: `ExpressionRef[]`, params: `Type`, results: `Type`): `ExpressionRef`<br />
  Similar to **call**, but calls indirectly, i.e., via a function pointer, so an expression replaces the name as the called value.

* Module#**return_call_indirect**(target: `ExpressionRef`, operands: `ExpressionRef[]`, params: `Type`, results: `Type`): `ExpressionRef`<br />
  Like **call_indirect**, but creates a tail-call. 🦄

#### [Linear memory accesses](http://webassembly.org/docs/semantics/#linear-memory-accesses)

* Module#i32.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br />
* Module#i32.**load8_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br />
* Module#i32.**load8_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br />
* Module#i32.**load16_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br />
* Module#i32.**load16_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br />
* Module#i32.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`<br />
* Module#i32.**store8**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`<br />
* Module#i32.**store16**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`<br />
>
* Module#i64.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`
* Module#i64.**load8_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`
* Module#i64.**load8_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`
* Module#i64.**load16_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`
* Module#i64.**load16_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`
* Module#i64.**load32_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`
* Module#i64.**load32_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`
* Module#i64.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**store8**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**store16**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**store32**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
>
* Module#f32.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`
* Module#f32.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
>
* Module#f64.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`
* Module#f64.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`

#### [Host operations](http://webassembly.org/docs/semantics/#resizing)

* Module#**memory.size**(): `ExpressionRef`
* Module#**memory.grow**(value: `number`): `ExpressionRef`

#### [Vector operations](https://github.com/WebAssembly/simd/blob/master/proposals/simd/SIMD.md) 🦄

* Module#v128.**const**(bytes: `Uint8Array`): `ExpressionRef`
* Module#v128.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`
* Module#v128.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#v128.**not**(value: `ExpressionRef`): `ExpressionRef`
* Module#v128.**and**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#v128.**or**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#v128.**xor**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#v128.**andnot**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#v128.**bitselect**(left: `ExpressionRef`, right: `ExpressionRef`, cond: `ExpressionRef`): `ExpressionRef`
>
* Module#i8x16.**splat**(value: `ExpressionRef`): `ExpressionRef`
* Module#i8x16.**extract_lane_s**(vec: `ExpressionRef`, index: `number`): `ExpressionRef`
* Module#i8x16.**extract_lane_u**(vec: `ExpressionRef`, index: `number`): `ExpressionRef`
* Module#i8x16.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef`
* Module#i8x16.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i8x16.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i8x16.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i8x16.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i8x16.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i8x16.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i8x16.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i8x16.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i8x16.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i8x16.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i8x16.**neg**(value: `ExpressionRef`): `ExpressionRef`
* Module#i8x16.**any_true**(value: `ExpressionRef`): `ExpressionRef`
* Module#i8x16.**all_true**(value: `ExpressionRef`): `ExpressionRef`
* Module#i8x16.**shl**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef`
* Module#i8x16.**shr_s**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef`
* Module#i8x16.**shr_u**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef`
* Module#i8x16.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i8x16.**add_saturate_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i8x16.**add_saturate_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i8x16.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i8x16.**sub_saturate_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i8x16.**sub_saturate_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i8x16.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i8x16.**min_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i8x16.**min_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i8x16.**max_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i8x16.**max_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i8x16.**avgr_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i8x16.**narrow_i16x8_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i8x16.**narrow_i16x8_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
>
* Module#i16x8.**splat**(value: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**extract_lane_s**(vec: `ExpressionRef`, index: `number`): `ExpressionRef`
* Module#i16x8.**extract_lane_u**(vec: `ExpressionRef`, index: `number`): `ExpressionRef`
* Module#i16x8.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**neg**(value: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**any_true**(value: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**all_true**(value: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**shl**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**shr_s**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**shr_u**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**add_saturate_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**add_saturate_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**sub_saturate_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**sub_saturate_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**min_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**min_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**max_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**max_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**avgr_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**narrow_i32x4_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**narrow_i32x4_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**widen_low_i8x16_s**(value: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**widen_high_i8x16_s**(value: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**widen_low_i8x16_u**(value: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**widen_high_i8x16_u**(value: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**load8x8_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`
* Module#i16x8.**load8x8_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`
>
* Module#i32x4.**splat**(value: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**extract_lane_s**(vec: `ExpressionRef`, index: `number`): `ExpressionRef`
* Module#i32x4.**extract_lane_u**(vec: `ExpressionRef`, index: `number`): `ExpressionRef`
* Module#i32x4.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**neg**(value: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**any_true**(value: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**all_true**(value: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**shl**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**shr_s**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**shr_u**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**min_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**min_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**max_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**max_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**dot_i16x8_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**trunc_sat_f32x4_s**(value: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**trunc_sat_f32x4_u**(value: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**widen_low_i16x8_s**(value: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**widen_high_i16x8_s**(value: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**widen_low_i16x8_u**(value: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**widen_high_i16x8_u**(value: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**load16x4_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`
* Module#i32x4.**load16x4_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`
>
* Module#i64x2.**splat**(value: `ExpressionRef`): `ExpressionRef`
* Module#i64x2.**extract_lane_s**(vec: `ExpressionRef`, index: `number`): `ExpressionRef`
* Module#i64x2.**extract_lane_u**(vec: `ExpressionRef`, index: `number`): `ExpressionRef`
* Module#i64x2.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef`
* Module#i64x2.**neg**(value: `ExpressionRef`): `ExpressionRef`
* Module#i64x2.**any_true**(value: `ExpressionRef`): `ExpressionRef`
* Module#i64x2.**all_true**(value: `ExpressionRef`): `ExpressionRef`
* Module#i64x2.**shl**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef`
* Module#i64x2.**shr_s**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef`
* Module#i64x2.**shr_u**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef`
* Module#i64x2.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i64x2.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#i64x2.**trunc_sat_f64x2_s**(value: `ExpressionRef`): `ExpressionRef`
* Module#i64x2.**trunc_sat_f64x2_u**(value: `ExpressionRef`): `ExpressionRef`
* Module#i64x2.**load32x2_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`
* Module#i64x2.**load32x2_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`
>
* Module#f32x4.**splat**(value: `ExpressionRef`): `ExpressionRef`
* Module#f32x4.**extract_lane**(vec: `ExpressionRef`, index: `number`): `ExpressionRef`
* Module#f32x4.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef`
* Module#f32x4.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f32x4.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f32x4.**lt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f32x4.**gt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f32x4.**le**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f32x4.**ge**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f32x4.**abs**(value: `ExpressionRef`): `ExpressionRef`
* Module#f32x4.**neg**(value: `ExpressionRef`): `ExpressionRef`
* Module#f32x4.**sqrt**(value: `ExpressionRef`): `ExpressionRef`
* Module#f32x4.**qfma**(a: `ExpressionRef`, b: `ExpressionRef`, c: `ExpressionRef`): `ExpressionRef`
* Module#f32x4.**qfms**(a: `ExpressionRef`, b: `ExpressionRef`, c: `ExpressionRef`): `ExpressionRef`
* Module#f32x4.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f32x4.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f32x4.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f32x4.**div**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f32x4.**min**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f32x4.**max**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f32x4.**convert_i32x4_s**(value: `ExpressionRef`): `ExpressionRef`
* Module#f32x4.**convert_i32x4_u**(value: `ExpressionRef`): `ExpressionRef`
>
* Module#f64x2.**splat**(value: `ExpressionRef`): `ExpressionRef`
* Module#f64x2.**extract_lane**(vec: `ExpressionRef`, index: `number`): `ExpressionRef`
* Module#f64x2.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef`
* Module#f64x2.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f64x2.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f64x2.**lt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f64x2.**gt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f64x2.**le**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f64x2.**ge**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f64x2.**abs**(value: `ExpressionRef`): `ExpressionRef`
* Module#f64x2.**neg**(value: `ExpressionRef`): `ExpressionRef`
* Module#f64x2.**sqrt**(value: `ExpressionRef`): `ExpressionRef`
* Module#f64x2.**qfma**(a: `ExpressionRef`, b: `ExpressionRef`, c: `ExpressionRef`): `ExpressionRef`
* Module#f64x2.**qfms**(a: `ExpressionRef`, b: `ExpressionRef`, c: `ExpressionRef`): `ExpressionRef`
* Module#f64x2.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f64x2.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f64x2.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f64x2.**div**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f64x2.**min**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f64x2.**max**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#f64x2.**convert_i64x2_s**(value: `ExpressionRef`): `ExpressionRef`
* Module#f64x2.**convert_i64x2_u**(value: `ExpressionRef`): `ExpressionRef`
>
* Module#v8x16.**shuffle**(left: `ExpressionRef`, right: `ExpressionRef`, mask: `Uint8Array`): `ExpressionRef`
* Module#v8x16.**swizzle**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef`
* Module#v8x16.**load_splat**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`
>
* Module#v16x8.**load_splat**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`
>
* Module#v32x4.**load_splat**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`
>
* Module#v64x2.**load_splat**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`

#### [Atomic memory accesses](https://github.com/WebAssembly/threads/blob/master/proposals/threads/Overview.md#atomic-memory-accesses) 🦄

* Module#i32.**atomic.load**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef`
* Module#i32.**atomic.load8_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef`
* Module#i32.**atomic.load16_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef`
* Module#i32.**atomic.store**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i32.**atomic.store8**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i32.**atomic.store16**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
>
* Module#i64.**atomic.load**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.load8_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.load16_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.load32_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.store**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.store8**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.store16**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.store32**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`

#### [Atomic read-modify-write operations](https://github.com/WebAssembly/threads/blob/master/proposals/threads/Overview.md#read-modify-write) 🦄

* Module#i32.**atomic.rmw.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i32.**atomic.rmw.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i32.**atomic.rmw.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i32.**atomic.rmw.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i32.**atomic.rmw.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i32.**atomic.rmw.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i32.**atomic.rmw.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef`
* Module#i32.**atomic.rmw8_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i32.**atomic.rmw8_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i32.**atomic.rmw8_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i32.**atomic.rmw8_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i32.**atomic.rmw8_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i32.**atomic.rmw8_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i32.**atomic.rmw8_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef`
* Module#i32.**atomic.rmw16_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i32.**atomic.rmw16_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i32.**atomic.rmw16_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i32.**atomic.rmw16_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i32.**atomic.rmw16_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i32.**atomic.rmw16_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i32.**atomic.rmw16_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef`
>
* Module#i64.**atomic.rmw.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.rmw.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.rmw.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.rmw.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.rmw.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.rmw.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.rmw.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.rmw8_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.rmw8_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.rmw8_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.rmw8_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.rmw8_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.rmw8_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.rmw8_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.rmw16_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.rmw16_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.rmw16_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.rmw16_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.rmw16_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.rmw16_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.rmw16_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.rmw32_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.rmw32_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.rmw32_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.rmw32_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.rmw32_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.rmw32_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.rmw32_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef`

#### [Atomic wait and notify operations](https://github.com/WebAssembly/threads/blob/master/proposals/threads/Overview.md#wait-and-notify-operators) 🦄

* Module#i32.**atomic.wait**(ptr: `ExpressionRef`, expected: `ExpressionRef`, timeout: `ExpressionRef`): `ExpressionRef`
* Module#i64.**atomic.wait**(ptr: `ExpressionRef`, expected: `ExpressionRef`, timeout: `ExpressionRef`): `ExpressionRef`
* Module#**atomic.notify**(ptr: `ExpressionRef`, notifyCount: `ExpressionRef`): `ExpressionRef`
* Module#**atomic.fence**(): `ExpressionRef`

#### [Sign extension operations](https://github.com/WebAssembly/sign-extension-ops/blob/master/proposals/sign-extension-ops/Overview.md) 🦄

* Module#i32.**extend8_s**(value: `ExpressionRef`): `ExpressionRef`
* Module#i32.**extend16_s**(value: `ExpressionRef`): `ExpressionRef`
>
* Module#i64.**extend8_s**(value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**extend16_s**(value: `ExpressionRef`): `ExpressionRef`
* Module#i64.**extend32_s**(value: `ExpressionRef`): `ExpressionRef`

#### [Multi-value operations](https://github.com/WebAssembly/multi-value/blob/master/proposals/multi-value/Overview.md) 🦄

Note that these are pseudo instructions enabling Binaryen to reason about multiple values on the stack.

* Module#**push**(value: `ExpressionRef`): `ExpressionRef`
* Module#i32.**pop**(): `ExpressionRef`
* Module#i64.**pop**(): `ExpressionRef`
* Module#f32.**pop**(): `ExpressionRef`
* Module#f64.**pop**(): `ExpressionRef`
* Module#v128.**pop**(): `ExpressionRef`
* Module#funcref.**pop**(): `ExpressionRef`
* Module#anyref.**pop**(): `ExpressionRef`
* Module#nullref.**pop**(): `ExpressionRef`
* Module#exnref.**pop**(): `ExpressionRef`
* Module#tuple.**make**(elements: `ExpressionRef[]`): `ExpressionRef`
* Module#tuple.**extract**(tuple: `ExpressionRef`, index: `number`): `ExpressionRef`

#### [Exception handling operations](https://github.com/WebAssembly/exception-handling/blob/master/proposals/Exceptions.md) 🦄

* Module#**try**(body: `ExpressionRef`, catchBody: `ExpressionRef`): `ExpressionRef`
* Module#**throw**(event: `string`, operands: `ExpressionRef[]`): `ExpressionRef`
* Module#**rethrow**(exnref: `ExpressionRef`): `ExpressionRef`
* Module#**br_on_exn**(label: `string`, event: `string`, exnref: `ExpressionRef`): `ExpressionRef`
>
* Module#**addEvent**(name: `string`, attribute: `number`, params: `Type`, results: `Type`): `Event`
* Module#**getEvent**(name: `string`): `Event`
* Module#**removeEvent**(name: `stirng`): `void`
* Module#**addEventImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`, attribute: `number`, params: `Type`, results: `Type`): `void`
* Module#**addEventExport**(internalName: `string`, externalName: `string`): `ExportRef`

#### [Reference types operations](https://github.com/WebAssembly/reference-types/blob/master/proposals/reference-types/Overview.md) 🦄

* Module#ref.**null**(): `ExpressionRef`
* Module#ref.**is_null**(value: `ExpressionRef`): `ExpressionRef`
* Module#ref.**func**(name: `string`): `ExpressionRef`

### Expression manipulation

* **getExpressionId**(expr: `ExpressionRef`): `ExpressionId`<br />
  Gets the id (kind) of the specified expression. Possible values are:

  * **InvalidId**: `ExpressionId`
  * **BlockId**: `ExpressionId`
  * **IfId**: `ExpressionId`
  * **LoopId**: `ExpressionId`
  * **BreakId**: `ExpressionId`
  * **SwitchId**: `ExpressionId`
  * **CallId**: `ExpressionId`
  * **CallIndirectId**: `ExpressionId`
  * **LocalGetId**: `ExpressionId`
  * **LocalSetId**: `ExpressionId`
  * **GlobalGetId**: `ExpressionId`
  * **GlobalSetId**: `ExpressionId`
  * **LoadId**: `ExpressionId`
  * **StoreId**: `ExpressionId`
  * **ConstId**: `ExpressionId`
  * **UnaryId**: `ExpressionId`
  * **BinaryId**: `ExpressionId`
  * **SelectId**: `ExpressionId`
  * **DropId**: `ExpressionId`
  * **ReturnId**: `ExpressionId`
  * **HostId**: `ExpressionId`
  * **NopId**: `ExpressionId`
  * **UnreachableId**: `ExpressionId`
  * **AtomicCmpxchgId**: `ExpressionId`
  * **AtomicRMWId**: `ExpressionId`
  * **AtomicWaitId**: `ExpressionId`
  * **AtomicNotifyId**: `ExpressionId`
  * **AtomicFenceId**: `ExpressionId`
  * **SIMDExtractId**: `ExpressionId`
  * **SIMDReplaceId**: `ExpressionId`
  * **SIMDShuffleId**: `ExpressionId`
  * **SIMDTernaryId**: `ExpressionId`
  * **SIMDShiftId**: `ExpressionId`
  * **SIMDLoadId**: `ExpressionId`
  * **MemoryInitId**: `ExpressionId`
  * **DataDropId**: `ExpressionId`
  * **MemoryCopyId**: `ExpressionId`
  * **MemoryFillId**: `ExpressionId`
  * **RefNullId**: `ExpressionId`
  * **RefIsNullId**: `ExpressionId`
  * **RefFuncId**: `ExpressionId`
  * **TryId**: `ExpressionId`
  * **ThrowId**: `ExpressionId`
  * **RethrowId**: `ExpressionId`
  * **BrOnExnId**: `ExpressionId`
  * **PushId**: `ExpressionId`
  * **PopId**: `ExpressionId`

* **getExpressionType**(expr: `ExpressionRef`): `Type`<br />
  Gets the type of the specified expression.

* **getExpressionInfo**(expr: `ExpressionRef`): `ExpressionInfo`<br />
  Obtains information about an expression, always including:

  * Info#**id**: `ExpressionId`
  * Info#**type**: `Type`

  Additional properties depend on the expression's `id` and are usually equivalent to the respective parameters when creating such an expression:

  * BlockInfo#**name**: `string`
  * BlockInfo#**children**: `ExpressionRef[]`
  >
  * IfInfo#**condition**: `ExpressionRef`
  * IfInfo#**ifTrue**: `ExpressionRef`
  * IfInfo#**ifFalse**: `ExpressionRef | null`
  >
  * LoopInfo#**name**: `string`
  * LoopInfo#**body**: `ExpressionRef`
  >
  * BreakInfo#**name**: `string`
  * BreakInfo#**condition**: `ExpressionRef | null`
  * BreakInfo#**value**: `ExpressionRef | null`
  >
  * SwitchInfo#**names**: `string[]`
  * SwitchInfo#**defaultName**: `string | null`
  * SwitchInfo#**condition**: `ExpressionRef`
  * SwitchInfo#**value**: `ExpressionRef | null`
  >
  * CallInfo#**target**: `string`
  * CallInfo#**operands**: `ExpressionRef[]`
  >
  * CallImportInfo#**target**: `string`
  * CallImportInfo#**operands**: `ExpressionRef[]`
  >
  * CallIndirectInfo#**target**: `ExpressionRef`
  * CallIndirectInfo#**operands**: `ExpressionRef[]`
  >
  * LocalGetInfo#**index**: `number`
  >
  * LocalSetInfo#**isTee**: `boolean`
  * LocalSetInfo#**index**: `number`
  * LocalSetInfo#**value**: `ExpressionRef`
  >
  * GlobalGetInfo#**name**: `string`
  >
  * GlobalSetInfo#**name**: `string`
  * GlobalSetInfo#**value**: `ExpressionRef`
  >
  * LoadInfo#**isAtomic**: `boolean`
  * LoadInfo#**isSigned**: `boolean`
  * LoadInfo#**offset**: `number`
  * LoadInfo#**bytes**: `number`
  * LoadInfo#**align**: `number`
  * LoadInfo#**ptr**: `ExpressionRef`
  >
  * StoreInfo#**isAtomic**: `boolean`
  * StoreInfo#**offset**: `number`
  * StoreInfo#**bytes**: `number`
  * StoreInfo#**align**: `number`
  * StoreInfo#**ptr**: `ExpressionRef`
  * StoreInfo#**value**: `ExpressionRef`
  >
  * ConstInfo#**value**: `number | { low: number, high: number }`
  >
  * UnaryInfo#**op**: `number`
  * UnaryInfo#**value**: `ExpressionRef`
  >
  * BinaryInfo#**op**: `number`
  * BinaryInfo#**left**: `ExpressionRef`
  * BinaryInfo#**right**: `ExpressionRef`
  >
  * SelectInfo#**ifTrue**: `ExpressionRef`
  * SelectInfo#**ifFalse**: `ExpressionRef`
  * SelectInfo#**condition**: `ExpressionRef`
  >
  * DropInfo#**value**: `ExpressionRef`
  >
  * ReturnInfo#**value**: `ExpressionRef | null`
  >
  * NopInfo
  >
  * UnreachableInfo
  >
  * HostInfo#**op**: `number`
  * HostInfo#**nameOperand**: `string | null`
  * HostInfo#**operands**: `ExpressionRef[]`
  >
  * AtomicRMWInfo#**op**: `number`
  * AtomicRMWInfo#**bytes**: `number`
  * AtomicRMWInfo#**offset**: `number`
  * AtomicRMWInfo#**ptr**: `ExpressionRef`
  * AtomicRMWInfo#**value**: `ExpressionRef`
  >
  * AtomicCmpxchgInfo#**bytes**: `number`
  * AtomicCmpxchgInfo#**offset**: `number`
  * AtomicCmpxchgInfo#**ptr**: `ExpressionRef`
  * AtomicCmpxchgInfo#**expected**: `ExpressionRef`
  * AtomicCmpxchgInfo#**replacement**: `ExpressionRef`
  >
  * AtomicWaitInfo#**ptr**: `ExpressionRef`
  * AtomicWaitInfo#**expected**: `ExpressionRef`
  * AtomicWaitInfo#**timeout**: `ExpressionRef`
  * AtomicWaitInfo#**expectedType**: `Type`
  >
  * AtomicNotifyInfo#**ptr**: `ExpressionRef`
  * AtomicNotifyInfo#**notifyCount**: `ExpressionRef`
  >
  * AtomicFenceInfo
  >
  * SIMDExtractInfo#**op**: `Op`
  * SIMDExtractInfo#**vec**: `ExpressionRef`
  * SIMDExtractInfo#**index**: `ExpressionRef`
  >
  * SIMDReplaceInfo#**op**: `Op`
  * SIMDReplaceInfo#**vec**: `ExpressionRef`
  * SIMDReplaceInfo#**index**: `ExpressionRef`
  * SIMDReplaceInfo#**value**: `ExpressionRef`
  >
  * SIMDShuffleInfo#**left**: `ExpressionRef`
  * SIMDShuffleInfo#**right**: `ExpressionRef`
  * SIMDShuffleInfo#**mask**: `Uint8Array`
  >
  * SIMDTernaryInfo#**op**: `Op`
  * SIMDTernaryInfo#**a**: `ExpressionRef`
  * SIMDTernaryInfo#**b**: `ExpressionRef`
  * SIMDTernaryInfo#**c**: `ExpressionRef`
  >
  * SIMDShiftInfo#**op**: `Op`
  * SIMDShiftInfo#**vec**: `ExpressionRef`
  * SIMDShiftInfo#**shift**: `ExpressionRef`
  >
  * SIMDLoadInfo#**op**: `Op`
  * SIMDLoadInfo#**offset**: `number`
  * SIMDLoadInfo#**align**: `number`
  * SIMDLoadInfo#**ptr**: `ExpressionRef`
  >
  * MemoryInitInfo#**segment**: `number`
  * MemoryInitInfo#**dest**: `ExpressionRef`
  * MemoryInitInfo#**offset**: `ExpressionRef`
  * MemoryInitInfo#**size**: `ExpressionRef`
  >
  * MemoryDropInfo#**segment**: `number`
  >
  * MemoryCopyInfo#**dest**: `ExpressionRef`
  * MemoryCopyInfo#**source**: `ExpressionRef`
  * MemoryCopyInfo#**size**: `ExpressionRef`
  >
  * MemoryFillInfo#**dest**: `ExpressionRef`
  * MemoryFillInfo#**value**: `ExpressionRef`
  * MemoryFillInfo#**size**: `ExpressionRef`
  >
  * TryInfo#**body**: `ExpressionRef`
  * TryInfo#**catchBody**: `ExpressionRef`
  >
  * RefNullInfo
  >
  * RefIsNullInfo#**value**: `ExpressionRef`
  >
  * RefFuncInfo#**func**: `string`
  >
  * ThrowInfo#**event**: `string`
  * ThrowInfo#**operands**: `ExpressionRef[]`
  >
  * RethrowInfo#**exnref**: `ExpressionRef`
  >
  * BrOnExnInfo#**name**: `string`
  * BrOnExnInfo#**event**: `string`
  * BrOnExnInfo#**exnref**: `ExpressionRef`
  >
  * PopInfo
  >
  * PushInfo#**value**: `ExpressionRef`

* **emitText**(expression: `ExpressionRef`): `string`<br />
  Emits the expression in Binaryen's s-expression text format (not official stack-style text format).

* **copyExpression**(expression: `ExpressionRef`): `ExpressionRef`<br />
  Creates a deep copy of an expression.

### Relooper

* new **Relooper**()<br />
  Constructs a relooper instance. This lets you provide an arbitrary CFG, and the relooper will structure it for WebAssembly.

* Relooper#**addBlock**(code: `ExpressionRef`): `RelooperBlockRef`<br />
  Adds a new block to the CFG, containing the provided code as its body.

* Relooper#**addBranch**(from: `RelooperBlockRef`, to: `RelooperBlockRef`, condition: `ExpressionRef`, code: `ExpressionRef`): `void`<br />
  Adds a branch from a block to another block, with a condition (or nothing, if this is the default branch to take from the origin - each block must have one such branch), and optional code to execute on the branch (useful for phis).

* Relooper#**addBlockWithSwitch**(code: `ExpressionRef`, condition: `ExpressionRef`): `RelooperBlockRef`<br />
  Adds a new block, which ends with a switch/br_table, with provided code and condition (that determines where we go in the switch).

* Relooper#**addBranchForSwitch**(from: `RelooperBlockRef`, to: `RelooperBlockRef`, indexes: `number[]`, code: `ExpressionRef`): `void`<br />
  Adds a branch from a block ending in a switch, to another block, using an array of indexes that determine where to go, and optional code to execute on the branch.

* Relooper#**renderAndDispose**(entry: `RelooperBlockRef`, labelHelper: `number`, module: `Module`): `ExpressionRef`<br />
  Renders and cleans up the Relooper instance. Call this after you have created all the blocks and branches, giving it the entry block (where control flow begins), a label helper variable (an index of a local we can use, necessary for irreducible control flow), and the module. This returns an expression - normal WebAssembly code - that you can use normally anywhere.

### Source maps

* Module#**addDebugInfoFileName**(filename: `string`): `number`<br />
  Adds a debug info file name to the module and returns its index.

* Module#**getDebugInfoFileName**(index: `number`): `string | null` <br />
  Gets the name of the debug info file at the specified index.

* Module#**setDebugLocation**(func: `FunctionRef`, expr: `ExpressionRef`, fileIndex: `number`, lineNumber: `number`, columnNumber: `number`): `void`<br />
  Sets the debug location of the specified `ExpressionRef` within the specified `FunctionRef`.

### Debugging

* Module#**interpret**(): `void`<br />
  Runs the module in the interpreter, calling the start function.
# near-sdk-core

This package contain a convenient interface for interacting with NEAR's host runtime.  To see the functions that are provided by the host node see [`env.ts`](./assembly/env/env.ts).
[![NPM registry](https://img.shields.io/npm/v/as-bignum.svg?style=for-the-badge)](https://www.npmjs.com/package/as-bignum)[![Build Status](https://img.shields.io/travis/com/MaxGraey/as-bignum/master?style=for-the-badge)](https://travis-ci.com/MaxGraey/as-bignum)[![NPM license](https://img.shields.io/badge/license-Apache%202.0-ba68c8.svg?style=for-the-badge)](LICENSE.md)

## Work in progress

---

### WebAssembly fixed length big numbers written on [AssemblyScript](https://github.com/AssemblyScript/assemblyscript)

Provide wide numeric types such as `u128`, `u256`, `i128`, `i256` and fixed points and also its arithmetic operations.

Namespace `safe` contain equivalents with overflow/underflow traps.

All kind of types pretty useful for economical and cryptographic usages and provide deterministic behavior.

### Install

> yarn add as-bignum

or

> npm i as-bignum

### Usage via AssemblyScript

```ts
import { u128 } from "as-bignum";

declare function logF64(value: f64): void;
declare function logU128(hi: u64, lo: u64): void;

var a = u128.One;
var b = u128.from(-32); // same as u128.from<i32>(-32)
var c = new u128(0x1, -0xF);
var d = u128.from(0x0123456789ABCDEF); // same as u128.from<i64>(0x0123456789ABCDEF)
var e = u128.from('0x0123456789ABCDEF01234567');
var f = u128.fromString('11100010101100101', 2); // same as u128.from('0b11100010101100101')
var r = d / c + (b << 5) + e;

logF64(r.as<f64>());
logU128(r.hi, r.lo);
```

### Usage via JavaScript/Typescript

```ts
TODO
```

### List of types

- [x] [`u128`](https://github.com/MaxGraey/as-bignum/blob/master/assembly/integer/u128.ts) unsigned type (tested)
- [ ] [`u256`](https://github.com/MaxGraey/as-bignum/blob/master/assembly/integer/u256.ts) unsigned type (very basic)
- [ ] `i128` signed type
- [ ] `i256` signed type
---
- [x] [`safe.u128`](https://github.com/MaxGraey/as-bignum/blob/master/assembly/integer/safe/u128.ts) unsigned type (tested)
- [ ] `safe.u256` unsigned type
- [ ] `safe.i128` signed type
- [ ] `safe.i256` signed type
---
- [ ] [`fp128<Q>`](https://github.com/MaxGraey/as-bignum/blob/master/assembly/fixed/fp128.ts) generic fixed point signed type٭ (very basic for now)
- [ ] `fp256<Q>` generic fixed point signed type٭
---
- [ ] `safe.fp128<Q>` generic fixed point signed type٭
- [ ] `safe.fp256<Q>` generic fixed point signed type٭

٭ _typename_ `Q` _is a type representing count of fractional bits_
A JSON with color names and its values. Based on http://dev.w3.org/csswg/css-color/#named-colors.

[![NPM](https://nodei.co/npm/color-name.png?mini=true)](https://nodei.co/npm/color-name/)

```js
var colors = require('color-name');
colors.red //[255,0,0]
```

<a href="LICENSE"><img src="https://upload.wikimedia.org/wikipedia/commons/0/0c/MIT_logo.svg" width="120"/></a>
# Visitor utilities for AssemblyScript Compiler transformers

## Example

### List Fields

The transformer:

```ts
import {
  ClassDeclaration,
  FieldDeclaration,
  MethodDeclaration,
} from "../../as";
import { ClassDecorator, registerDecorator } from "../decorator";
import { toString } from "../utils";

class ListMembers extends ClassDecorator {
  visitFieldDeclaration(node: FieldDeclaration): void {
    if (!node.name) console.log(toString(node) + "\n");
    const name = toString(node.name);
    const _type = toString(node.type!);
    this.stdout.write(name + ": " + _type + "\n");
  }

  visitMethodDeclaration(node: MethodDeclaration): void {
    const name = toString(node.name);
    if (name == "constructor") {
      return;
    }
    const sig = toString(node.signature);
    this.stdout.write(name + ": " + sig + "\n");
  }

  visitClassDeclaration(node: ClassDeclaration): void {
    this.visit(node.members);
  }

  get name(): string {
    return "list";
  }
}

export = registerDecorator(new ListMembers());
```

assembly/foo.ts:
```ts
@list
class Foo {
  a: u8;
  b: bool;
  i: i32;
}
```

And then compile with `--transform` flag:

```
asc assembly/foo.ts --transform ./dist/examples/list --noEmit
```

Which prints the following to the console:

```
a: u8
b: bool
i: i32
```
# y18n

[![Build Status][travis-image]][travis-url]
[![Coverage Status][coveralls-image]][coveralls-url]
[![NPM version][npm-image]][npm-url]
[![js-standard-style][standard-image]][standard-url]
[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org)

The bare-bones internationalization library used by yargs.

Inspired by [i18n](https://www.npmjs.com/package/i18n).

## Examples

_simple string translation:_

```js
var __ = require('y18n').__

console.log(__('my awesome string %s', 'foo'))
```

output:

`my awesome string foo`

_using tagged template literals_

```js
var __ = require('y18n').__
var str = 'foo'

console.log(__`my awesome string ${str}`)
```

output:

`my awesome string foo`

_pluralization support:_

```js
var __n = require('y18n').__n

console.log(__n('one fish %s', '%d fishes %s', 2, 'foo'))
```

output:

`2 fishes foo`

## JSON Language Files

The JSON language files should be stored in a `./locales` folder.
File names correspond to locales, e.g., `en.json`, `pirate.json`.

When strings are observed for the first time they will be
added to the JSON file corresponding to the current locale.

## Methods

### require('y18n')(config)

Create an instance of y18n with the config provided, options include:

* `directory`: the locale directory, default `./locales`.
* `updateFiles`: should newly observed strings be updated in file, default `true`.
* `locale`: what locale should be used.
* `fallbackToLanguage`: should fallback to a language-only file (e.g. `en.json`)
  be allowed if a file matching the locale does not exist (e.g. `en_US.json`),
  default `true`.

### y18n.\_\_(str, arg, arg, arg)

Print a localized string, `%s` will be replaced with `arg`s.

This function can also be used as a tag for a template literal. You can use it
like this: <code>__&#96;hello ${'world'}&#96;</code>. This will be equivalent to
`__('hello %s', 'world')`.

### y18n.\_\_n(singularString, pluralString, count, arg, arg, arg)

Print a localized string with appropriate pluralization. If `%d` is provided
in the string, the `count` will replace this placeholder.

### y18n.setLocale(str)

Set the current locale being used.

### y18n.getLocale()

What locale is currently being used?

### y18n.updateLocale(obj)

Update the current locale with the key value pairs in `obj`.

## License

ISC

[travis-url]: https://travis-ci.org/yargs/y18n
[travis-image]: https://img.shields.io/travis/yargs/y18n.svg
[coveralls-url]: https://coveralls.io/github/yargs/y18n
[coveralls-image]: https://img.shields.io/coveralls/yargs/y18n.svg
[npm-url]: https://npmjs.org/package/y18n
[npm-image]: https://img.shields.io/npm/v/y18n.svg
[standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg
[standard-url]: https://github.com/feross/standard
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 });
});
...
```
[![build status](https://secure.travis-ci.org/dankogai/js-base64.png)](http://travis-ci.org/dankogai/js-base64)

# base64.js

Yet another [Base64] transcoder.

[Base64]: http://en.wikipedia.org/wiki/Base64

## HEADS UP

In version 3.0 `js-base64` switch to ES2015 module so it is no longer compatible with legacy browsers like IE (see below).  And since version 3.3 it is written in TypeScript.  Now `base64.mjs` is compiled from `base64.ts` then `base64.js` is generated from `base64.mjs`.

## Install

```shell
$ npm install --save js-base64
```

## Usage

### In Browser

Locally…

```html
<script src="base64.js"></script>
```

… or Directly from CDN.  In which case you don't even need to install.

```html
<script src="https://cdn.jsdelivr.net/npm/js-base64@3.6.0/base64.min.js"></script>
```

This good old way loads `Base64` in the global context (`window`).  Though `Base64.noConflict()` is made available, you should consider using ES6 Module to avoid tainting `window`.

### As an ES6 Module

locally…

```javascript
import { Base64 } from 'js-base64';
```

```javascript
// or if you prefer no Base64 namespace
import { encode, decode } from 'js-base64';
```

or even remotely.

```html
<script type="module">
// note jsdelivr.net does not automatically minify .mjs
import { Base64 } from 'https://cdn.jsdelivr.net/npm/js-base64@3.6.0/base64.mjs';
</script>
```

```html
<script type="module">
// or if you prefer no Base64 namespace
import { encode, decode } from 'https://cdn.jsdelivr.net/npm/js-base64@3.6.0/base64.mjs';
</script>
```

### node.js (commonjs)

```javascript
const {Base64} = require('js-base64');
```

Unlike the case above, the global context is no longer modified.

You can also use [esm] to `import` instead of `require`.

[esm]: https://github.com/standard-things/esm

```javascript
require=require('esm')(module);
import {Base64} from 'js-base64';
```

## SYNOPSIS

```javascript
let latin = 'dankogai';
let utf8  = '小飼弾'
let u8s   =  new Uint8Array([100,97,110,107,111,103,97,105]);
Base64.encode(latin);             // ZGFua29nYWk=
Base64.btoa(latin);               // ZGFua29nYWk=
Base64.btoa(utf8);                // raises exception
Base64.fromUint8Array(u8s);       // ZGFua29nYWk=
Base64.fromUint8Array(u8s, true); // ZGFua29nYW which is URI safe
Base64.encode(utf8);              // 5bCP6aO85by+
Base64.encode(utf8, true)         // 5bCP6aO85by-
Base64.encodeURI(utf8);           // 5bCP6aO85by-
```

```javascript
Base64.decode(      'ZGFua29nYWk=');// dankogai
Base64.atob(        'ZGFua29nYWk=');// dankogai
Base64.atob(        '5bCP6aO85by+');// 'å°é£¼å¼¾' which is nonsense
Base64.toUint8Array('ZGFua29nYWk=');// u8s above
Base64.decode(      '5bCP6aO85by+');// 小飼弾
// note .decodeURI() is unnecessary since it accepts both flavors
Base64.decode(      '5bCP6aO85by-');// 小飼弾
```

```javascript
Base64.isValid(0);      // false: 0 is not string
Base64.isValid('');     // true: a valid Base64-encoded empty byte
Base64.isValid('ZA=='); // true: a valid Base64-encoded 'd'
Base64.isValid('Z A='); // true: whitespaces are okay
Base64.isValid('ZA');   // true: padding ='s can be omitted
Base64.isValid('++');   // true: can be non URL-safe
Base64.isValid('--');   // true: or URL-safe
Base64.isValid('+-');   // false: can't mix both
```

### Built-in Extensions

By default `Base64` leaves built-in prototypes untouched.  But you can extend them as below.

```javascript
// you have to explicitly extend String.prototype
Base64.extendString();
// once extended, you can do the following
'dankogai'.toBase64();        // ZGFua29nYWk=
'小飼弾'.toBase64();           // 5bCP6aO85by+
'小飼弾'.toBase64(true);       // 5bCP6aO85by-
'小飼弾'.toBase64URI();        // 5bCP6aO85by- ab alias of .toBase64(true)
'小飼弾'.toBase64URL();        // 5bCP6aO85by- an alias of .toBase64URI()
'ZGFua29nYWk='.fromBase64();  // dankogai
'5bCP6aO85by+'.fromBase64();  // 小飼弾
'5bCP6aO85by-'.fromBase64();  // 小飼弾
'5bCP6aO85by-'.toUint8Array();// u8s above
```

```javascript
// you have to explicitly extend String.prototype
Base64.extendString();
// once extended, you can do the following
u8s.toBase64();     // 'ZGFua29nYWk='
u8s.toBase64URI();  // 'ZGFua29nYWk'
u8s.toBase64URL();  // 'ZGFua29nYWk' an alias of .toBase64URI()
```

```javascript
// extend all at once
Base64.extendBuiltins()
```

## `.decode()` vs `.atob` (and `.encode()` vs `btoa()`)

Suppose you have:

```
var pngBase64 = 
  "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
```

Which is a Base64-encoded 1x1 transparent PNG, **DO NOT USE** `Base64.decode(pngBase64)`.  Use `Base64.atob(pngBase64)` instead.  `Base64.decode()` decodes to UTF-8 string while `Base64.atob()` decodes to bytes, which is compatible to browser built-in `atob()` (Which is absent in node.js).  The same rule applies to the opposite direction.

Or even better, `Base64.toUint8Array(pngBase64)`.

### If you really, really need an ES5 version

You can transpiles to an ES5 that runs on IE11.  Do the following in your shell.

```shell
$ make base64.es5.js
```
# 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))
```
<p align="center">
  <img width="250" src="https://raw.githubusercontent.com/yargs/yargs/master/yargs-logo.png">
</p>
<h1 align="center"> Yargs </h1>
<p align="center">
  <b >Yargs be a node.js library fer hearties tryin' ter parse optstrings</b>
</p>

<br>

![ci](https://github.com/yargs/yargs/workflows/ci/badge.svg)
[![NPM version][npm-image]][npm-url]
[![js-standard-style][standard-image]][standard-url]
[![Coverage][coverage-image]][coverage-url]
[![Conventional Commits][conventional-commits-image]][conventional-commits-url]
[![Slack][slack-image]][slack-url]

## Description
Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface.

It gives you:

* commands and (grouped) options (`my-program.js serve --port=5000`).
* a dynamically generated help menu based on your arguments:

```
mocha [spec..]

Run tests with Mocha

Commands
  mocha inspect [spec..]  Run tests with Mocha                         [default]
  mocha init <path>       create a client-side Mocha setup at <path>

Rules & Behavior
  --allow-uncaught           Allow uncaught errors to propagate        [boolean]
  --async-only, -A           Require all tests to use a callback (async) or
                             return a Promise                          [boolean]
```

* bash-completion shortcuts for commands and options.
* and [tons more](/docs/api.md).

## Installation

Stable version:
```bash
npm i yargs
```

Bleeding edge version with the most recent features:
```bash
npm i yargs@next
```

## Usage

### Simple Example

```javascript
#!/usr/bin/env node
const yargs = require('yargs/yargs')
const { hideBin } = require('yargs/helpers')
const argv = yargs(hideBin(process.argv)).argv

if (argv.ships > 3 && argv.distance < 53.5) {
  console.log('Plunder more riffiwobbles!')
} else {
  console.log('Retreat from the xupptumblers!')
}
```

```bash
$ ./plunder.js --ships=4 --distance=22
Plunder more riffiwobbles!

$ ./plunder.js --ships 12 --distance 98.7
Retreat from the xupptumblers!
```

### Complex Example

```javascript
#!/usr/bin/env node
const yargs = require('yargs/yargs')
const { hideBin } = require('yargs/helpers')

yargs(hideBin(process.argv))
  .command('serve [port]', 'start the server', (yargs) => {
    yargs
      .positional('port', {
        describe: 'port to bind on',
        default: 5000
      })
  }, (argv) => {
    if (argv.verbose) console.info(`start server on :${argv.port}`)
    serve(argv.port)
  })
  .option('verbose', {
    alias: 'v',
    type: 'boolean',
    description: 'Run with verbose logging'
  })
  .argv
```

Run the example above with `--help` to see the help for the application.

## Supported Platforms

### TypeScript

yargs has type definitions at [@types/yargs][type-definitions].

```
npm i @types/yargs --save-dev
```

See usage examples in [docs](/docs/typescript.md).

### Deno

As of `v16`, `yargs` supports [Deno](https://github.com/denoland/deno):

```typescript
import yargs from 'https://deno.land/x/yargs/deno.ts'
import { Arguments } from 'https://deno.land/x/yargs/deno-types.ts'

yargs(Deno.args)
  .command('download <files...>', 'download a list of files', (yargs: any) => {
    return yargs.positional('files', {
      describe: 'a list of files to do something with'
    })
  }, (argv: Arguments) => {
    console.info(argv)
  })
  .strictCommands()
  .demandCommand(1)
  .argv
```

### ESM

As of `v16`,`yargs` supports ESM imports:

```js
import yargs from 'yargs'
import { hideBin } from 'yargs/helpers'

yargs(hideBin(process.argv))
  .command('curl <url>', 'fetch the contents of the URL', () => {}, (argv) => {
    console.info(argv)
  })
  .demandCommand(1)
  .argv
```

### Usage in Browser

See examples of using yargs in the browser in [docs](/docs/browser.md).

## Community

Having problems? want to contribute? join our [community slack](http://devtoolscommunity.herokuapp.com).

## Documentation

### Table of Contents

* [Yargs' API](/docs/api.md)
* [Examples](/docs/examples.md)
* [Parsing Tricks](/docs/tricks.md)
  * [Stop the Parser](/docs/tricks.md#stop)
  * [Negating Boolean Arguments](/docs/tricks.md#negate)
  * [Numbers](/docs/tricks.md#numbers)
  * [Arrays](/docs/tricks.md#arrays)
  * [Objects](/docs/tricks.md#objects)
  * [Quotes](/docs/tricks.md#quotes)
* [Advanced Topics](/docs/advanced.md)
  * [Composing Your App Using Commands](/docs/advanced.md#commands)
  * [Building Configurable CLI Apps](/docs/advanced.md#configuration)
  * [Customizing Yargs' Parser](/docs/advanced.md#customizing)
  * [Bundling yargs](/docs/bundling.md)
* [Contributing](/contributing.md)

## Supported Node.js Versions

Libraries in this ecosystem make a best effort to track
[Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a
post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a).

[npm-url]: https://www.npmjs.com/package/yargs
[npm-image]: https://img.shields.io/npm/v/yargs.svg
[standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg
[standard-url]: http://standardjs.com/
[conventional-commits-image]: https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg
[conventional-commits-url]: https://conventionalcommits.org/
[slack-image]: http://devtoolscommunity.herokuapp.com/badge.svg
[slack-url]: http://devtoolscommunity.herokuapp.com
[type-definitions]: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yargs
[coverage-image]: https://img.shields.io/nycrc/yargs/yargs
[coverage-url]: https://github.com/yargs/yargs/blob/master/.nycrc
# hasurl [![NPM Version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url]

> Determine whether Node.js' native [WHATWG `URL`](https://nodejs.org/api/url.html#url_the_whatwg_url_api) implementation is available.

## Installation

[Node.js](http://nodejs.org/) `>= 4` is required. To install, type this at the command line:
```shell
npm install hasurl
```

## Usage

```js
const hasURL = require('hasurl');

if (hasURL()) {
	// supported
} else {
	// fallback
}
```

[npm-image]: https://img.shields.io/npm/v/hasurl.svg
[npm-url]: https://npmjs.org/package/hasurl
[travis-image]: https://img.shields.io/travis/stevenvachon/hasurl.svg
[travis-url]: https://travis-ci.org/stevenvachon/hasurl
# Glob

Match files using the patterns the shell uses, like stars and stuff.

[![Build Status](https://travis-ci.org/isaacs/node-glob.svg?branch=master)](https://travis-ci.org/isaacs/node-glob/) [![Build Status](https://ci.appveyor.com/api/projects/status/kd7f3yftf7unxlsx?svg=true)](https://ci.appveyor.com/project/isaacs/node-glob) [![Coverage Status](https://coveralls.io/repos/isaacs/node-glob/badge.svg?branch=master&service=github)](https://coveralls.io/github/isaacs/node-glob?branch=master)

This is a glob implementation in JavaScript.  It uses the `minimatch`
library to do its matching.

![](logo/glob.png)

## Usage

Install with npm

```
npm i glob
```

```javascript
var glob = require("glob")

// options is optional
glob("**/*.js", options, function (er, files) {
  // files is an array of filenames.
  // If the `nonull` option is set, and nothing
  // was found, then files is ["**/*.js"]
  // er is an error object or null.
})
```

## Glob Primer

"Globs" are the patterns you type when you do stuff like `ls *.js` on
the command line, or put `build/*` in a `.gitignore` file.

Before parsing the path part patterns, braced sections are expanded
into a set.  Braced sections start with `{` and end with `}`, with any
number of comma-delimited sections within.  Braced sections may contain
slash characters, so `a{/b/c,bcd}` would expand into `a/b/c` and `abcd`.

The following characters have special magic meaning when used in a
path portion:

* `*` Matches 0 or more characters in a single path portion
* `?` Matches 1 character
* `[...]` Matches a range of characters, similar to a RegExp range.
  If the first character of the range is `!` or `^` then it matches
  any character not in the range.
* `!(pattern|pattern|pattern)` Matches anything that does not match
  any of the patterns provided.
* `?(pattern|pattern|pattern)` Matches zero or one occurrence of the
  patterns provided.
* `+(pattern|pattern|pattern)` Matches one or more occurrences of the
  patterns provided.
* `*(a|b|c)` Matches zero or more occurrences of the patterns provided
* `@(pattern|pat*|pat?erN)` Matches exactly one of the patterns
  provided
* `**` If a "globstar" is alone in a path portion, then it matches
  zero or more directories and subdirectories searching for matches.
  It does not crawl symlinked directories.

### Dots

If a file or directory path portion has a `.` as the first character,
then it will not match any glob pattern unless that pattern's
corresponding path part also has a `.` as its first character.

For example, the pattern `a/.*/c` would match the file at `a/.b/c`.
However the pattern `a/*/c` would not, because `*` does not start with
a dot character.

You can make glob treat dots as normal characters by setting
`dot:true` in the options.

### Basename Matching

If you set `matchBase:true` in the options, and the pattern has no
slashes in it, then it will seek for any file anywhere in the tree
with a matching basename.  For example, `*.js` would match
`test/simple/basic.js`.

### Empty Sets

If no matching files are found, then an empty array is returned.  This
differs from the shell, where the pattern itself is returned.  For
example:

    $ echo a*s*d*f
    a*s*d*f

To get the bash-style behavior, set the `nonull:true` in the options.

### See Also:

* `man sh`
* `man bash` (Search for "Pattern Matching")
* `man 3 fnmatch`
* `man 5 gitignore`
* [minimatch documentation](https://github.com/isaacs/minimatch)

## glob.hasMagic(pattern, [options])

Returns `true` if there are any special characters in the pattern, and
`false` otherwise.

Note that the options affect the results.  If `noext:true` is set in
the options object, then `+(a|b)` will not be considered a magic
pattern.  If the pattern has a brace expansion, like `a/{b/c,x/y}`
then that is considered magical, unless `nobrace:true` is set in the
options.

## glob(pattern, [options], cb)

* `pattern` `{String}` Pattern to be matched
* `options` `{Object}`
* `cb` `{Function}`
  * `err` `{Error | null}`
  * `matches` `{Array<String>}` filenames found matching the pattern

Perform an asynchronous glob search.

## glob.sync(pattern, [options])

* `pattern` `{String}` Pattern to be matched
* `options` `{Object}`
* return: `{Array<String>}` filenames found matching the pattern

Perform a synchronous glob search.

## Class: glob.Glob

Create a Glob object by instantiating the `glob.Glob` class.

```javascript
var Glob = require("glob").Glob
var mg = new Glob(pattern, options, cb)
```

It's an EventEmitter, and starts walking the filesystem to find matches
immediately.

### new glob.Glob(pattern, [options], [cb])

* `pattern` `{String}` pattern to search for
* `options` `{Object}`
* `cb` `{Function}` Called when an error occurs, or matches are found
  * `err` `{Error | null}`
  * `matches` `{Array<String>}` filenames found matching the pattern

Note that if the `sync` flag is set in the options, then matches will
be immediately available on the `g.found` member.

### Properties

* `minimatch` The minimatch object that the glob uses.
* `options` The options object passed in.
* `aborted` Boolean which is set to true when calling `abort()`.  There
  is no way at this time to continue a glob search after aborting, but
  you can re-use the statCache to avoid having to duplicate syscalls.
* `cache` Convenience object.  Each field has the following possible
  values:
  * `false` - Path does not exist
  * `true` - Path exists
  * `'FILE'` - Path exists, and is not a directory
  * `'DIR'` - Path exists, and is a directory
  * `[file, entries, ...]` - Path exists, is a directory, and the
    array value is the results of `fs.readdir`
* `statCache` Cache of `fs.stat` results, to prevent statting the same
  path multiple times.
* `symlinks` A record of which paths are symbolic links, which is
  relevant in resolving `**` patterns.
* `realpathCache` An optional object which is passed to `fs.realpath`
  to minimize unnecessary syscalls.  It is stored on the instantiated
  Glob object, and may be re-used.

### Events

* `end` When the matching is finished, this is emitted with all the
  matches found.  If the `nonull` option is set, and no match was found,
  then the `matches` list contains the original pattern.  The matches
  are sorted, unless the `nosort` flag is set.
* `match` Every time a match is found, this is emitted with the specific
  thing that matched. It is not deduplicated or resolved to a realpath.
* `error` Emitted when an unexpected error is encountered, or whenever
  any fs error occurs if `options.strict` is set.
* `abort` When `abort()` is called, this event is raised.

### Methods

* `pause` Temporarily stop the search
* `resume` Resume the search
* `abort` Stop the search forever

### Options

All the options that can be passed to Minimatch can also be passed to
Glob to change pattern matching behavior.  Also, some have been added,
or have glob-specific ramifications.

All options are false by default, unless otherwise noted.

All options are added to the Glob object, as well.

If you are running many `glob` operations, you can pass a Glob object
as the `options` argument to a subsequent operation to shortcut some
`stat` and `readdir` calls.  At the very least, you may pass in shared
`symlinks`, `statCache`, `realpathCache`, and `cache` options, so that
parallel glob operations will be sped up by sharing information about
the filesystem.

* `cwd` The current working directory in which to search.  Defaults
  to `process.cwd()`.
* `root` The place where patterns starting with `/` will be mounted
  onto.  Defaults to `path.resolve(options.cwd, "/")` (`/` on Unix
  systems, and `C:\` or some such on Windows.)
* `dot` Include `.dot` files in normal matches and `globstar` matches.
  Note that an explicit dot in a portion of the pattern will always
  match dot files.
* `nomount` By default, a pattern starting with a forward-slash will be
  "mounted" onto the root setting, so that a valid filesystem path is
  returned.  Set this flag to disable that behavior.
* `mark` Add a `/` character to directory matches.  Note that this
  requires additional stat calls.
* `nosort` Don't sort the results.
* `stat` Set to true to stat *all* results.  This reduces performance
  somewhat, and is completely unnecessary, unless `readdir` is presumed
  to be an untrustworthy indicator of file existence.
* `silent` When an unusual error is encountered when attempting to
  read a directory, a warning will be printed to stderr.  Set the
  `silent` option to true to suppress these warnings.
* `strict` When an unusual error is encountered when attempting to
  read a directory, the process will just continue on in search of
  other matches.  Set the `strict` option to raise an error in these
  cases.
* `cache` See `cache` property above.  Pass in a previously generated
  cache object to save some fs calls.
* `statCache` A cache of results of filesystem information, to prevent
  unnecessary stat calls.  While it should not normally be necessary
  to set this, you may pass the statCache from one glob() call to the
  options object of another, if you know that the filesystem will not
  change between calls.  (See "Race Conditions" below.)
* `symlinks` A cache of known symbolic links.  You may pass in a
  previously generated `symlinks` object to save `lstat` calls when
  resolving `**` matches.
* `sync` DEPRECATED: use `glob.sync(pattern, opts)` instead.
* `nounique` In some cases, brace-expanded patterns can result in the
  same file showing up multiple times in the result set.  By default,
  this implementation prevents duplicates in the result set.  Set this
  flag to disable that behavior.
* `nonull` Set to never return an empty set, instead returning a set
  containing the pattern itself.  This is the default in glob(3).
* `debug` Set to enable debug logging in minimatch and glob.
* `nobrace` Do not expand `{a,b}` and `{1..3}` brace sets.
* `noglobstar` Do not match `**` against multiple filenames.  (Ie,
  treat it as a normal `*` instead.)
* `noext` Do not match `+(a|b)` "extglob" patterns.
* `nocase` Perform a case-insensitive match.  Note: on
  case-insensitive filesystems, non-magic patterns will match by
  default, since `stat` and `readdir` will not raise errors.
* `matchBase` Perform a basename-only match if the pattern does not
  contain any slash characters.  That is, `*.js` would be treated as
  equivalent to `**/*.js`, matching all js files in all directories.
* `nodir` Do not match directories, only files.  (Note: to match
  *only* directories, simply put a `/` at the end of the pattern.)
* `ignore` Add a pattern or an array of glob patterns to exclude matches.
  Note: `ignore` patterns are *always* in `dot:true` mode, regardless
  of any other settings.
* `follow` Follow symlinked directories when expanding `**` patterns.
  Note that this can result in a lot of duplicate references in the
  presence of cyclic links.
* `realpath` Set to true to call `fs.realpath` on all of the results.
  In the case of a symlink that cannot be resolved, the full absolute
  path to the matched entry is returned (though it will usually be a
  broken symlink)
* `absolute` Set to true to always receive absolute paths for matched
  files.  Unlike `realpath`, this also affects the values returned in
  the `match` event.

## Comparisons to other fnmatch/glob implementations

While strict compliance with the existing standards is a worthwhile
goal, some discrepancies exist between node-glob and other
implementations, and are intentional.

The double-star character `**` is supported by default, unless the
`noglobstar` flag is set.  This is supported in the manner of bsdglob
and bash 4.3, where `**` only has special significance if it is the only
thing in a path part.  That is, `a/**/b` will match `a/x/y/b`, but
`a/**b` will not.

Note that symlinked directories are not crawled as part of a `**`,
though their contents may match against subsequent portions of the
pattern.  This prevents infinite loops and duplicates and the like.

If an escaped pattern has no matches, and the `nonull` flag is set,
then glob returns the pattern as-provided, rather than
interpreting the character escapes.  For example,
`glob.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than
`"*a?"`.  This is akin to setting the `nullglob` option in bash, except
that it does not resolve escaped pattern characters.

If brace expansion is not disabled, then it is performed before any
other interpretation of the glob pattern.  Thus, a pattern like
`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded
**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are
checked for validity.  Since those two are valid, matching proceeds.

### Comments and Negation

Previously, this module let you mark a pattern as a "comment" if it
started with a `#` character, or a "negated" pattern if it started
with a `!` character.

These options were deprecated in version 5, and removed in version 6.

To specify things that should not match, use the `ignore` option.

## Windows

**Please only use forward-slashes in glob expressions.**

Though windows uses either `/` or `\` as its path separator, only `/`
characters are used by this glob implementation.  You must use
forward-slashes **only** in glob expressions.  Back-slashes will always
be interpreted as escape characters, not path separators.

Results from absolute patterns such as `/foo/*` are mounted onto the
root setting using `path.join`.  On windows, this will by default result
in `/foo/*` matching `C:\foo\bar.txt`.

## Race Conditions

Glob searching, by its very nature, is susceptible to race conditions,
since it relies on directory walking and such.

As a result, it is possible that a file that exists when glob looks for
it may have been deleted or modified by the time it returns the result.

As part of its internal implementation, this program caches all stat
and readdir calls that it makes, in order to cut down on system
overhead.  However, this also makes it even more susceptible to races,
especially if the cache or statCache objects are reused between glob
calls.

Users are thus advised not to use a glob result as a guarantee of
filesystem state in the face of rapid changes.  For the vast majority
of operations, this is never a problem.

## Glob Logo
Glob's logo was created by [Tanya Brassie](http://tanyabrassie.com/). Logo files can be found [here](https://github.com/isaacs/node-glob/tree/master/logo).

The logo is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0/).

## Contributing

Any change to behavior (including bugfixes) must come with a test.

Patches that fail tests or reduce performance will be rejected.

```
# to run tests
npm test

# to re-generate test fixtures
npm run test-regen

# to benchmark against bash/zsh
npm run bench

# to profile javascript
npm run prof
```

![](oh-my-glob.gif)
# 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.
# set-blocking

[![Build Status](https://travis-ci.org/yargs/set-blocking.svg)](https://travis-ci.org/yargs/set-blocking)
[![NPM version](https://img.shields.io/npm/v/set-blocking.svg)](https://www.npmjs.com/package/set-blocking)
[![Coverage Status](https://coveralls.io/repos/yargs/set-blocking/badge.svg?branch=)](https://coveralls.io/r/yargs/set-blocking?branch=master)
[![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version)

set blocking `stdio` and `stderr` ensuring that terminal output does not truncate.

```js
const setBlocking = require('set-blocking')
setBlocking(true)
console.log(someLargeStringToOutput)
```

## Historical Context/Word of Warning

This was created as a shim to address the bug discussed in [node #6456](https://github.com/nodejs/node/issues/6456). This bug crops up on
newer versions of Node.js (`0.12+`), truncating terminal output.

You should be mindful of the side-effects caused by using `set-blocking`:

* if your module sets blocking to `true`, it will effect other modules
  consuming your library. In [yargs](https://github.com/yargs/yargs/blob/master/yargs.js#L653) we only call
  `setBlocking(true)` once we already know we are about to call `process.exit(code)`.
* this patch will not apply to subprocesses spawned with `isTTY = true`, this is
  the [default `spawn()` behavior](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options).

## License

ISC
# 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()
```
Shims used when bundling asc for browser usage.
