From bd8171c13e085f95318e8785560d2e6ec8e473db Mon Sep 17 00:00:00 2001 From: spalger Date: Sun, 3 Apr 2022 00:23:30 -0600 Subject: [PATCH] [plugins] use module ids to import across plugins --- .buildkite/scripts/build_kibana_plugins.sh | 16 +- .gitignore | 2 + .../monorepo-packages.asciidoc | 1 - package.json | 9 +- packages/BUILD.bazel | 7 +- .../elastic-eslint-config-kibana/.eslintrc.js | 3 +- packages/kbn-babel-code-parser/BUILD.bazel | 61 - packages/kbn-babel-code-parser/README.md | 19 - packages/kbn-babel-code-parser/package.json | 15 - .../kbn-babel-code-parser/src/can_require.js | 23 - .../kbn-babel-code-parser/src/code_parser.js | 94 - .../kbn-babel-code-parser/src/strategies.js | 90 - .../src/strategies.test.js | 97 - .../kbn-babel-code-parser/src/visitors.js | 131 - .../src/visitors.test.js | 57 - .../BUILD.bazel | 64 + .../babel_plugin_synthetic_packages.js | 183 + .../package.json | 10 + packages/kbn-babel-preset/BUILD.bazel | 1 + packages/kbn-babel-preset/common_preset.js | 6 +- packages/kbn-babel-preset/node_preset.js | 2 +- packages/kbn-babel-preset/webpack_preset.js | 4 +- packages/kbn-bazel-packages/BUILD.bazel | 2 + .../kbn-bazel-packages/src/bazel_package.ts | 38 +- .../src/discover_packages.ts | 29 +- .../src/parse_package_json.ts | 63 + packages/kbn-config/BUILD.bazel | 2 + packages/kbn-config/src/env.ts | 2 +- packages/kbn-config/src/index.ts | 1 - .../src/plugins/plugin_search_paths.ts | 26 - packages/kbn-docs-utils/BUILD.bazel | 4 +- .../src/api_docs/find_plugins.ts | 3 +- packages/kbn-eslint-plugin-eslint/BUILD.bazel | 1 + .../rules/no_restricted_paths.js | 6 +- .../kbn-eslint-plugin-imports/BUILD.bazel | 2 + .../src/get_import_resolver.ts | 30 + .../src/helpers/report.ts | 31 + .../src/helpers/running_in_editor.ts | 13 + .../helpers/visit_all_import_statements.ts | 152 +- .../kbn-eslint-plugin-imports/src/index.ts | 10 +- .../resolve_kibana_import.test.ts | 149 - .../src/resolve_kibana_import.ts | 161 - ..._imports.ts => no_unresolvable_imports.ts} | 13 +- .../src/rules/uniform_imports.ts | 120 + .../kbn-find-used-node-modules/BUILD.bazel | 122 + packages/kbn-find-used-node-modules/README.md | 7 + .../jest.config.js | 4 +- .../kbn-find-used-node-modules/package.json | 10 + .../src/find_used_node_modules.test.ts | 186 + .../src/find_used_node_modules.ts | 138 + .../src/fs.ts} | 14 +- .../src/get_import_requests.test.ts | 64 + .../src/get_import_requests.ts | 30 + .../src/import_visitor.ts | 82 + .../src/index.ts} | 4 +- .../kbn-find-used-node-modules/tsconfig.json | 17 + packages/kbn-import-resolver/BUILD.bazel | 124 + packages/kbn-import-resolver/README.md | 3 + .../jest.integration.config.js | 13 + packages/kbn-import-resolver/package.json | 10 + .../node_modules/@pkg/box/index.js | 0 .../__fixtures__/node_modules/foo/index.js | 0 .../src/__fixtures__/packages/box/index.js} | 2 - .../src/__fixtures__/src/bar/bar.js} | 2 - .../src/__fixtures__/src/bar/index.js | 7 + .../src/__fixtures__/src/index.js | 7 + .../src/helpers/fs.ts | 17 +- .../src/helpers/import_req.ts | 100 + .../src/helpers/memoize.ts | 0 .../src/import_resolver.ts | 281 + packages/kbn-import-resolver/src/index.ts | 11 + .../integration_tests/import_resolver.test.ts | 192 + .../src/resolve_result.ts | 24 +- packages/kbn-import-resolver/tsconfig.json | 17 + packages/kbn-optimizer/BUILD.bazel | 2 + packages/kbn-optimizer/src/cli.ts | 8 + .../src/optimizer/optimizer_cache_key.test.ts | 9 + .../src/optimizer/optimizer_cache_key.ts | 4 + .../src/optimizer/optimizer_config.ts | 7 +- .../src/plugin_search_paths.ts | 23 +- packages/kbn-pm/dist/index.js | 48382 ++++++++-------- packages/kbn-pm/src/commands/bootstrap.ts | 7 +- packages/kbn-pm/src/run.test.ts | 6 +- packages/kbn-pm/src/run.ts | 122 +- .../utils/convert_plugin_id_to_package_id.ts | 21 + .../src/utils/regenerate_base_tsconfig.ts | 35 + .../src/utils/regenerate_package_json.ts | 18 + .../utils/regenerate_synthetic_package_map.ts | 33 + packages/kbn-pm/src/utils/watch.test.ts | 65 - packages/kbn-storybook/src/webpack.config.ts | 4 +- .../kbn-synthetic-package-map/BUILD.bazel | 51 + packages/kbn-synthetic-package-map/index.d.ts | 18 + packages/kbn-synthetic-package-map/index.js | 26 + .../kbn-synthetic-package-map/package.json | 10 + .../kbn-synthetic-package-map/tsconfig.json | 15 + packages/kbn-telemetry-tools/BUILD.bazel | 4 + .../src/tools/compiler_host.ts | 59 + .../src/tools/extract_collectors.ts | 3 +- .../src/tools/serializer.test.ts | 3 +- .../src/tools/ts_parser.test.ts | 3 +- .../kbn-telemetry-tools/src/tools/utils.ts | 6 + packages/kbn-test/jest-preset.js | 14 +- scripts/kbn.js | 2 +- scripts/type_summarizer.js | 4 +- .../elasticsearch_config.test.mocks.ts | 5 +- src/dev/bazel/pkg_npm_types.bzl | 2 +- .../package_json/create_package_json_tasks.ts | 6 +- .../package_json/find_used_dependencies.ts | 94 +- src/dev/build/tasks/transpile_babel_task.ts | 31 +- src/dev/plugin_discovery/find_plugins.ts | 2 +- .../run_find_plugins_with_circular_deps.ts | 2 +- tsconfig.base.json | 443 +- .../canvas/scripts/shareable_runtime.js | 10 +- .../shareable_runtime/webpack.config.js | 7 - .../server/routes/preconfiguration/handler.ts | 2 +- .../server/services/preconfiguration/index.ts | 10 - .../fleet/server/services/setup.test.ts | 2 +- x-pack/plugins/fleet/server/services/setup.ts | 2 +- .../pdf/pdf_maker/worker_src_harness.js | 1 + yarn.lock | 45 +- 120 files changed, 27550 insertions(+), 25319 deletions(-) delete mode 100644 packages/kbn-babel-code-parser/BUILD.bazel delete mode 100755 packages/kbn-babel-code-parser/README.md delete mode 100755 packages/kbn-babel-code-parser/package.json delete mode 100644 packages/kbn-babel-code-parser/src/can_require.js delete mode 100644 packages/kbn-babel-code-parser/src/code_parser.js delete mode 100644 packages/kbn-babel-code-parser/src/strategies.js delete mode 100644 packages/kbn-babel-code-parser/src/strategies.test.js delete mode 100644 packages/kbn-babel-code-parser/src/visitors.js delete mode 100644 packages/kbn-babel-code-parser/src/visitors.test.js create mode 100644 packages/kbn-babel-plugin-synthetic-packages/BUILD.bazel create mode 100644 packages/kbn-babel-plugin-synthetic-packages/babel_plugin_synthetic_packages.js create mode 100644 packages/kbn-babel-plugin-synthetic-packages/package.json create mode 100644 packages/kbn-bazel-packages/src/parse_package_json.ts delete mode 100644 packages/kbn-config/src/plugins/plugin_search_paths.ts create mode 100644 packages/kbn-eslint-plugin-imports/src/get_import_resolver.ts create mode 100644 packages/kbn-eslint-plugin-imports/src/helpers/report.ts create mode 100644 packages/kbn-eslint-plugin-imports/src/helpers/running_in_editor.ts delete mode 100644 packages/kbn-eslint-plugin-imports/src/integration_tests/resolve_kibana_import.test.ts delete mode 100644 packages/kbn-eslint-plugin-imports/src/resolve_kibana_import.ts rename packages/kbn-eslint-plugin-imports/src/rules/{no_unresolved_imports.ts => no_unresolvable_imports.ts} (72%) create mode 100644 packages/kbn-eslint-plugin-imports/src/rules/uniform_imports.ts create mode 100644 packages/kbn-find-used-node-modules/BUILD.bazel create mode 100644 packages/kbn-find-used-node-modules/README.md rename packages/{kbn-babel-code-parser => kbn-find-used-node-modules}/jest.config.js (81%) create mode 100644 packages/kbn-find-used-node-modules/package.json create mode 100644 packages/kbn-find-used-node-modules/src/find_used_node_modules.test.ts create mode 100644 packages/kbn-find-used-node-modules/src/find_used_node_modules.ts rename packages/{kbn-pm/src/utils/sort_package_json.ts => kbn-find-used-node-modules/src/fs.ts} (51%) create mode 100644 packages/kbn-find-used-node-modules/src/get_import_requests.test.ts create mode 100644 packages/kbn-find-used-node-modules/src/get_import_requests.ts create mode 100644 packages/kbn-find-used-node-modules/src/import_visitor.ts rename packages/{kbn-babel-code-parser/src/index.js => kbn-find-used-node-modules/src/index.ts} (63%) create mode 100644 packages/kbn-find-used-node-modules/tsconfig.json create mode 100644 packages/kbn-import-resolver/BUILD.bazel create mode 100644 packages/kbn-import-resolver/README.md create mode 100644 packages/kbn-import-resolver/jest.integration.config.js create mode 100644 packages/kbn-import-resolver/package.json create mode 100644 packages/kbn-import-resolver/src/__fixtures__/node_modules/@pkg/box/index.js create mode 100644 packages/kbn-import-resolver/src/__fixtures__/node_modules/foo/index.js rename packages/{kbn-pm/cli.js => kbn-import-resolver/src/__fixtures__/packages/box/index.js} (88%) rename packages/{kbn-config/src/plugins/index.ts => kbn-import-resolver/src/__fixtures__/src/bar/bar.js} (84%) create mode 100644 packages/kbn-import-resolver/src/__fixtures__/src/bar/index.js create mode 100644 packages/kbn-import-resolver/src/__fixtures__/src/index.js rename packages/{kbn-eslint-plugin-imports => kbn-import-resolver}/src/helpers/fs.ts (55%) create mode 100644 packages/kbn-import-resolver/src/helpers/import_req.ts rename packages/{kbn-eslint-plugin-imports => kbn-import-resolver}/src/helpers/memoize.ts (100%) create mode 100644 packages/kbn-import-resolver/src/import_resolver.ts create mode 100644 packages/kbn-import-resolver/src/index.ts create mode 100644 packages/kbn-import-resolver/src/integration_tests/import_resolver.test.ts rename packages/{kbn-eslint-plugin-imports => kbn-import-resolver}/src/resolve_result.ts (74%) create mode 100644 packages/kbn-import-resolver/tsconfig.json create mode 100644 packages/kbn-pm/src/utils/convert_plugin_id_to_package_id.ts create mode 100644 packages/kbn-pm/src/utils/regenerate_base_tsconfig.ts create mode 100644 packages/kbn-pm/src/utils/regenerate_package_json.ts create mode 100644 packages/kbn-pm/src/utils/regenerate_synthetic_package_map.ts delete mode 100644 packages/kbn-pm/src/utils/watch.test.ts create mode 100644 packages/kbn-synthetic-package-map/BUILD.bazel create mode 100644 packages/kbn-synthetic-package-map/index.d.ts create mode 100644 packages/kbn-synthetic-package-map/index.js create mode 100644 packages/kbn-synthetic-package-map/package.json create mode 100644 packages/kbn-synthetic-package-map/tsconfig.json create mode 100644 packages/kbn-telemetry-tools/src/tools/compiler_host.ts delete mode 100644 x-pack/plugins/fleet/server/services/preconfiguration/index.ts diff --git a/.buildkite/scripts/build_kibana_plugins.sh b/.buildkite/scripts/build_kibana_plugins.sh index 94366d9524346..fafd68d86a65d 100755 --- a/.buildkite/scripts/build_kibana_plugins.sh +++ b/.buildkite/scripts/build_kibana_plugins.sh @@ -3,18 +3,4 @@ set -euo pipefail echo "--- Build Platform Plugins" -node scripts/build_kibana_platform_plugins \ - --scan-dir "$KIBANA_DIR/test/analytics/__fixtures__/plugins" \ - --scan-dir "$KIBANA_DIR/test/plugin_functional/plugins" \ - --scan-dir "$KIBANA_DIR/test/interpreter_functional/plugins" \ - --scan-dir "$KIBANA_DIR/test/common/fixtures/plugins" \ - --scan-dir "$KIBANA_DIR/examples" \ - --scan-dir "$XPACK_DIR/test/plugin_functional/plugins" \ - --scan-dir "$XPACK_DIR/test/functional_with_es_ssl/fixtures/plugins" \ - --scan-dir "$XPACK_DIR/test/alerting_api_integration/plugins" \ - --scan-dir "$XPACK_DIR/test/plugin_api_integration/plugins" \ - --scan-dir "$XPACK_DIR/test/plugin_api_perf/plugins" \ - --scan-dir "$XPACK_DIR/test/licensing_plugin/plugins" \ - --scan-dir "$XPACK_DIR/test/usage_collection/plugins" \ - --scan-dir "$XPACK_DIR/test/security_functional/fixtures/common" \ - --scan-dir "$XPACK_DIR/examples" +node scripts/build_kibana_platform_plugins --examples --test-plugins diff --git a/.gitignore b/.gitignore index 588c185b17a0b..7c20367dfe6de 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,7 @@ node_modules !/src/dev/npm/integration_tests/__fixtures__/fixture1/node_modules !/src/dev/notice/__fixtures__/node_modules +!/packages/kbn-import-resolver/src/__fixtures__/node_modules trash /optimize /built_assets @@ -98,4 +99,5 @@ elastic-agent-* fleet-server-* elastic-agent.yml fleet-server.yml +/packages/kbn-synthetic-package-map/synthetic-packages.json diff --git a/docs/developer/getting-started/monorepo-packages.asciidoc b/docs/developer/getting-started/monorepo-packages.asciidoc index 0216d26023a78..eed060d253a28 100644 --- a/docs/developer/getting-started/monorepo-packages.asciidoc +++ b/docs/developer/getting-started/monorepo-packages.asciidoc @@ -57,7 +57,6 @@ yarn kbn watch - @kbn/analytics - @kbn/apm-config-loader - @kbn/apm-utils -- @kbn/babel-code-parser - @kbn/babel-preset - @kbn/cli-dev-mode - @kbn/config diff --git a/package.json b/package.json index d1d4d8137d0c2..dd72003d7bd6e 100644 --- a/package.json +++ b/package.json @@ -445,6 +445,7 @@ "@babel/eslint-parser": "^7.17.0", "@babel/eslint-plugin": "^7.17.7", "@babel/generator": "^7.17.7", + "@babel/helper-plugin-utils": "^7.16.7", "@babel/parser": "^7.17.8", "@babel/plugin-proposal-class-properties": "^7.16.7", "@babel/plugin-proposal-export-namespace-from": "^7.16.7", @@ -476,7 +477,7 @@ "@jest/console": "^26.6.2", "@jest/reporters": "^26.6.2", "@kbn/axe-config": "link:bazel-bin/packages/kbn-axe-config", - "@kbn/babel-code-parser": "link:bazel-bin/packages/kbn-babel-code-parser", + "@kbn/babel-plugin-synthetic-packages": "link:bazel-bin/packages/kbn-babel-plugin-synthetic-packages", "@kbn/babel-preset": "link:bazel-bin/packages/kbn-babel-preset", "@kbn/bazel-packages": "link:bazel-bin/packages/kbn-bazel-packages", "@kbn/cli-dev-mode": "link:bazel-bin/packages/kbn-cli-dev-mode", @@ -486,13 +487,16 @@ "@kbn/es-archiver": "link:bazel-bin/packages/kbn-es-archiver", "@kbn/eslint-plugin-eslint": "link:bazel-bin/packages/kbn-eslint-plugin-eslint", "@kbn/expect": "link:bazel-bin/packages/kbn-expect", + "@kbn/find-used-node-modules": "link:bazel-bin/packages/kbn-find-used-node-modules", "@kbn/generate": "link:bazel-bin/packages/kbn-generate", + "@kbn/import-resolver": "link:bazel-bin/packages/kbn-import-resolver", "@kbn/optimizer": "link:bazel-bin/packages/kbn-optimizer", "@kbn/plugin-generator": "link:bazel-bin/packages/kbn-plugin-generator", "@kbn/plugin-helpers": "link:bazel-bin/packages/kbn-plugin-helpers", "@kbn/pm": "link:packages/kbn-pm", "@kbn/spec-to-console": "link:bazel-bin/packages/kbn-spec-to-console", "@kbn/storybook": "link:bazel-bin/packages/kbn-storybook", + "@kbn/synthetic-package-map": "link:bazel-bin/packages/kbn-synthetic-package-map", "@kbn/telemetry-tools": "link:bazel-bin/packages/kbn-telemetry-tools", "@kbn/test": "link:bazel-bin/packages/kbn-test", "@kbn/test-jest-helpers": "link:bazel-bin/packages/kbn-test-jest-helpers", @@ -528,6 +532,7 @@ "@types/apidoc": "^0.22.3", "@types/archiver": "^5.1.0", "@types/babel__core": "^7.1.19", + "@types/babel__helper-plugin-utils": "^7.10.0", "@types/base64-js": "^1.2.5", "@types/chance": "^1.0.0", "@types/chroma-js": "^1.4.2", @@ -607,9 +612,11 @@ "@types/kbn__es-query": "link:bazel-bin/packages/kbn-es-query/npm_module_types", "@types/kbn__eslint-plugin-imports": "link:bazel-bin/packages/kbn-eslint-plugin-imports/npm_module_types", "@types/kbn__field-types": "link:bazel-bin/packages/kbn-field-types/npm_module_types", + "@types/kbn__find-used-node-modules": "link:bazel-bin/packages/kbn-find-used-node-modules/npm_module_types", "@types/kbn__generate": "link:bazel-bin/packages/kbn-generate/npm_module_types", "@types/kbn__i18n": "link:bazel-bin/packages/kbn-i18n/npm_module_types", "@types/kbn__i18n-react": "link:bazel-bin/packages/kbn-i18n-react/npm_module_types", + "@types/kbn__import-resolver": "link:bazel-bin/packages/kbn-import-resolver/npm_module_types", "@types/kbn__interpreter": "link:bazel-bin/packages/kbn-interpreter/npm_module_types", "@types/kbn__io-ts-utils": "link:bazel-bin/packages/kbn-io-ts-utils/npm_module_types", "@types/kbn__logging": "link:bazel-bin/packages/kbn-logging/npm_module_types", diff --git a/packages/BUILD.bazel b/packages/BUILD.bazel index 8cc55309f30e9..3e05f7f745b6e 100644 --- a/packages/BUILD.bazel +++ b/packages/BUILD.bazel @@ -21,7 +21,7 @@ filegroup( "//packages/kbn-apm-config-loader:build", "//packages/kbn-apm-utils:build", "//packages/kbn-axe-config:build", - "//packages/kbn-babel-code-parser:build", + "//packages/kbn-babel-plugin-synthetic-packages:build", "//packages/kbn-babel-preset:build", "//packages/kbn-bazel-packages:build", "//packages/kbn-cli-dev-mode:build", @@ -40,10 +40,12 @@ filegroup( "//packages/kbn-eslint-plugin-imports:build", "//packages/kbn-expect:build", "//packages/kbn-field-types:build", + "//packages/kbn-find-used-node-modules:build", "//packages/kbn-flot-charts:build", "//packages/kbn-generate:build", "//packages/kbn-i18n-react:build", "//packages/kbn-i18n:build", + "//packages/kbn-import-resolver:build", "//packages/kbn-interpreter:build", "//packages/kbn-io-ts-utils:build", "//packages/kbn-logging-mocks:build", @@ -79,6 +81,7 @@ filegroup( "//packages/kbn-spec-to-console:build", "//packages/kbn-std:build", "//packages/kbn-storybook:build", + "//packages/kbn-synthetic-package-map:build", "//packages/kbn-telemetry-tools:build", "//packages/kbn-test-jest-helpers:build", "//packages/kbn-test-subj-selector:build", @@ -124,9 +127,11 @@ filegroup( "//packages/kbn-es-query:build_types", "//packages/kbn-eslint-plugin-imports:build_types", "//packages/kbn-field-types:build_types", + "//packages/kbn-find-used-node-modules:build_types", "//packages/kbn-generate:build_types", "//packages/kbn-i18n-react:build_types", "//packages/kbn-i18n:build_types", + "//packages/kbn-import-resolver:build_types", "//packages/kbn-interpreter:build_types", "//packages/kbn-io-ts-utils:build_types", "//packages/kbn-logging-mocks:build_types", diff --git a/packages/elastic-eslint-config-kibana/.eslintrc.js b/packages/elastic-eslint-config-kibana/.eslintrc.js index 0680fafe50de3..5882dbc57c2f9 100644 --- a/packages/elastic-eslint-config-kibana/.eslintrc.js +++ b/packages/elastic-eslint-config-kibana/.eslintrc.js @@ -110,6 +110,7 @@ module.exports = { '@kbn/eslint/no_trailing_import_slash': 'error', '@kbn/eslint/no_constructor_args_in_property_initializers': 'error', '@kbn/eslint/no_this_in_property_initializers': 'error', - '@kbn/imports/no_unresolved_imports': 'error', + '@kbn/imports/no_unresolvable_imports': 'error', + '@kbn/imports/uniform_imports': 'error', }, }; diff --git a/packages/kbn-babel-code-parser/BUILD.bazel b/packages/kbn-babel-code-parser/BUILD.bazel deleted file mode 100644 index 06cb6dfff2281..0000000000000 --- a/packages/kbn-babel-code-parser/BUILD.bazel +++ /dev/null @@ -1,61 +0,0 @@ -load("@build_bazel_rules_nodejs//:index.bzl", "js_library") -load("//src/dev/bazel:index.bzl", "jsts_transpiler", "pkg_npm") - -PKG_BASE_NAME = "kbn-babel-code-parser" -PKG_REQUIRE_NAME = "@kbn/babel-code-parser" - -SOURCE_FILES = glob( - [ - "src/**/*", - ], - exclude = [ - "**/*.test.*" - ], -) - -SRCS = SOURCE_FILES - -filegroup( - name = "srcs", - srcs = SRCS, -) - -NPM_MODULE_EXTRA_FILES = [ - "package.json", - "README.md", -] - -RUNTIME_DEPS = [ - "@npm//@babel/parser", - "@npm//@babel/traverse", - "@npm//lodash", -] - -jsts_transpiler( - name = "target_node", - srcs = SRCS, - build_pkg_name = package_name(), -) - -js_library( - name = PKG_BASE_NAME, - srcs = NPM_MODULE_EXTRA_FILES, - deps = RUNTIME_DEPS + [":target_node"], - package_name = PKG_REQUIRE_NAME, - visibility = ["//visibility:public"], -) - -pkg_npm( - name = "npm_module", - deps = [ - ":%s" % PKG_BASE_NAME, - ] -) - -filegroup( - name = "build", - srcs = [ - ":npm_module", - ], - visibility = ["//visibility:public"], -) diff --git a/packages/kbn-babel-code-parser/README.md b/packages/kbn-babel-code-parser/README.md deleted file mode 100755 index f99d01541ee22..0000000000000 --- a/packages/kbn-babel-code-parser/README.md +++ /dev/null @@ -1,19 +0,0 @@ -# @kbn/babel-code-parser - -Simple abstraction over the `@babel/parser` and the `@babel/traverse` in order -to build a code parser on top. - -We have two main functions `parseSingleFile` (sync and sync version) and the -`parseEntries` (only async version). The first one just parse one entry file -and the second one parses recursively all the files from a list of -start entry points. - -Then we have `visitors` and `strategies`. The first ones are basically the -`visitors` to use into the ast from the `@babel/traverse`. They are the only -way to collect info when using the `parseSingleFile`. The `strategies` are -meant to be used with the `parseEntries` and configures the info we want -to collect from our parsed code. After each loop, one per entry file, the -`parseEntries` method will call the given `strategy` expecting that -`strategy` would call the desired visitors, assemble the important -information to collect and adds them to the final results. - diff --git a/packages/kbn-babel-code-parser/package.json b/packages/kbn-babel-code-parser/package.json deleted file mode 100755 index 7ff913087f5bd..0000000000000 --- a/packages/kbn-babel-code-parser/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "@kbn/babel-code-parser", - "description": "babel code parser for Kibana", - "private": true, - "version": "1.0.0", - "main": "./target_node/index.js", - "license": "SSPL-1.0 OR Elastic License 2.0", - "repository": { - "type": "git", - "url": "https://github.com/elastic/kibana/tree/main/packages/kbn-babel-code-parser" - }, - "kibana": { - "devOnly": true - } -} diff --git a/packages/kbn-babel-code-parser/src/can_require.js b/packages/kbn-babel-code-parser/src/can_require.js deleted file mode 100644 index b1b41790583dd..0000000000000 --- a/packages/kbn-babel-code-parser/src/can_require.js +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -export function canRequire(cwd, entry) { - try { - // We will try to test if we can resolve - // this entry through the require.resolve - // setting as the start looking path the - // given cwd. Require.resolve will keep - // looking recursively as normal starting - // from that location. - return require.resolve(entry, { - paths: [cwd], - }); - } catch (e) { - return false; - } -} diff --git a/packages/kbn-babel-code-parser/src/code_parser.js b/packages/kbn-babel-code-parser/src/code_parser.js deleted file mode 100644 index 955d529bbabe4..0000000000000 --- a/packages/kbn-babel-code-parser/src/code_parser.js +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import { canRequire } from './can_require'; -import { readFile, readFileSync } from 'fs'; -import { extname } from 'path'; -import { promisify } from 'util'; -import * as parser from '@babel/parser'; -import traverse from '@babel/traverse'; -import * as babelParserOptions from '@kbn/babel-preset/common_babel_parser_options'; - -const read = promisify(readFile); - -function _cannotParseFile(filePath) { - return extname(filePath) !== '.js'; -} - -function _parseAndTraverseFileContent(fileContent, visitorsGenerator) { - const results = []; - - // Parse and get the code AST - // All the babel parser plugins - // were enabled - const ast = parser.parse(fileContent, babelParserOptions); - - // Loop through the code AST with - // the defined visitors - traverse(ast, visitorsGenerator(results)); - - return results; -} - -export async function parseSingleFile(filePath, visitorsGenerator) { - // Don't parse any other files than .js ones - if (_cannotParseFile(filePath)) { - return []; - } - - // Read the file - const content = await read(filePath, { encoding: 'utf8' }); - - // return the results found on parse and traverse - // the file content with the given visitors - return _parseAndTraverseFileContent(content, visitorsGenerator); -} - -export function parseSingleFileSync(filePath, visitorsGenerator) { - // Don't parse any other files than .js ones - if (_cannotParseFile(filePath)) { - return []; - } - - // Read the file - const content = readFileSync(filePath, { encoding: 'utf8' }); - - // return the results found on parse and traverse - // the file content with the given visitors - return _parseAndTraverseFileContent(content, visitorsGenerator); -} - -export async function parseEntries(cwd, entries, strategy, results, wasParsed = {}) { - // Assure that we always have a cwd - const sanitizedCwd = cwd || process.cwd(); - - // Test each entry against canRequire function - const entriesQueue = entries.map((entry) => canRequire(sanitizedCwd, entry)); - - while (entriesQueue.length) { - // Get the first element in the queue as - // select it as our current entry to parse - const mainEntry = entriesQueue.shift(); - - // Avoid parse the current entry if it is not valid - // or it was already parsed - if (typeof mainEntry !== 'string' || wasParsed[mainEntry]) { - continue; - } - - // Find new entries and adds them to the end of the queue - entriesQueue.push( - ...(await strategy(sanitizedCwd, parseSingleFile, mainEntry, wasParsed, results)) - ); - - // Mark the current main entry as already parsed - wasParsed[mainEntry] = true; - } - - return results; -} diff --git a/packages/kbn-babel-code-parser/src/strategies.js b/packages/kbn-babel-code-parser/src/strategies.js deleted file mode 100644 index 9928959da99c8..0000000000000 --- a/packages/kbn-babel-code-parser/src/strategies.js +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import { canRequire } from './can_require'; -import { dependenciesVisitorsGenerator } from './visitors'; -import { dirname, isAbsolute, resolve } from 'path'; - -export function _calculateTopLevelDependency(inputDep, outputDep = '') { - // The path separator will be always the forward slash - // as at this point we only have the found entries into - // the provided source code entries where we just use it - const pathSeparator = '/'; - const depSplitPaths = inputDep.split(pathSeparator); - const firstPart = depSplitPaths.shift(); - const outputDepFirstArgAppend = outputDep ? pathSeparator : ''; - - outputDep += `${outputDepFirstArgAppend}${firstPart}`; - - // In case our dependency isn't started by @ - // we are already done and we can return the - // dependency value we already have - if (firstPart.charAt(0) !== '@') { - return outputDep; - } - - // Otherwise we need to keep constructing the dependency - // value because dependencies starting with @ points to - // folders of dependencies. For example, in case we found - // dependencies values with '@the-deps/a' and '@the-deps/a/b' - // we don't want to map it to '@the-deps' but also to @'the-deps/a' - // because inside '@the-deps' we can also have '@the-dep/b' - return _calculateTopLevelDependency(depSplitPaths.join(pathSeparator), outputDep); -} - -export async function dependenciesParseStrategy( - cwd, - parseSingleFile, - mainEntry, - wasParsed, - results -) { - // Retrieve native nodeJS modules - const natives = process.binding('natives'); - - // Get dependencies from a single file and filter - // out node native modules from the result - const dependencies = (await parseSingleFile(mainEntry, dependenciesVisitorsGenerator)).filter( - (dep) => !natives[dep] - ); - - // Return the list of all the new entries found into - // the current mainEntry that we could use to look for - // new dependencies - return dependencies.reduce((filteredEntries, entry) => { - const absEntryPath = resolve(cwd, dirname(mainEntry), entry); - const requiredPath = canRequire(cwd, absEntryPath); - const requiredRelativePath = canRequire(cwd, entry); - const isRelativeFile = !isAbsolute(entry); - const isNodeModuleDep = isRelativeFile && !requiredPath && requiredRelativePath; - const isNewEntry = isRelativeFile && requiredPath; - - // If it is a node_module add it to the results and also - // add the resolved path for the node_module main file - // as an entry point to look for dependencies it was - // not already parsed - if (isNodeModuleDep) { - // Save the result as the top level dependency - results[_calculateTopLevelDependency(entry)] = true; - - if (!wasParsed[requiredRelativePath]) { - filteredEntries.push(requiredRelativePath); - } - } - - // If a new, not yet parsed, relative entry were found - // add it to the list of entries to be parsed - if (isNewEntry && !wasParsed[requiredPath]) { - if (!wasParsed[requiredPath]) { - filteredEntries.push(requiredPath); - } - } - - return filteredEntries; - }, []); -} diff --git a/packages/kbn-babel-code-parser/src/strategies.test.js b/packages/kbn-babel-code-parser/src/strategies.test.js deleted file mode 100644 index fef46858c5a0a..0000000000000 --- a/packages/kbn-babel-code-parser/src/strategies.test.js +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import { readFile } from 'fs'; -import { canRequire } from './can_require'; -import { parseSingleFile } from './code_parser'; -import { _calculateTopLevelDependency, dependenciesParseStrategy } from './strategies'; - -jest.mock('./can_require', () => ({ - canRequire: jest.fn(), -})); - -jest.mock('fs', () => ({ - readFile: jest.fn(), -})); - -const mockCwd = '/tmp/project/dir/'; - -describe('Code Parser Strategies', () => { - it('should calculate the top level dependencies correctly', () => { - const plainDep = 'dep1/file'; - const foldedDep = '@kbn/es/file'; - const otherFoldedDep = '@kbn/es'; - - expect(_calculateTopLevelDependency(plainDep)).toEqual('dep1'); - expect(_calculateTopLevelDependency(foldedDep)).toEqual('@kbn/es'); - expect(_calculateTopLevelDependency(otherFoldedDep)).toEqual('@kbn/es'); - }); - - it('should exclude native modules', async () => { - readFile.mockImplementationOnce((path, options, cb) => { - cb(null, `require('fs')`); - }); - - const results = []; - await dependenciesParseStrategy(mockCwd, parseSingleFile, 'dep1/file.js', {}, results); - - expect(results.length).toBe(0); - }); - - it('should return a dep from_modules', async () => { - readFile.mockImplementationOnce((path, options, cb) => { - cb(null, `require('dep_from_node_modules')`); - }); - - canRequire.mockImplementation((mockCwd, entry) => { - if (entry === `${mockCwd}dep1/dep_from_node_modules`) { - return false; - } - - if (entry === 'dep_from_node_modules') { - return `${mockCwd}node_modules/dep_from_node_modules/index.js`; - } - }); - - const results = await dependenciesParseStrategy( - mockCwd, - parseSingleFile, - 'dep1/file.js', - {}, - {} - ); - expect(results[0]).toBe(`${mockCwd}node_modules/dep_from_node_modules/index.js`); - }); - - it('should return a relative dep file', async () => { - readFile.mockImplementationOnce((path, options, cb) => { - cb(null, `require('./relative_dep')`); - }); - - canRequire.mockImplementation((mockCwd, entry) => { - if (entry === `${mockCwd}dep1/relative_dep`) { - return `${entry}/index.js`; - } - - return false; - }); - - const results = await dependenciesParseStrategy( - mockCwd, - parseSingleFile, - 'dep1/file.js', - {}, - {} - ); - expect(results[0]).toBe(`${mockCwd}dep1/relative_dep/index.js`); - }); - - afterAll(() => { - jest.clearAllMocks(); - }); -}); diff --git a/packages/kbn-babel-code-parser/src/visitors.js b/packages/kbn-babel-code-parser/src/visitors.js deleted file mode 100644 index 9974b58b5fb7e..0000000000000 --- a/packages/kbn-babel-code-parser/src/visitors.js +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import { matches } from 'lodash'; - -/** - * @notice - * - * This product has relied on ASTExplorer that is licensed under MIT. - */ -export function dependenciesVisitorsGenerator(dependenciesAcc) { - return (() => { - // This was built with help on an ast explorer and some ESTree docs - // like the babel parser ast spec and the main docs for the Esprima - // which is a complete and useful docs for the ESTree spec. - // - // https://astexplorer.net - // https://github.com/babel/babel/blob/master/packages/babel-parser/ast/spec.md - // https://esprima.readthedocs.io/en/latest/syntax-tree-format.html - // https://github.com/estree/estree - return { - // Visitors to traverse and found dependencies - // raw values on require + require.resolve - CallExpression: ({ node }) => { - // AST check for require expressions - const isRequire = (node) => { - return matches({ - callee: { - type: 'Identifier', - name: 'require', - }, - })(node); - }; - - // AST check for require.resolve expressions - const isRequireResolve = (node) => { - return matches({ - callee: { - type: 'MemberExpression', - object: { - type: 'Identifier', - name: 'require', - }, - property: { - type: 'Identifier', - name: 'resolve', - }, - }, - })(node); - }; - - // Get string values inside the expressions - // whether they are require or require.resolve - if (isRequire(node) || isRequireResolve(node)) { - const nodeArguments = node.arguments; - const reqArg = Array.isArray(nodeArguments) ? nodeArguments.shift() : null; - - if (!reqArg) { - return; - } - - if (reqArg.type === 'StringLiteral') { - dependenciesAcc.push(reqArg.value); - } - } - }, - // Visitors to traverse and found dependencies - // raw values on import - ImportDeclaration: ({ node }) => { - // AST check for supported import expressions - const isImport = (node) => { - return matches({ - type: 'ImportDeclaration', - source: { - type: 'StringLiteral', - }, - })(node); - }; - - // Get string values from import expressions - if (isImport(node)) { - const importSource = node.source; - dependenciesAcc.push(importSource.value); - } - }, - // Visitors to traverse and found dependencies - // raw values on export from - ExportNamedDeclaration: ({ node }) => { - // AST check for supported export from expressions - const isExportFrom = (node) => { - return matches({ - type: 'ExportNamedDeclaration', - source: { - type: 'StringLiteral', - }, - })(node); - }; - - // Get string values from export from expressions - if (isExportFrom(node)) { - const exportFromSource = node.source; - dependenciesAcc.push(exportFromSource.value); - } - }, - // Visitors to traverse and found dependencies - // raw values on export * from - ExportAllDeclaration: ({ node }) => { - // AST check for supported export * from expressions - const isExportAllFrom = (node) => { - return matches({ - type: 'ExportAllDeclaration', - source: { - type: 'StringLiteral', - }, - })(node); - }; - - // Get string values from export * from expressions - if (isExportAllFrom(node)) { - const exportAllFromSource = node.source; - dependenciesAcc.push(exportAllFromSource.value); - } - }, - }; - })(); -} diff --git a/packages/kbn-babel-code-parser/src/visitors.test.js b/packages/kbn-babel-code-parser/src/visitors.test.js deleted file mode 100644 index fd8413840d4de..0000000000000 --- a/packages/kbn-babel-code-parser/src/visitors.test.js +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import * as parser from '@babel/parser'; -import traverse from '@babel/traverse'; -import { dependenciesVisitorsGenerator } from './visitors'; - -const visitorsApplier = (code) => { - const result = []; - traverse( - parser.parse(code, { - sourceType: 'unambiguous', - plugins: ['exportDefaultFrom'], - }), - dependenciesVisitorsGenerator(result) - ); - return result; -}; - -describe('Code Parser Visitors', () => { - it('should get values from require', () => { - const rawCode = `/*foo*/require('dep1'); const bar = 1;`; - const foundDeps = visitorsApplier(rawCode); - expect(foundDeps[0] === 'dep1'); - }); - - it('should get values from require.resolve', () => { - const rawCode = `/*foo*/require.resolve('dep2'); const bar = 1;`; - const foundDeps = visitorsApplier(rawCode); - expect(foundDeps[0] === 'dep2'); - }); - - it('should get values from import', () => { - const rawCode = `/*foo*/import dep1 from 'dep1'; import dep2 from 'dep2';const bar = 1;`; - const foundDeps = visitorsApplier(rawCode); - expect(foundDeps[0] === 'dep1'); - expect(foundDeps[1] === 'dep2'); - }); - - it('should get values from export from', () => { - const rawCode = `/*foo*/export dep1 from 'dep1'; import dep2 from 'dep2';const bar = 1;`; - const foundDeps = visitorsApplier(rawCode); - expect(foundDeps[0] === 'dep1'); - }); - - it('should get values from export * from', () => { - const rawCode = `/*foo*/export * from 'dep1'; export dep2 from 'dep2';const bar = 1;`; - const foundDeps = visitorsApplier(rawCode); - expect(foundDeps[0] === 'dep1'); - expect(foundDeps[1] === 'dep2'); - }); -}); diff --git a/packages/kbn-babel-plugin-synthetic-packages/BUILD.bazel b/packages/kbn-babel-plugin-synthetic-packages/BUILD.bazel new file mode 100644 index 0000000000000..da588dab2ce42 --- /dev/null +++ b/packages/kbn-babel-plugin-synthetic-packages/BUILD.bazel @@ -0,0 +1,64 @@ +load("@npm//@bazel/typescript:index.bzl", "ts_config") +load("@build_bazel_rules_nodejs//:index.bzl", "js_library") +load("//src/dev/bazel:index.bzl", "jsts_transpiler", "pkg_npm", "pkg_npm_types", "ts_project") + +PKG_DIRNAME = "kbn-babel-plugin-synthetic-packages" +PKG_REQUIRE_NAME = "@kbn/babel-plugin-synthetic-packages" + +filegroup( + name = "srcs", + srcs = [ + "babel_plugin_synthetic_packages.js" + ], +) + +NPM_MODULE_EXTRA_FILES = [ + "package.json", +] + +# In this array place runtime dependencies, including other packages and NPM packages +# which must be available for this code to run. +# +# To reference other packages use: +# "//repo/relative/path/to/package" +# eg. "//packages/kbn-utils" +# +# To reference a NPM package use: +# "@npm//name-of-package" +# eg. "@npm//lodash" +RUNTIME_DEPS = [ + "@npm//@babel/helper-plugin-utils", + "@npm//normalize-path", + "//packages/kbn-synthetic-package-map", +] + +js_library( + name = PKG_DIRNAME, + srcs = NPM_MODULE_EXTRA_FILES + [ + ":srcs", + ], + deps = RUNTIME_DEPS, + package_name = PKG_REQUIRE_NAME, + visibility = ["//visibility:public"], +) + +pkg_npm( + name = "npm_module", + deps = [ + ":%s" % PKG_DIRNAME, + ] +) + +filegroup( + name = "build", + srcs = [ + ":npm_module", + ], + visibility = ["//visibility:public"], +) + +alias( + name = "npm_module_types", + actual = ":" + PKG_DIRNAME, + visibility = ["//visibility:public"], +) diff --git a/packages/kbn-babel-plugin-synthetic-packages/babel_plugin_synthetic_packages.js b/packages/kbn-babel-plugin-synthetic-packages/babel_plugin_synthetic_packages.js new file mode 100644 index 0000000000000..8caa3906c8fe0 --- /dev/null +++ b/packages/kbn-babel-plugin-synthetic-packages/babel_plugin_synthetic_packages.js @@ -0,0 +1,183 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +/** @typedef {import('@babel/core').PluginObj} PluginObj */ + +const Path = require('path'); +const Fs = require('fs'); + +const T = require('@babel/types'); +const normalizePath = require('normalize-path'); +const { declare } = require('@babel/helper-plugin-utils'); +const KbnSyntheticPackageMap = require('@kbn/synthetic-package-map'); + +const PKG_MAP = KbnSyntheticPackageMap.readPackageMap(); +const PKG_MAP_HASH = KbnSyntheticPackageMap.readHashOfPackageMap(); + +function getFilename(state) { + if (typeof state !== 'object' || !state || !state.filename || !Path.isAbsolute(state.filename)) { + throw new Error( + `@kbn/babel-plugin-synthetic-packages is only compatible when building files with absolute filename state` + ); + } + + return state.filename; +} + +let foundKibanaRoot; +function getKibanaRoot(someSourceFilename) { + if (foundKibanaRoot) { + return foundKibanaRoot; + } + + // try to find the Kibana package.json file in a parent directory of the sourceFile + let cursorDir = Path.dirname(someSourceFilename); + while (true) { + const packageJsonPath = Path.resolve(cursorDir, 'package.json'); + try { + const pkg = JSON.parse(Fs.readFileSync(packageJsonPath, 'utf8')); + if (pkg && pkg.name === 'kibana') { + foundKibanaRoot = cursorDir; + return foundKibanaRoot; + } + } catch { + // this directory is not the Kibana dir + } + + const nextCursor = Path.dirname(cursorDir); + if (!nextCursor || nextCursor === cursorDir) { + // stop iterating when we get to the root of the root of the filesystem + break; + } + + cursorDir = nextCursor; + } + + throw new Error( + '@kbn/*-plugin and @kbn/core imports can only be used by source files which have not been converted to packages, building packages which rely on these imports requires converting the thing you want into a package.' + ); +} + +function fixImportRequest(req, filename, kibanaRoot) { + if (!req.startsWith('@kbn/')) { + return; + } + + const parts = req.split('/'); + const dir = PKG_MAP.get(`@kbn/${parts[1]}`); + if (!dir) { + return; + } + + return normalizePath( + Path.relative( + Path.dirname(filename), + Path.resolve(kibanaRoot ?? getKibanaRoot(filename), dir, ...parts.slice(2)) + ) + ); +} + +/** + * @param {T.CallExpression} node + */ +function isDynamicImport(node) { + return !!( + T.isImport(node.callee) && + node.arguments.length === 1 && + T.isStringLiteral(node.arguments[0]) + ); +} + +/** + * @param {T.CallExpression} node + */ +function isRequire(node) { + return !!( + T.isIdentifier(node.callee) && + node.callee.name === 'require' && + node.arguments.length >= 1 && + T.isStringLiteral(node.arguments[0]) + ); +} + +/** + * @param {T.CallExpression} node + */ +function isRequireResolve(node) { + return !!( + T.isMemberExpression(node.callee) && + T.isIdentifier(node.callee.object) && + node.callee.object.name === 'require' && + T.isIdentifier(node.callee.property) && + node.callee.property.name === 'resolve' && + node.arguments.length >= 1 && + T.isStringLiteral(node.arguments[0]) + ); +} + +/** + * @param {T.CallExpression} node + */ +function isJestMockCall(node) { + return !!( + T.isMemberExpression(node.callee) && + T.isIdentifier(node.callee.object) && + node.callee.object.name === 'jest' && + node.arguments.length >= 1 && + T.isStringLiteral(node.arguments[0]) + ); +} + +module.exports = declare((api, options) => { + const kibanaRoot = options['kibana/rootDir']; + + api.assertVersion(7); + api.cache.using(() => `${PKG_MAP_HASH}:${kibanaRoot}`); + + /** @type {PluginObj} */ + const plugin = { + name: 'synthetic-packages', + visitor: { + 'ImportDeclaration|ExportNamedDeclaration|ExportAllDeclaration'(path) { + const filename = getFilename(this); + + const source = path.node.source; + if (!T.isStringLiteral(source)) { + return; + } + + const req = source.value; + const newReq = fixImportRequest(req, filename, kibanaRoot); + if (newReq) { + path.get('source').replaceWith(T.stringLiteral(newReq)); + } + }, + CallExpression(path) { + const filename = getFilename(this); + + const { node } = path; + if ( + !isDynamicImport(node) && + !isRequire(node) && + !isRequireResolve(node) && + !isJestMockCall(node) + ) { + return; + } + + const req = node.arguments[0].value; + const newReq = fixImportRequest(req, filename, kibanaRoot); + if (newReq) { + path.get('arguments.0').replaceWith(T.stringLiteral(newReq)); + } + }, + }, + }; + + return plugin; +}); diff --git a/packages/kbn-babel-plugin-synthetic-packages/package.json b/packages/kbn-babel-plugin-synthetic-packages/package.json new file mode 100644 index 0000000000000..f488064fc6100 --- /dev/null +++ b/packages/kbn-babel-plugin-synthetic-packages/package.json @@ -0,0 +1,10 @@ +{ + "name": "@kbn/babel-plugin-synthetic-packages", + "private": true, + "version": "1.0.0", + "main": "./babel_plugin_synthetic_packages.js", + "license": "SSPL-1.0 OR Elastic License 2.0", + "kibana": { + "devOnly": true + } +} diff --git a/packages/kbn-babel-preset/BUILD.bazel b/packages/kbn-babel-preset/BUILD.bazel index 8e600eb6b23be..1e64c1e9f9ef7 100644 --- a/packages/kbn-babel-preset/BUILD.bazel +++ b/packages/kbn-babel-preset/BUILD.bazel @@ -40,6 +40,7 @@ RUNTIME_DEPS = [ "@npm//babel-plugin-add-module-exports", "@npm//babel-plugin-styled-components", "@npm//babel-plugin-transform-react-remove-prop-types", + "//packages/kbn-babel-plugin-synthetic-packages", ] js_library( diff --git a/packages/kbn-babel-preset/common_preset.js b/packages/kbn-babel-preset/common_preset.js index 824a73f9b2611..1c3e2135d1049 100644 --- a/packages/kbn-babel-preset/common_preset.js +++ b/packages/kbn-babel-preset/common_preset.js @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -module.exports = { +module.exports = (_, options = {}) => ({ presets: [ // plugins always run before presets, but in this case we need the // @babel/preset-typescript preset to run first so we have to move @@ -46,6 +46,8 @@ module.exports = { version: '^7.12.5', }, ], + + [require.resolve('@kbn/babel-plugin-synthetic-packages'), options], ], }, @@ -59,4 +61,4 @@ module.exports = { }, ], ], -}; +}); diff --git a/packages/kbn-babel-preset/node_preset.js b/packages/kbn-babel-preset/node_preset.js index b69c59f5e2cc5..295ea5d0d8e8b 100644 --- a/packages/kbn-babel-preset/node_preset.js +++ b/packages/kbn-babel-preset/node_preset.js @@ -37,7 +37,7 @@ module.exports = (_, options = {}) => { ...(options['@babel/preset-env'] || {}), }, ], - require('./common_preset'), + [require('./common_preset'), options], ], }; }; diff --git a/packages/kbn-babel-preset/webpack_preset.js b/packages/kbn-babel-preset/webpack_preset.js index 7bf1f518012a4..1f5a840f4f54d 100644 --- a/packages/kbn-babel-preset/webpack_preset.js +++ b/packages/kbn-babel-preset/webpack_preset.js @@ -8,7 +8,7 @@ const { USES_STYLED_COMPONENTS } = require('./styled_components_files'); -module.exports = () => { +module.exports = (_, options = {}) => { return { presets: [ [ @@ -22,7 +22,7 @@ module.exports = () => { bugfixes: true, }, ], - require('./common_preset'), + [require('./common_preset'), options], ], env: { production: { diff --git a/packages/kbn-bazel-packages/BUILD.bazel b/packages/kbn-bazel-packages/BUILD.bazel index 9adfe80060889..024282768d633 100644 --- a/packages/kbn-bazel-packages/BUILD.bazel +++ b/packages/kbn-bazel-packages/BUILD.bazel @@ -39,6 +39,7 @@ NPM_MODULE_EXTRA_FILES = [ RUNTIME_DEPS = [ "//packages/kbn-utils", "//packages/kbn-std", + "//packages/kbn-synthetic-package-map", "@npm//globby", "@npm//normalize-path", ] @@ -56,6 +57,7 @@ RUNTIME_DEPS = [ TYPES_DEPS = [ "//packages/kbn-utils:npm_module_types", "//packages/kbn-std:npm_module_types", + "//packages/kbn-synthetic-package-map:npm_module_types", "@npm//@types/normalize-path", "@npm//globby", "@npm//normalize-path", diff --git a/packages/kbn-bazel-packages/src/bazel_package.ts b/packages/kbn-bazel-packages/src/bazel_package.ts index 35950c9896faf..492ce05cf04bf 100644 --- a/packages/kbn-bazel-packages/src/bazel_package.ts +++ b/packages/kbn-bazel-packages/src/bazel_package.ts @@ -13,51 +13,21 @@ import Fsp from 'fs/promises'; import normalizePath from 'normalize-path'; import { REPO_ROOT } from '@kbn/utils'; +import { readPackageJson, ParsedPackageJson } from './parse_package_json'; + const BUILD_RULE_NAME = /(^|\s)name\s*=\s*"build"/; const BUILD_TYPES_RULE_NAME = /(^|\s)name\s*=\s*"build_types"/; -/** - * Simple parsed representation of a package.json file, validated - * by `assertParsedPackageJson()` and extensible as needed in the future - */ -export interface ParsedPackageJson { - /** - * The name of the package, usually `@kbn/`+something - */ - name: string; - /** - * All other fields in the package.json are typed as unknown as all we need at this time is "name" - */ - [key: string]: unknown; -} - -function isObj(v: unknown): v is Record { - return !!(typeof v === 'object' && v); -} - -function assertParsedPackageJson(v: unknown): asserts v is ParsedPackageJson { - if (!isObj(v) || typeof v.name !== 'string') { - throw new Error('Expected parsed package.json to be an object with at least a "name" property'); - } -} - /** * Representation of a Bazel Package in the Kibana repository */ export class BazelPackage { /** * Create a BazelPackage object from a package directory. Reads some files from the package and returns - * a Promise for a BazelPackage instance + * a Promise for a BazelPackage instance. */ static async fromDir(dir: string) { - let pkg; - try { - pkg = JSON.parse(await Fsp.readFile(Path.resolve(dir, 'package.json'), 'utf8')); - } catch (error) { - throw new Error(`unable to parse package.json in [${dir}]: ${error.message}`); - } - - assertParsedPackageJson(pkg); + const pkg = readPackageJson(Path.resolve(dir, 'package.json')); let buildBazelContent; if (pkg.name !== '@kbn/pm') { diff --git a/packages/kbn-bazel-packages/src/discover_packages.ts b/packages/kbn-bazel-packages/src/discover_packages.ts index fa636b9d3dba6..db31b54beec75 100644 --- a/packages/kbn-bazel-packages/src/discover_packages.ts +++ b/packages/kbn-bazel-packages/src/discover_packages.ts @@ -15,22 +15,23 @@ import { asyncMapWithLimit } from '@kbn/std'; import { BazelPackage } from './bazel_package'; import { BAZEL_PACKAGE_DIRS } from './bazel_package_dirs'; -/** - * Search the local Kibana repo for bazel packages and return an array of BazelPackage objects - * representing each package found. - */ -export async function discoverBazelPackages() { - const packageJsons = globby.sync( - BAZEL_PACKAGE_DIRS.map((dir) => `${dir}/*/package.json`), - { - cwd: REPO_ROOT, - absolute: true, - } - ); +export function discoverBazelPackageLocations(repoRoot: string) { + return globby + .sync( + BAZEL_PACKAGE_DIRS.map((dir) => `${dir}/*/package.json`), + { + cwd: repoRoot, + absolute: true, + } + ) + .sort((a, b) => a.localeCompare(b)) + .map((path) => Path.dirname(path)); +} +export async function discoverBazelPackages(repoRoot: string = REPO_ROOT) { return await asyncMapWithLimit( - packageJsons.sort((a, b) => a.localeCompare(b)), + discoverBazelPackageLocations(repoRoot), 100, - async (path) => await BazelPackage.fromDir(Path.dirname(path)) + async (dir) => await BazelPackage.fromDir(dir) ); } diff --git a/packages/kbn-bazel-packages/src/parse_package_json.ts b/packages/kbn-bazel-packages/src/parse_package_json.ts new file mode 100644 index 0000000000000..b213c7c8596b0 --- /dev/null +++ b/packages/kbn-bazel-packages/src/parse_package_json.ts @@ -0,0 +1,63 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import Fs from 'fs'; + +/** + * Simple parsed representation of a package.json file, validated + * by `assertParsedPackageJson()` and extensible as needed in the future + */ +export interface ParsedPackageJson { + /** + * The name of the package, usually `@kbn/`+something + */ + name: string; + /** "dependenices" property from package.json */ + dependencies?: Record; + /** "devDependenices" property from package.json */ + devDependencies?: Record; + /** + * All other fields in the package.json are typed as unknown as we don't care what they are + */ + [key: string]: unknown; +} + +function isObj(v: unknown): v is Record { + return !!(typeof v === 'object' && v); +} + +/** + * Asserts that given value looks like a parsed package.json file + */ +export function assertParsedPackageJson(v: unknown): asserts v is ParsedPackageJson { + if (!isObj(v) || typeof v.name !== 'string') { + throw new Error('Expected at least a "name" property'); + } + + if (v.dependencies && !isObj(v.dependencies)) { + throw new Error('Expected "dependencies" to be an object'); + } + + if (v.devDependencies && !isObj(v.devDependencies)) { + throw new Error('Expected "dependencies" to be an object'); + } +} + +/** + * Reads a given package.json file from disk and parses it + */ +export function readPackageJson(path: string): ParsedPackageJson { + let pkg; + try { + pkg = JSON.parse(Fs.readFileSync(path, 'utf8')); + assertParsedPackageJson(pkg); + } catch (error) { + throw new Error(`unable to parse package.json at [${path}]: ${error.message}`); + } + return pkg; +} diff --git a/packages/kbn-config/BUILD.bazel b/packages/kbn-config/BUILD.bazel index e242cf5c92622..3567c549a77c4 100644 --- a/packages/kbn-config/BUILD.bazel +++ b/packages/kbn-config/BUILD.bazel @@ -37,6 +37,7 @@ RUNTIME_DEPS = [ "//packages/kbn-std", "//packages/kbn-utility-types", "//packages/kbn-i18n", + "//packages/kbn-plugin-discovery", "@npm//js-yaml", "@npm//load-json-file", "@npm//lodash", @@ -52,6 +53,7 @@ TYPES_DEPS = [ "//packages/kbn-std:npm_module_types", "//packages/kbn-utility-types:npm_module_types", "//packages/kbn-i18n:npm_module_types", + "//packages/kbn-plugin-discovery:npm_module_types", "@npm//load-json-file", "@npm//rxjs", "@npm//@types/jest", diff --git a/packages/kbn-config/src/env.ts b/packages/kbn-config/src/env.ts index 73f32606c463f..4c54178447105 100644 --- a/packages/kbn-config/src/env.ts +++ b/packages/kbn-config/src/env.ts @@ -8,7 +8,7 @@ import { resolve, join } from 'path'; import loadJsonFile from 'load-json-file'; -import { getPluginSearchPaths } from './plugins'; +import { getPluginSearchPaths } from '@kbn/plugin-discovery'; import { PackageInfo, EnvironmentMode } from './types'; /** @internal */ diff --git a/packages/kbn-config/src/index.ts b/packages/kbn-config/src/index.ts index 272ee7598570c..e4b60d939c074 100644 --- a/packages/kbn-config/src/index.ts +++ b/packages/kbn-config/src/index.ts @@ -30,4 +30,3 @@ export { ObjectToConfigAdapter } from './object_to_config_adapter'; export type { CliArgs, RawPackageInfo } from './env'; export { Env } from './env'; export type { EnvironmentMode, PackageInfo } from './types'; -export { getPluginSearchPaths } from './plugins'; diff --git a/packages/kbn-config/src/plugins/plugin_search_paths.ts b/packages/kbn-config/src/plugins/plugin_search_paths.ts deleted file mode 100644 index 32eb36f9bc956..0000000000000 --- a/packages/kbn-config/src/plugins/plugin_search_paths.ts +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import { resolve } from 'path'; - -interface SearchOptions { - rootDir: string; - oss: boolean; - examples: boolean; -} - -export function getPluginSearchPaths({ rootDir, oss, examples }: SearchOptions) { - return [ - resolve(rootDir, 'src', 'plugins'), - ...(oss ? [] : [resolve(rootDir, 'x-pack', 'plugins')]), - resolve(rootDir, 'plugins'), - ...(examples ? [resolve(rootDir, 'examples')] : []), - ...(examples && !oss ? [resolve(rootDir, 'x-pack', 'examples')] : []), - resolve(rootDir, '..', 'kibana-extra'), - ]; -} diff --git a/packages/kbn-docs-utils/BUILD.bazel b/packages/kbn-docs-utils/BUILD.bazel index 30baa9dccb7f7..a9035e5aeed89 100644 --- a/packages/kbn-docs-utils/BUILD.bazel +++ b/packages/kbn-docs-utils/BUILD.bazel @@ -28,7 +28,7 @@ NPM_MODULE_EXTRA_FILES = [ ] RUNTIME_DEPS = [ - "//packages/kbn-config", + "//packages/kbn-plugin-discovery", "//packages/kbn-dev-utils", "//packages/kbn-utils", "@npm//dedent", @@ -36,7 +36,7 @@ RUNTIME_DEPS = [ ] TYPES_DEPS = [ - "//packages/kbn-config:npm_module_types", + "//packages/kbn-plugin-discovery:npm_module_types", "//packages/kbn-dev-utils:npm_module_types", "//packages/kbn-utils:npm_module_types", "@npm//ts-morph", diff --git a/packages/kbn-docs-utils/src/api_docs/find_plugins.ts b/packages/kbn-docs-utils/src/api_docs/find_plugins.ts index ebe329029302c..5740d094a6894 100644 --- a/packages/kbn-docs-utils/src/api_docs/find_plugins.ts +++ b/packages/kbn-docs-utils/src/api_docs/find_plugins.ts @@ -11,8 +11,7 @@ import globby from 'globby'; import loadJsonFile from 'load-json-file'; -import { getPluginSearchPaths } from '@kbn/config'; -import { simpleKibanaPlatformPluginDiscovery } from '@kbn/plugin-discovery'; +import { getPluginSearchPaths, simpleKibanaPlatformPluginDiscovery } from '@kbn/plugin-discovery'; import { REPO_ROOT } from '@kbn/utils'; import { ApiScope, PluginOrPackage } from './types'; diff --git a/packages/kbn-eslint-plugin-eslint/BUILD.bazel b/packages/kbn-eslint-plugin-eslint/BUILD.bazel index c02a468456f77..f8242afb6cf9e 100644 --- a/packages/kbn-eslint-plugin-eslint/BUILD.bazel +++ b/packages/kbn-eslint-plugin-eslint/BUILD.bazel @@ -30,6 +30,7 @@ NPM_MODULE_EXTRA_FILES = [ ] RUNTIME_DEPS = [ + "//packages/kbn-utils", "@npm//@babel/eslint-parser", "@npm//dedent", "@npm//eslint", diff --git a/packages/kbn-eslint-plugin-eslint/rules/no_restricted_paths.js b/packages/kbn-eslint-plugin-eslint/rules/no_restricted_paths.js index 733bfc91ab9e1..97126995f3b52 100644 --- a/packages/kbn-eslint-plugin-eslint/rules/no_restricted_paths.js +++ b/packages/kbn-eslint-plugin-eslint/rules/no_restricted_paths.js @@ -28,7 +28,7 @@ */ const path = require('path'); const mm = require('micromatch'); -const { resolveKibanaImport } = require('@kbn/eslint-plugin-imports'); +const { getImportResolver } = require('@kbn/eslint-plugin-imports'); function isStaticRequire(node) { return ( @@ -90,6 +90,8 @@ module.exports = { }, create(context) { + const resolver = getImportResolver(context); + const sourcePath = context.getPhysicalFilename ? context.getPhysicalFilename() : context.getFilename(); @@ -103,7 +105,7 @@ module.exports = { } function checkForRestrictedImportPath(importPath, node) { - const resolveReport = resolveKibanaImport(importPath, sourceDirname); + const resolveReport = resolver.resolve(importPath, sourceDirname); if (resolveReport?.type !== 'file' || resolveReport.nodeModule) { return; diff --git a/packages/kbn-eslint-plugin-imports/BUILD.bazel b/packages/kbn-eslint-plugin-imports/BUILD.bazel index ecfb51b9a6ecb..6d5facdd14e0f 100644 --- a/packages/kbn-eslint-plugin-imports/BUILD.bazel +++ b/packages/kbn-eslint-plugin-imports/BUILD.bazel @@ -37,6 +37,7 @@ NPM_MODULE_EXTRA_FILES = [ # eg. "@npm//lodash" RUNTIME_DEPS = [ "//packages/kbn-utils", + "//packages/kbn-import-resolver", "@npm//resolve", "@npm//@typescript-eslint/typescript-estree", "@npm//eslint", @@ -55,6 +56,7 @@ RUNTIME_DEPS = [ TYPES_DEPS = [ "//packages/kbn-utils:npm_module_types", "//packages/kbn-dev-utils:npm_module_types", # only required for the tests, which are excluded except on windows + "//packages/kbn-import-resolver:npm_module_types", "@npm//@types/eslint", "@npm//@types/jest", "@npm//@types/node", diff --git a/packages/kbn-eslint-plugin-imports/src/get_import_resolver.ts b/packages/kbn-eslint-plugin-imports/src/get_import_resolver.ts new file mode 100644 index 0000000000000..331232288aef1 --- /dev/null +++ b/packages/kbn-eslint-plugin-imports/src/get_import_resolver.ts @@ -0,0 +1,30 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { ImportResolver } from '@kbn/import-resolver'; +import { REPO_ROOT } from '@kbn/utils'; +import { Rule } from 'eslint'; +import { RUNNING_IN_EDITOR } from './helpers/running_in_editor'; + +let importResolverCache: ImportResolver | undefined; + +/** + * Create a request resolver for ESLint, requires a PluginPackageResolver from @kbn/bazel-packages which will + * be created and cached on contextServices automatically. + * + * All import requests in the repository should return a result, if they don't it's a bug + * which should be caught by the `@kbn/import/no_unresolved` rule, which should never be disabled. If you need help + * adding support for an import style please reach out to operations. + */ +export function getImportResolver(context: Rule.RuleContext): ImportResolver { + if (RUNNING_IN_EDITOR) { + return (context.parserServices.kibanaImportResolver ||= ImportResolver.create(REPO_ROOT)); + } + + return (importResolverCache ||= ImportResolver.create(REPO_ROOT)); +} diff --git a/packages/kbn-eslint-plugin-imports/src/helpers/report.ts b/packages/kbn-eslint-plugin-imports/src/helpers/report.ts new file mode 100644 index 0000000000000..bfcd9956018cc --- /dev/null +++ b/packages/kbn-eslint-plugin-imports/src/helpers/report.ts @@ -0,0 +1,31 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import Eslint from 'eslint'; +import { SomeNode } from './visit_all_import_statements'; + +interface ReportOptions { + node: SomeNode; + message: string; + correctImport?: string; +} + +/** + * Simple wrapper around context.report so that the types work better with typescript-estree + */ +export function report(context: Eslint.Rule.RuleContext, options: ReportOptions) { + context.report({ + node: options.node as any, + message: options.message, + fix: options.correctImport + ? (fixer) => { + return fixer.replaceText(options.node as any, `'${options.correctImport}'`); + } + : null, + }); +} diff --git a/packages/kbn-eslint-plugin-imports/src/helpers/running_in_editor.ts b/packages/kbn-eslint-plugin-imports/src/helpers/running_in_editor.ts new file mode 100644 index 0000000000000..3067cc9d1005f --- /dev/null +++ b/packages/kbn-eslint-plugin-imports/src/helpers/running_in_editor.ts @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +export const RUNNING_IN_EDITOR = + // vscode sets this in the env for all workers + !!process.env.VSCODE_CWD || + // MacOS sets this for intellij processes, not sure if it works in webstorm but we could expand this check later + !!process.env.__CFBundleIdentifier?.startsWith('com.jetbrains.intellij'); diff --git a/packages/kbn-eslint-plugin-imports/src/helpers/visit_all_import_statements.ts b/packages/kbn-eslint-plugin-imports/src/helpers/visit_all_import_statements.ts index c65843764ef79..fe6b9b2ed04ba 100644 --- a/packages/kbn-eslint-plugin-imports/src/helpers/visit_all_import_statements.ts +++ b/packages/kbn-eslint-plugin-imports/src/helpers/visit_all_import_statements.ts @@ -6,73 +6,113 @@ * Side Public License, v 1. */ +import { Rule } from 'eslint'; import { AST_NODE_TYPES, TSESTree } from '@typescript-eslint/typescript-estree'; -// @ts-expect-error no types for this module -import moduleVisitor from 'eslint-module-utils/moduleVisitor'; +import * as T from '@babel/types'; +import { ImportType } from '@kbn/import-resolver'; -type Importers = - | TSESTree.ImportDeclaration - | TSESTree.ExportNamedDeclaration - | TSESTree.ExportAllDeclaration - | TSESTree.CallExpression - | TSESTree.ImportExpression - | TSESTree.CallExpression; +const JEST_MODULE_METHODS = [ + 'jest.createMockFromModule', + 'jest.mock', + 'jest.unmock', + 'jest.doMock', + 'jest.dontMock', + 'jest.setMock', + 'jest.requireActual', + 'jest.requireMock', +]; -type ImportVisitor = (req: string, node: Importers) => void; +export type SomeNode = TSESTree.Node | T.Node; + +type Visitor = (req: string | null, node: SomeNode, type: ImportType) => void; + +const isIdent = (node: SomeNode): node is TSESTree.Identifier | T.Identifier => + T.isIdentifier(node) || node.type === AST_NODE_TYPES.Identifier; + +const isStringLiteral = (node: SomeNode): node is TSESTree.StringLiteral | T.StringLiteral => + T.isStringLiteral(node) || + (node.type === AST_NODE_TYPES.Literal && typeof node.value === 'string'); + +const isTemplateLiteral = (node: SomeNode): node is TSESTree.TemplateLiteral | T.TemplateLiteral => + T.isTemplateLiteral(node) || node.type === AST_NODE_TYPES.TemplateLiteral; + +function passSourceAsString(source: SomeNode | null | undefined, type: ImportType, fn: Visitor) { + if (!source) { + return; + } + + if (isStringLiteral(source)) { + return fn(source.value, source, type); + } + + if (isTemplateLiteral(source)) { + if (source.expressions.length) { + return null; + } + + return fn( + [...source.quasis].reduce((acc, q) => acc + q.value.raw, ''), + source, + type + ); + } + + return fn(null, source, type); +} /** - * Create an ESLint rule visitor that calls visitor() for every import string, including - * 'export from' statements, require() calls, jest.mock() calls, and more. + * Create an ESLint rule visitor that calls fn() for every import string, including + * 'export from' statements, require() calls, require.resolve(), jest.mock() calls, and more. + * Works with both babel eslint and typescript-eslint parsers */ -export function visitAllImportStatements(visitor: ImportVisitor) { - const baseWrapper = moduleVisitor( - (reqNode: TSESTree.Literal, importer: Importers) => { - const req = reqNode.value; - if (typeof req !== 'string') { - throw new Error('unable to read value of import request'); - } - - visitor(req, importer); +export function visitAllImportStatements(fn: Visitor) { + const visitor = { + ImportDeclaration(node: TSESTree.ImportDeclaration | T.ImportDeclaration) { + passSourceAsString(node.source, 'esm', fn); }, - { - esmodules: true, - commonjs: true, - } - ); - - const baseCallExpressionVisitor = baseWrapper.CallExpression; - - /** - * wrapper around the base wrapper which also picks up calls to jest.('../' or '@kbn/', ...) as "import statements" - * @param {CallExpression} node - */ - baseWrapper.CallExpression = (node: TSESTree.CallExpression) => { - const { callee } = node; - // is this call expression a represenation of an obj.method() call? - if (callee.type === AST_NODE_TYPES.MemberExpression) { - const { object } = callee; - - // is the object being called named "jest"? - if (object.type === AST_NODE_TYPES.Identifier && object.name === 'jest') { - const [path] = node.arguments; - - // is the first argument to the method a string which starts with '../' or '@kbn/'? - if ( - path && - path.type === AST_NODE_TYPES.Literal && - typeof path.value === 'string' && - (path.value.startsWith('../') || path.value.startsWith('@kbn/')) - ) { - // call our visitor and assume this node represents a call to a jest mocking function and validate the relative path - visitor(path.value, node); - } + ExportNamedDeclaration(node: TSESTree.ExportNamedDeclaration | T.ExportNamedDeclaration) { + passSourceAsString(node.source, 'esm', fn); + }, + ExportAllDeclaration(node: TSESTree.ExportAllDeclaration | T.ExportAllDeclaration) { + passSourceAsString(node.source, 'esm', fn); + }, + ImportExpression(node: TSESTree.ImportExpression) { + passSourceAsString(node.source, 'esm', fn); + }, + CallExpression({ callee, arguments: args }: TSESTree.CallExpression | T.CallExpression) { + // babel parser used for .js files treats import() calls as CallExpressions with callees of type "Import" + if (T.isImport(callee)) { + passSourceAsString(args[0], 'esm', fn); + return; + } + // is this a `require()` call? + if (isIdent(callee) && callee.name === 'require') { + passSourceAsString(args[0], 'require', fn); return; } - } - return baseCallExpressionVisitor(node); + // is this an `obj.method()` call? + if ( + callee.type === AST_NODE_TYPES.MemberExpression && + isIdent(callee.object) && + isIdent(callee.property) + ) { + const { object: left, property: right } = callee; + const name = `${left.name}.${right.name}`; + + // is it "require.resolve()"? + if (name === 'require.resolve') { + passSourceAsString(args[0], 'require-resolve', fn); + } + + // is it one of jest's mock methods? + if (left.name === 'jest' && JEST_MODULE_METHODS.includes(name)) { + passSourceAsString(args[0], 'jest', fn); + } + } + }, }; - return baseWrapper; + return visitor as Rule.RuleListener; } diff --git a/packages/kbn-eslint-plugin-imports/src/index.ts b/packages/kbn-eslint-plugin-imports/src/index.ts index 756a6f0c19852..5e6fd1f578a4a 100644 --- a/packages/kbn-eslint-plugin-imports/src/index.ts +++ b/packages/kbn-eslint-plugin-imports/src/index.ts @@ -6,15 +6,15 @@ * Side Public License, v 1. */ -export * from './resolve_kibana_import'; -export * from './resolve_result'; - -import { NoUnresolvedImportsRule } from './rules/no_unresolved_imports'; +export * from './get_import_resolver'; +import { NoUnresolvableImportsRule } from './rules/no_unresolvable_imports'; +import { UniformImportsRule } from './rules/uniform_imports'; /** * Custom ESLint rules, add `'@kbn/eslint-plugin-imports'` to your eslint config to use them * @internal */ export const rules = { - no_unresolved_imports: NoUnresolvedImportsRule, + no_unresolvable_imports: NoUnresolvableImportsRule, + uniform_imports: UniformImportsRule, }; diff --git a/packages/kbn-eslint-plugin-imports/src/integration_tests/resolve_kibana_import.test.ts b/packages/kbn-eslint-plugin-imports/src/integration_tests/resolve_kibana_import.test.ts deleted file mode 100644 index 21b1ea7b30409..0000000000000 --- a/packages/kbn-eslint-plugin-imports/src/integration_tests/resolve_kibana_import.test.ts +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import Path from 'path'; - -import { REPO_ROOT } from '@kbn/utils'; -import { createAbsolutePathSerializer } from '@kbn/dev-utils'; -import { resolveKibanaImport } from '../resolve_kibana_import'; - -expect.addSnapshotSerializer(createAbsolutePathSerializer()); - -const plugin = (subPath: string) => Path.resolve(REPO_ROOT, 'src/plugins', subPath); -const xPlugin = (subPath: string) => Path.resolve(REPO_ROOT, 'x-pack/plugins', subPath); -const pkg = (subPath: string) => Path.resolve(REPO_ROOT, 'packages', subPath); - -describe('standard import formats', () => { - it('resolves requests to src/', () => { - expect(resolveKibanaImport('src/core/public', plugin('discovery/public/components/foo'))) - .toMatchInlineSnapshot(` - Object { - "absolute": /src/core/public/index.ts, - "type": "file", - } - `); - expect(resolveKibanaImport('src/core/server', xPlugin('spaces/server/routes'))) - .toMatchInlineSnapshot(` - Object { - "absolute": /src/core/server/index.ts, - "type": "file", - } - `); - expect(resolveKibanaImport('src/core/utils', pkg('kbn-dev-utils/lib'))).toMatchInlineSnapshot(` - Object { - "absolute": /src/core/utils/index.ts, - "type": "file", - } - `); - }); - - it('resolves relative paths too', () => { - expect(resolveKibanaImport('../../../../core/public', plugin('foo/bar/baz'))) - .toMatchInlineSnapshot(` - Object { - "absolute": /src/core/public/index.ts, - "type": "file", - } - `); - }); - - it('resolves @kbn/ imports', () => { - expect(resolveKibanaImport('@kbn/std', pkg('kbn-dev-utils/src'))).toMatchInlineSnapshot(` - Object { - "absolute": /node_modules/@kbn/std/target_node/index.js, - "nodeModule": "@kbn/std", - "type": "file", - } - `); - }); - - it('resolves @elastic/ imports', () => { - expect(resolveKibanaImport('@elastic/eui', pkg('kbn-dev-utils/src'))).toMatchInlineSnapshot(` - Object { - "absolute": /node_modules/@elastic/eui/lib/index.js, - "nodeModule": "@elastic/eui", - "type": "file", - } - `); - }); - - it('resolves normal node module imports', () => { - expect(resolveKibanaImport('lodash', pkg('kbn-dev-utils/src'))).toMatchInlineSnapshot(` - Object { - "absolute": /node_modules/lodash/lodash.js, - "nodeModule": "lodash", - "type": "file", - } - `); - - expect(resolveKibanaImport('globby', pkg('kbn-dev-utils/src'))).toMatchInlineSnapshot(` - Object { - "absolute": /node_modules/globby/index.js, - "nodeModule": "globby", - "type": "file", - } - `); - }); - - it('returns null when the import cannot be resolved', () => { - expect(resolveKibanaImport('../../../../invalid', plugin('foo/bar'))).toMatchInlineSnapshot( - `null` - ); - expect(resolveKibanaImport('src/invalid', plugin('foo/bar'))).toMatchInlineSnapshot(`null`); - expect(resolveKibanaImport('kibana/invalid', plugin('foo/bar'))).toMatchInlineSnapshot(`null`); - expect(resolveKibanaImport('@kbn/invalid', plugin('foo/bar'))).toMatchInlineSnapshot(`null`); - }); - - it('returns ignore results for known unresolvable but okay import statements', () => { - expect(resolveKibanaImport('../../grammar/built_grammar.js', plugin('foo/bar'))) - .toMatchInlineSnapshot(` - Object { - "type": "ignore", - } - `); - - expect(resolveKibanaImport('kibana-buildkite-library', pkg('kbn-foo/src'))) - .toMatchInlineSnapshot(` - Object { - "type": "ignore", - } - `); - - expect(resolveKibanaImport('core_styles', pkg('kbn-foo/src'))).toMatchInlineSnapshot(` - Object { - "type": "ignore", - } - `); - - expect(resolveKibanaImport('core_app_image_assets', pkg('kbn-foo/src'))).toMatchInlineSnapshot(` - Object { - "type": "ignore", - } - `); - - expect(resolveKibanaImport('ace/lib/dom', pkg('kbn-foo/src'))).toMatchInlineSnapshot(` - Object { - "type": "ignore", - } - `); - - expect(resolveKibanaImport('@elastic/eui/src/components/', pkg('kbn-foo/src'))) - .toMatchInlineSnapshot(` - Object { - "type": "ignore", - } - `); - - expect(resolveKibanaImport('@elastic/eui/src/services/', pkg('kbn-foo/src'))) - .toMatchInlineSnapshot(` - Object { - "type": "ignore", - } - `); - }); -}); diff --git a/packages/kbn-eslint-plugin-imports/src/resolve_kibana_import.ts b/packages/kbn-eslint-plugin-imports/src/resolve_kibana_import.ts deleted file mode 100644 index 00ab3e0cdcf82..0000000000000 --- a/packages/kbn-eslint-plugin-imports/src/resolve_kibana_import.ts +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import Fs from 'fs'; -import Path from 'path'; - -import Resolve from 'resolve'; -import { REPO_ROOT } from '@kbn/utils'; - -import { isDirectory, isFile } from './helpers/fs'; -import { ResolveResult } from './resolve_result'; - -const NODE_MODULE_SEG = Path.sep + 'node_modules' + Path.sep; - -function packageFilter(pkg: Record) { - if (!pkg.main && pkg.types) { - // for the purpose of resolving files, a "types" file is adequate - return { - ...pkg, - main: pkg.types, - }; - } - - return pkg; -} - -function adaptReq(req: string, dirname: string): string | undefined { - // transform webpack loader requests and focus on the actual file selected - if (req.startsWith('!!')) { - return req.split('!').pop()?.split('?').shift(); - } - - // handle typescript aliases - if (req === 'kibana/public') { - return adaptReq('src/core/public', dirname); - } - - if (req === 'kibana/server') { - return adaptReq('src/core/server', dirname); - } - - // turn root-relative paths into relative paths - if ( - req.startsWith('src/') || - req.startsWith('x-pack/') || - req.startsWith('examples/') || - req.startsWith('test/') - ) { - const absolute = Path.resolve(REPO_ROOT, req); - return `./${Path.relative(dirname, absolute)}`; - } -} - -function shouldResolve(req: string) { - // this library is only installed on CI and never resolvable - if (req === 'kibana-buildkite-library') { - return; - } - - // these are special webpack-aliases only used in storybooks, ignore them - if (req === 'core_styles' || req === 'core_app_image_assets') { - return; - } - - // ignore amd require done by ace syntax plugin - if (req === 'ace/lib/dom') { - return; - } - - // ignore requests to grammar/built_grammar.js files or built kbn-monaco workers, these are built by bazel and never resolvable - if ( - req.endsWith('grammar/built_grammar.js') || - (req.includes('/target_workers/') && req.endsWith('.editor.worker.js')) - ) { - return; - } - - // typescript validates these imports fine and they're purely virtual thanks to ambient type definitions in @elastic/eui so /shrug - if ( - req.startsWith('@elastic/eui/src/components/') || - req.startsWith('@elastic/eui/src/services/') - ) { - return; - } - - return true; -} - -function tryNodeResolve(req: string, dirname: string): ResolveResult | null { - try { - const path = Resolve.sync(req, { - basedir: dirname, - extensions: ['.js', '.json', '.ts', '.tsx', '.d.ts'], - isDirectory, - isFile, - packageFilter, - }); - - if (path.includes(NODE_MODULE_SEG)) { - const modulePath = path.split(NODE_MODULE_SEG).pop()!.split(Path.sep); - const moduleId = modulePath[0].startsWith('@') - ? `${modulePath[0]}/${modulePath[1]}` - : modulePath[0]; - return { - type: 'file', - absolute: path, - nodeModule: moduleId, - }; - } - - return { - type: 'file', - absolute: path.includes('node_modules') ? Fs.readlinkSync(path) : path, - }; - } catch (error) { - if (error && error.code === 'MODULE_NOT_FOUND') { - return null; - } - - throw error; - } -} - -function tryTypesResolve(req: string, dirname: string): ResolveResult | null { - const parts = req.split('/'); - const nmParts = parts[0].startsWith('@') ? [parts[0].slice(1), parts[1]] : [parts[0]]; - const typesReq = `@types/${nmParts.join('__')}`; - const result = tryNodeResolve(typesReq, dirname); - - if (result) { - return { - type: '@types', - module: typesReq, - }; - } - - return null; -} - -/** - * Resolve an import request. All import requests in the repository should return a result, if they don't it's a bug - * which should be caught by the `@kbn/import/no_unresolved` rule, which should never be disabled. If you need help - * adding support for an import style please reach out to operations. - * - * @param req Text from an import/require, like `../../src/core/public` or `@kbn/std` - * @param dirname The directory of the file where the req was found - */ -export function resolveKibanaImport(req: string, dirname: string): ResolveResult | null { - req = adaptReq(req, dirname) ?? req; - - if (!shouldResolve(req)) { - return { type: 'ignore' }; - } - - return tryNodeResolve(req, dirname) ?? tryTypesResolve(req, dirname); -} diff --git a/packages/kbn-eslint-plugin-imports/src/rules/no_unresolved_imports.ts b/packages/kbn-eslint-plugin-imports/src/rules/no_unresolvable_imports.ts similarity index 72% rename from packages/kbn-eslint-plugin-imports/src/rules/no_unresolved_imports.ts rename to packages/kbn-eslint-plugin-imports/src/rules/no_unresolvable_imports.ts index 1e0b8173ab583..e9ff3e59506f6 100644 --- a/packages/kbn-eslint-plugin-imports/src/rules/no_unresolved_imports.ts +++ b/packages/kbn-eslint-plugin-imports/src/rules/no_unresolvable_imports.ts @@ -9,11 +9,14 @@ import Path from 'path'; import { Rule } from 'eslint'; -import { resolveKibanaImport } from '../resolve_kibana_import'; +import { report } from '../helpers/report'; +import { getImportResolver } from '../get_import_resolver'; import { visitAllImportStatements } from '../helpers/visit_all_import_statements'; -export const NoUnresolvedImportsRule: Rule.RuleModule = { +export const NoUnresolvableImportsRule: Rule.RuleModule = { create(context) { + const resolver = getImportResolver(context); + const sourceFilename = context.getPhysicalFilename ? context.getPhysicalFilename() : context.getFilename(); @@ -23,9 +26,9 @@ export const NoUnresolvedImportsRule: Rule.RuleModule = { } return visitAllImportStatements((req, importer) => { - if (!resolveKibanaImport(req, Path.dirname(sourceFilename))) { - context.report({ - node: importer as any, + if (req !== null && !resolver.resolve(req, Path.dirname(sourceFilename))) { + report(context, { + node: importer, message: `Unable to resolve import [${req}]`, }); } diff --git a/packages/kbn-eslint-plugin-imports/src/rules/uniform_imports.ts b/packages/kbn-eslint-plugin-imports/src/rules/uniform_imports.ts new file mode 100644 index 0000000000000..5239f68b7749e --- /dev/null +++ b/packages/kbn-eslint-plugin-imports/src/rules/uniform_imports.ts @@ -0,0 +1,120 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import Path from 'path'; + +import Eslint from 'eslint'; +import { REPO_ROOT } from '@kbn/utils'; +import { getRelativeImportReq, getPackageRelativeImportReq } from '@kbn/import-resolver'; + +import { report } from '../helpers/report'; +import { visitAllImportStatements } from '../helpers/visit_all_import_statements'; +import { getImportResolver } from '../get_import_resolver'; + +// TODO: get rid of all the special cases in here by moving more things to packages + +const SETUP_NODE_ENV_DIR = Path.resolve(REPO_ROOT, 'src/setup_node_env'); +const PKGJSON_PATH = Path.resolve(REPO_ROOT, 'package.json'); +const XPACK_PKGJSON_PATH = Path.resolve(REPO_ROOT, 'x-pack/package.json'); +const KBN_PM_SCRIPT = Path.resolve(REPO_ROOT, 'packages/kbn-pm/dist/index.js'); + +export const UniformImportsRule: Eslint.Rule.RuleModule = { + meta: { + fixable: 'code', + }, + + create(context) { + const resolver = getImportResolver(context); + const sourceFilename = context.getPhysicalFilename + ? context.getPhysicalFilename() + : context.getFilename(); + + const sourceDirname = Path.dirname(sourceFilename); + + const ownPackageId = resolver.getPackageIdForPath(sourceFilename); + + return visitAllImportStatements((req, importer, type) => { + if (!req) { + return; + } + + const result = resolver.resolve(req, sourceDirname); + if (result?.type !== 'file' || result.nodeModule) { + return; + } + + const { absolute } = result; + // don't mess with imports to the kbn/pm script for now + if (absolute === KBN_PM_SCRIPT) { + return; + } + + const packageId = resolver.getPackageIdForPath(absolute); + if (ownPackageId && !packageId) { + // special cases, files that aren't in packages but packages are allowed to import them + if ( + absolute === PKGJSON_PATH || + absolute === XPACK_PKGJSON_PATH || + absolute.startsWith(SETUP_NODE_ENV_DIR) + ) { + return; + } + + if (resolver.isBazelPackage(ownPackageId)) { + report(context, { + node: importer, + message: `Package [${ownPackageId}] can only import other packages`, + }); + return; + } + } + + if (packageId === ownPackageId || !packageId) { + const correct = getRelativeImportReq({ + ...result, + original: req, + dirname: sourceDirname, + type, + }); + + if (req !== correct) { + report(context, { + node: importer, + message: `Use import request [${correct}]`, + correctImport: correct, + }); + } + return; + } + + const packageDir = resolver.getAbsolutePackageDir(packageId); + if (!packageDir) { + report(context, { + node: importer, + message: `Unable to determine location of package [${packageId}]`, + }); + return; + } + + const correct = getPackageRelativeImportReq({ + ...result, + packageDir, + packageId, + type, + }); + if (req !== correct) { + report(context, { + node: importer, + message: `Use import request [${correct}]`, + correctImport: correct, + }); + return; + } + }); + }, +}; diff --git a/packages/kbn-find-used-node-modules/BUILD.bazel b/packages/kbn-find-used-node-modules/BUILD.bazel new file mode 100644 index 0000000000000..61dc2c7703217 --- /dev/null +++ b/packages/kbn-find-used-node-modules/BUILD.bazel @@ -0,0 +1,122 @@ +load("@npm//@bazel/typescript:index.bzl", "ts_config") +load("@build_bazel_rules_nodejs//:index.bzl", "js_library") +load("//src/dev/bazel:index.bzl", "jsts_transpiler", "pkg_npm", "pkg_npm_types", "ts_project") + +PKG_DIRNAME = "kbn-find-used-node-modules" +PKG_REQUIRE_NAME = "@kbn/find-used-node-modules" + +SOURCE_FILES = glob( + [ + "src/**/*.ts", + ], + exclude = [ + "**/*.test.*", + ], +) + +SRCS = SOURCE_FILES + +filegroup( + name = "srcs", + srcs = SRCS, +) + +NPM_MODULE_EXTRA_FILES = [ + "package.json", +] + +# In this array place runtime dependencies, including other packages and NPM packages +# which must be available for this code to run. +# +# To reference other packages use: +# "//repo/relative/path/to/package" +# eg. "//packages/kbn-utils" +# +# To reference a NPM package use: +# "@npm//name-of-package" +# eg. "@npm//lodash" +RUNTIME_DEPS = [ + "//packages/kbn-babel-preset", + "@npm//@babel/core", + "@npm//@babel/types", + "@npm//@babel/traverse", +] + +# In this array place dependencies necessary to build the types, which will include the +# :npm_module_types target of other packages and packages from NPM, including @types/* +# packages. +# +# To reference the types for another package use: +# "//repo/relative/path/to/package:npm_module_types" +# eg. "//packages/kbn-utils:npm_module_types" +# +# References to NPM packages work the same as RUNTIME_DEPS +TYPES_DEPS = [ + "//packages/kbn-import-resolver:npm_module_types", + "@npm//@types/node", + "@npm//@types/jest", + "@npm//@types/babel__core", + "@npm//@babel/traverse", + "@npm//@babel/types", +] + +jsts_transpiler( + name = "target_node", + srcs = SRCS, + build_pkg_name = package_name(), +) + +ts_config( + name = "tsconfig", + src = "tsconfig.json", + deps = [ + "//:tsconfig.base.json", + "//:tsconfig.bazel.json", + ], +) + +ts_project( + name = "tsc_types", + args = ['--pretty'], + srcs = SRCS, + deps = TYPES_DEPS, + declaration = True, + emit_declaration_only = True, + out_dir = "target_types", + root_dir = "src", + tsconfig = ":tsconfig", +) + +js_library( + name = PKG_DIRNAME, + srcs = NPM_MODULE_EXTRA_FILES, + deps = RUNTIME_DEPS + [":target_node"], + package_name = PKG_REQUIRE_NAME, + visibility = ["//visibility:public"], +) + +pkg_npm( + name = "npm_module", + deps = [":" + PKG_DIRNAME], +) + +filegroup( + name = "build", + srcs = [":npm_module"], + visibility = ["//visibility:public"], +) + +pkg_npm_types( + name = "npm_module_types", + srcs = SRCS, + deps = [":tsc_types"], + package_name = PKG_REQUIRE_NAME, + tsconfig = ":tsconfig", + visibility = ["//visibility:public"], +) + +filegroup( + name = "build_types", + srcs = [":npm_module_types"], + visibility = ["//visibility:public"], +) diff --git a/packages/kbn-find-used-node-modules/README.md b/packages/kbn-find-used-node-modules/README.md new file mode 100644 index 0000000000000..3480448a1f86a --- /dev/null +++ b/packages/kbn-find-used-node-modules/README.md @@ -0,0 +1,7 @@ +# @kbn/find-used-node-modules + +Simple abstraction over the `@babel/parser` and the `@babel/traverse` to find the node_modules used by a list of files. + +## `findUsedNodeModules(resolver, entryPaths): string[]` + +Pass an `ImportResolver` instance from `@kbn/import-resolver` and a list of absolute paths to JS files to get the list of `node_modules` used by those files and the files the import. \ No newline at end of file diff --git a/packages/kbn-babel-code-parser/jest.config.js b/packages/kbn-find-used-node-modules/jest.config.js similarity index 81% rename from packages/kbn-babel-code-parser/jest.config.js rename to packages/kbn-find-used-node-modules/jest.config.js index c5242b7dad926..e8cdf1190cb47 100644 --- a/packages/kbn-babel-code-parser/jest.config.js +++ b/packages/kbn-find-used-node-modules/jest.config.js @@ -7,7 +7,7 @@ */ module.exports = { - preset: '@kbn/test', + preset: '@kbn/test/jest_node', rootDir: '../..', - roots: ['/packages/kbn-babel-code-parser'], + roots: ['/packages/kbn-find-used-node-modules'], }; diff --git a/packages/kbn-find-used-node-modules/package.json b/packages/kbn-find-used-node-modules/package.json new file mode 100644 index 0000000000000..c5da8d1f898c1 --- /dev/null +++ b/packages/kbn-find-used-node-modules/package.json @@ -0,0 +1,10 @@ +{ + "name": "@kbn/find-used-node-modules", + "private": true, + "version": "1.0.0", + "main": "./target_node/index.js", + "license": "SSPL-1.0 OR Elastic License 2.0", + "kibana": { + "devOnly": true + } +} diff --git a/packages/kbn-find-used-node-modules/src/find_used_node_modules.test.ts b/packages/kbn-find-used-node-modules/src/find_used_node_modules.test.ts new file mode 100644 index 0000000000000..a5175c8734183 --- /dev/null +++ b/packages/kbn-find-used-node-modules/src/find_used_node_modules.test.ts @@ -0,0 +1,186 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { findUsedNodeModules } from './find_used_node_modules'; +import { ImportResolver } from '@kbn/import-resolver'; + +jest.mock('./fs'); + +const FILES: Record = { + '/foo.js': ` + require('./bar.js') + `, + '/bar.js': ` + require('./box') + `, + '/box.js': ` + require('foo') + `, +}; + +class MockResolver extends ImportResolver { + constructor() { + super('/', new Map(), new Map()); + } + + isBazelPackage = jest.fn(); + resolve = jest.fn(); +} + +const RESOLVER = new MockResolver(); + +beforeEach(() => { + jest.resetAllMocks(); + jest.requireMock('./fs').readFile.mockImplementation((path: string) => { + if (Object.hasOwn(FILES, path)) { + return FILES[path]; + } + + const error: any = new Error(`ENOENT, missing file [${path}]`); + error.code = 'ENOENT'; + throw error; + }); +}); + +describe('findUsedNodeModules()', () => { + it('excludes built-in modules', async () => { + RESOLVER.resolve.mockImplementation(() => ({ + type: 'built-in', + })); + + const results = await findUsedNodeModules({ + entryPaths: ['/foo.js'], + resolver: RESOLVER, + findUsedPeers: false, + }); + + expect(RESOLVER.resolve).toHaveBeenCalledTimes(1); + expect(results).toEqual([]); + }); + + it('returns node_modules found in the source file', async () => { + RESOLVER.resolve.mockImplementation((req) => { + if (req === './bar.js') { + return { + type: 'file', + nodeModule: '@foo/bar', + absolute: '/bar.js', + }; + } + + throw new Error('unexpected request'); + }); + + const results = await findUsedNodeModules({ + entryPaths: ['/foo.js'], + resolver: RESOLVER, + findUsedPeers: false, + }); + expect(RESOLVER.resolve).toHaveBeenCalledTimes(1); + expect(results).toEqual(['@foo/bar']); + }); + + it('returns node_modules found in referenced files', async () => { + RESOLVER.resolve.mockImplementation((req) => { + if (req === './bar.js') { + return { + type: 'file', + absolute: '/bar.js', + }; + } + + if (req === './box') { + return { + type: 'file', + nodeModule: '@foo/box', + absolute: '/box.js', + }; + } + + throw new Error('unexpected request'); + }); + + const results = await findUsedNodeModules({ + entryPaths: ['/foo.js'], + resolver: RESOLVER, + findUsedPeers: false, + }); + expect(RESOLVER.resolve).toHaveBeenCalledTimes(2); + expect(results).toEqual(['@foo/box']); + }); + + it('does not traverse node_modules', async () => { + RESOLVER.resolve.mockImplementation((req) => { + if (req === './bar.js') { + return { + type: 'file', + absolute: '/bar.js', + }; + } + + if (req === './box') { + return { + type: 'file', + nodeModule: '@foo/box', + absolute: '/box.js', + }; + } + + throw new Error('unexpected request'); + }); + + const results = await findUsedNodeModules({ + entryPaths: ['/foo.js'], + resolver: RESOLVER, + findUsedPeers: false, + }); + expect(RESOLVER.resolve).toHaveBeenCalledTimes(2); + expect(results).toEqual(['@foo/box']); + }); + + it('does traverse node_modules which are also bazel packages', async () => { + RESOLVER.resolve.mockImplementation((req) => { + if (req === './bar.js') { + return { + type: 'file', + absolute: '/bar.js', + }; + } + + if (req === './box') { + return { + type: 'file', + nodeModule: '@foo/box', + absolute: '/box.js', + }; + } + + if (req === 'foo') { + return { + type: 'file', + nodeModule: '@foo/core', + absolute: '/non-existant', + }; + } + + throw new Error('unexpected request'); + }); + + RESOLVER.isBazelPackage.mockImplementation((pkgId) => { + return pkgId === '@foo/box'; + }); + + const results = await findUsedNodeModules({ + entryPaths: ['/foo.js'], + resolver: RESOLVER, + findUsedPeers: false, + }); + expect(RESOLVER.resolve).toHaveBeenCalledTimes(3); + expect(results).toEqual(['@foo/box', '@foo/core']); + }); +}); diff --git a/packages/kbn-find-used-node-modules/src/find_used_node_modules.ts b/packages/kbn-find-used-node-modules/src/find_used_node_modules.ts new file mode 100644 index 0000000000000..d02cc084e8901 --- /dev/null +++ b/packages/kbn-find-used-node-modules/src/find_used_node_modules.ts @@ -0,0 +1,138 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import Path from 'path'; + +import { asyncForEachWithLimit } from '@kbn/std'; +import type { ImportResolver } from '@kbn/import-resolver'; + +import { readFile, readFileSync } from './fs'; +import { getImportRequests } from './get_import_requests'; + +function isObj(v: any): v is Record { + return typeof v === 'object' && v !== null; +} + +function getPeerDeps(thisNodeModule: string) { + const pkgPath = require.resolve(`${thisNodeModule}/package.json`); + const pkg = JSON.parse(readFileSync(pkgPath)); + + if (isObj(pkg) && isObj(pkg.peerDependencies)) { + return Object.keys(pkg.peerDependencies); + } else { + return []; + } +} + +interface Options { + resolver: ImportResolver; + entryPaths: string[]; + findUsedPeers: boolean; + // if we are finding used modules in a node_module, this must be the name of the node_module + // we should treat as "this module" rather than "another node module" + thisNodeModule?: string; +} + +/** + * Parse a list of entry paths and find the node_modules which are required by them. If the + * entry path requires/imports a non-node_module then that file is scanned too, deeply, until + * all referenced files are scanned. + * + * Optionally, we can find the used peers of the used node_modules. This will keep track of all + * the paths we use to enter a node_module and then traverse from those points, finding the + * used modules and comparing those to the `peerDependencies` listed in the node_module's package.json + * file. If a used dependeny is in the `peerDependencies` and is used by the node_module it will + * be included in the results. + * + * This was implemented mostly for `@emotion/react` which is used by @elastic/eui but only listed + * as a peerDependency. If we didn't keep it in the Kibana package.json then the package would not + * be installed and cause an error on startup because `@emotion/react` can't be found. We used to + * solve this by scanning the node_modules directory for all the packages which are used but that + * was much slower and lead to extra entries in package.json. + */ +export async function findUsedNodeModules(options: Options) { + const queue = new Set(options.entryPaths); + const results = new Set(); + + const entryPathsIntoNodeModules = new Map>(); + + for (const path of queue) { + if (Path.extname(path) !== '.js') { + continue; + } + + const dirname = Path.dirname(path); + const code = await readFile(path); + const reqs = getImportRequests(code); + + for (const req of reqs) { + // resolve the request to it's actual file on dist + const result = options.resolver.resolve(req, dirname); + + // ignore non-file resolution results, these represent files which aren't on + // the file-system yet (like during the build) built-ins, explicitily ignored + // files, and @types only imports + if (result?.type !== 'file') { + continue; + } + + // if the result points to a node_module (or another node_module)... + if (result.nodeModule && result.nodeModule !== options.thisNodeModule) { + // add it to the results + results.add(result.nodeModule); + + // record this absolute path as an entry path into the node module from our entries, if we + // need to scan this node_module for used deps we need to know how we access it. + const nmEntries = entryPathsIntoNodeModules.get(result.nodeModule); + if (!nmEntries) { + entryPathsIntoNodeModules.set(result.nodeModule, new Set([result.absolute])); + } else { + nmEntries.add(result.absolute); + } + } + + // no need to scan node_modules unless they're bazel packages + if ( + !result.nodeModule || + result.nodeModule === options.thisNodeModule || + options.resolver.isBazelPackage(result.nodeModule) + ) { + queue.add(result.absolute); + } + } + } + + if (options.findUsedPeers) { + await asyncForEachWithLimit(results, 10, async (dep) => { + const entryPaths = entryPathsIntoNodeModules.get(dep); + if (!entryPaths?.size) { + return; + } + + const peerDeps = getPeerDeps(dep); + if (!peerDeps.length) { + return; + } + + const usedInside = await findUsedNodeModules({ + resolver: options.resolver, + entryPaths: Array.from(entryPaths), + findUsedPeers: false, + thisNodeModule: dep, + }); + + for (const peer of peerDeps) { + if (usedInside.includes(peer)) { + results.add(peer); + } + } + }); + } + + return Array.from(results).sort((a, b) => a.localeCompare(b)); +} diff --git a/packages/kbn-pm/src/utils/sort_package_json.ts b/packages/kbn-find-used-node-modules/src/fs.ts similarity index 51% rename from packages/kbn-pm/src/utils/sort_package_json.ts rename to packages/kbn-find-used-node-modules/src/fs.ts index 84a1ed6d80960..e0e9c9690803c 100644 --- a/packages/kbn-pm/src/utils/sort_package_json.ts +++ b/packages/kbn-find-used-node-modules/src/fs.ts @@ -6,11 +6,13 @@ * Side Public License, v 1. */ -import Fs from 'fs/promises'; -import { sortPackageJson as sort } from '@kbn/dev-utils/sort_package_json'; -import { Kibana } from './kibana'; +import Fs from 'fs'; +import Fsp from 'fs/promises'; -export async function sortPackageJson(kbn: Kibana) { - const packageJsonPath = kbn.getAbsolute('package.json'); - await Fs.writeFile(packageJsonPath, sort(await Fs.readFile(packageJsonPath, 'utf-8'))); +export function readFileSync(path: string) { + return Fs.readFileSync(path, 'utf8'); +} + +export function readFile(path: string) { + return Fsp.readFile(path, 'utf8'); } diff --git a/packages/kbn-find-used-node-modules/src/get_import_requests.test.ts b/packages/kbn-find-used-node-modules/src/get_import_requests.test.ts new file mode 100644 index 0000000000000..ebfc7572cf1e7 --- /dev/null +++ b/packages/kbn-find-used-node-modules/src/get_import_requests.test.ts @@ -0,0 +1,64 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { getImportRequests } from './get_import_requests'; + +describe('getImportRequests()', () => { + it('should get requests from `require`', () => { + const rawCode = `/*foo*/require('dep1'); const bar = 1;`; + const foundDeps = getImportRequests(rawCode); + expect(foundDeps).toMatchInlineSnapshot(` + Array [ + "dep1", + ] + `); + }); + + it('should get requests from `require.resolve`', () => { + const rawCode = `/*foo*/require.resolve('dep2'); const bar = 1;`; + const foundDeps = getImportRequests(rawCode); + expect(foundDeps).toMatchInlineSnapshot(` + Array [ + "dep2", + ] + `); + }); + + it('should get requests from `import`', () => { + const rawCode = `/*foo*/import dep1 from 'dep1'; import dep2 from 'dep2';const bar = 1;`; + const foundDeps = getImportRequests(rawCode); + expect(foundDeps).toMatchInlineSnapshot(` + Array [ + "dep1", + "dep2", + ] + `); + }); + + it('should get requests from `export from`', () => { + const rawCode = `/*foo*/export dep1 from 'dep1'; import dep2 from 'dep2';const bar = 1;`; + const foundDeps = getImportRequests(rawCode); + expect(foundDeps).toMatchInlineSnapshot(` + Array [ + "dep1", + "dep2", + ] + `); + }); + + it('should get requests from `export * from`', () => { + const rawCode = `/*foo*/export * from 'dep1'; export dep2 from 'dep2';const bar = 1;`; + const foundDeps = getImportRequests(rawCode); + expect(foundDeps).toMatchInlineSnapshot(` + Array [ + "dep1", + "dep2", + ] + `); + }); +}); diff --git a/packages/kbn-find-used-node-modules/src/get_import_requests.ts b/packages/kbn-find-used-node-modules/src/get_import_requests.ts new file mode 100644 index 0000000000000..03de25f7fb92a --- /dev/null +++ b/packages/kbn-find-used-node-modules/src/get_import_requests.ts @@ -0,0 +1,30 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import * as parser from '@babel/parser'; +import traverse from '@babel/traverse'; +// @ts-expect-error Not available with types +import babelParserOptions from '@kbn/babel-preset/common_babel_parser_options'; + +import { importVisitor } from './import_visitor'; + +/** + * Parse the code and return an array of all the import requests in that file + */ +export function getImportRequests(code: string) { + const importRequests: string[] = []; + + // Parse and get the code AST + const ast = parser.parse(code, babelParserOptions); + + // Loop through the code AST with + // the defined visitors + traverse(ast, importVisitor(importRequests)); + + return importRequests; +} diff --git a/packages/kbn-find-used-node-modules/src/import_visitor.ts b/packages/kbn-find-used-node-modules/src/import_visitor.ts new file mode 100644 index 0000000000000..ac7e09cd726d0 --- /dev/null +++ b/packages/kbn-find-used-node-modules/src/import_visitor.ts @@ -0,0 +1,82 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import * as T from '@babel/types'; +import type { Visitor } from '@babel/core'; + +/** + * @notice + * + * This product has relied on ASTExplorer that is licensed under MIT. + */ + +// AST check for require expressions +const isRequire = ({ callee }: T.CallExpression) => + T.isIdentifier(callee) && callee.name === 'require'; + +// AST check for require.resolve expressions +const isRequireResolve = ({ callee }: T.CallExpression) => + T.isMemberExpression(callee) && + T.isIdentifier(callee.object) && + callee.object.name === 'require' && + T.isIdentifier(callee.property) && + callee.property.name === 'resolve'; + +/** + * Create a Babel AST visitor that will write import requests into the passed array + */ +export function importVisitor(importRequests: string[]): Visitor { + // This was built with help on an ast explorer and some ESTree docs + // like the babel parser ast spec and the main docs for the Esprima + // which is a complete and useful docs for the ESTree spec. + // + // https://astexplorer.net + // https://github.com/babel/babel/blob/master/packages/babel-parser/ast/spec.md + // https://esprima.readthedocs.io/en/latest/syntax-tree-format.html + // https://github.com/estree/estree + + // Visitors to traverse and find dependencies + return { + // raw values on require + require.resolve + CallExpression: ({ node }) => { + if (isRequire(node) || isRequireResolve(node)) { + const nodeArguments = node.arguments; + const reqArg = Array.isArray(nodeArguments) ? nodeArguments.shift() : null; + + if (!reqArg) { + return; + } + + if (reqArg.type === 'StringLiteral') { + importRequests.push(reqArg.value); + } + } + }, + + // raw values on import + ImportDeclaration: ({ node }) => { + // Get string values from import expressions + const importSource = node.source; + importRequests.push(importSource.value); + }, + + // raw values on export from + ExportNamedDeclaration: ({ node }) => { + // Get string values from export from expressions + if (node.source) { + importRequests.push(node.source.value); + } + }, + + // raw values on export * from + ExportAllDeclaration: ({ node }) => { + const exportAllFromSource = node.source; + importRequests.push(exportAllFromSource.value); + }, + }; +} diff --git a/packages/kbn-babel-code-parser/src/index.js b/packages/kbn-find-used-node-modules/src/index.ts similarity index 63% rename from packages/kbn-babel-code-parser/src/index.js rename to packages/kbn-find-used-node-modules/src/index.ts index cc03bc75a4b4e..52e2935b5f0e0 100644 --- a/packages/kbn-babel-code-parser/src/index.js +++ b/packages/kbn-find-used-node-modules/src/index.ts @@ -6,6 +6,4 @@ * Side Public License, v 1. */ -export { dependenciesParseStrategy } from './strategies'; -export { dependenciesVisitorsGenerator } from './visitors'; -export { parseSingleFile, parseSingleFileSync, parseEntries } from './code_parser'; +export { findUsedNodeModules } from './find_used_node_modules'; diff --git a/packages/kbn-find-used-node-modules/tsconfig.json b/packages/kbn-find-used-node-modules/tsconfig.json new file mode 100644 index 0000000000000..a8cfc2cceb08b --- /dev/null +++ b/packages/kbn-find-used-node-modules/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../tsconfig.bazel.json", + "compilerOptions": { + "declaration": true, + "emitDeclarationOnly": true, + "outDir": "target_types", + "rootDir": "src", + "stripInternal": false, + "types": [ + "jest", + "node" + ] + }, + "include": [ + "src/**/*" + ] +} diff --git a/packages/kbn-import-resolver/BUILD.bazel b/packages/kbn-import-resolver/BUILD.bazel new file mode 100644 index 0000000000000..50e91c29d1750 --- /dev/null +++ b/packages/kbn-import-resolver/BUILD.bazel @@ -0,0 +1,124 @@ +load("@npm//@bazel/typescript:index.bzl", "ts_config") +load("@build_bazel_rules_nodejs//:index.bzl", "js_library") +load("//src/dev/bazel:index.bzl", "jsts_transpiler", "pkg_npm", "pkg_npm_types", "ts_project") + +PKG_DIRNAME = "kbn-import-resolver" +PKG_REQUIRE_NAME = "@kbn/import-resolver" + +SOURCE_FILES = glob( + [ + "src/**/*.ts", + ], + exclude = [ + "**/*.test.*", + ], +) + +SRCS = SOURCE_FILES + +filegroup( + name = "srcs", + srcs = SRCS, +) + +NPM_MODULE_EXTRA_FILES = [ + "package.json", +] + +# In this array place runtime dependencies, including other packages and NPM packages +# which must be available for this code to run. +# +# To reference other packages use: +# "//repo/relative/path/to/package" +# eg. "//packages/kbn-utils" +# +# To reference a NPM package use: +# "@npm//name-of-package" +# eg. "@npm//lodash" +RUNTIME_DEPS = [ + "//packages/kbn-bazel-packages", + "//packages/kbn-utils", + "//packages/kbn-synthetic-package-map", + "@npm//resolve", + "@npm//normalize-path", +] + +# In this array place dependencies necessary to build the types, which will include the +# :npm_module_types target of other packages and packages from NPM, including @types/* +# packages. +# +# To reference the types for another package use: +# "//repo/relative/path/to/package:npm_module_types" +# eg. "//packages/kbn-utils:npm_module_types" +# +# References to NPM packages work the same as RUNTIME_DEPS +TYPES_DEPS = [ + "//packages/kbn-bazel-packages:npm_module_types", + "//packages/kbn-utils:npm_module_types", + "//packages/kbn-synthetic-package-map:npm_module_types", + "@npm//@types/node", + "@npm//@types/jest", + "@npm//@types/resolve", + "@npm//@types/normalize-path", +] + +jsts_transpiler( + name = "target_node", + srcs = SRCS, + build_pkg_name = package_name(), +) + +ts_config( + name = "tsconfig", + src = "tsconfig.json", + deps = [ + "//:tsconfig.base.json", + "//:tsconfig.bazel.json", + ], +) + +ts_project( + name = "tsc_types", + args = ['--pretty'], + srcs = SRCS, + deps = TYPES_DEPS, + declaration = True, + emit_declaration_only = True, + out_dir = "target_types", + root_dir = "src", + tsconfig = ":tsconfig", +) + +js_library( + name = PKG_DIRNAME, + srcs = NPM_MODULE_EXTRA_FILES, + deps = RUNTIME_DEPS + [":target_node"], + package_name = PKG_REQUIRE_NAME, + visibility = ["//visibility:public"], +) + +pkg_npm( + name = "npm_module", + deps = [":" + PKG_DIRNAME], +) + +filegroup( + name = "build", + srcs = [":npm_module"], + visibility = ["//visibility:public"], +) + +pkg_npm_types( + name = "npm_module_types", + srcs = SRCS, + deps = [":tsc_types"], + package_name = PKG_REQUIRE_NAME, + tsconfig = ":tsconfig", + visibility = ["//visibility:public"], +) + +filegroup( + name = "build_types", + srcs = [":npm_module_types"], + visibility = ["//visibility:public"], +) diff --git a/packages/kbn-import-resolver/README.md b/packages/kbn-import-resolver/README.md new file mode 100644 index 0000000000000..82760b05f8c4c --- /dev/null +++ b/packages/kbn-import-resolver/README.md @@ -0,0 +1,3 @@ +# @kbn/import-resolver + +Empty package generated by @kbn/generate diff --git a/packages/kbn-import-resolver/jest.integration.config.js b/packages/kbn-import-resolver/jest.integration.config.js new file mode 100644 index 0000000000000..7a593982100b0 --- /dev/null +++ b/packages/kbn-import-resolver/jest.integration.config.js @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +module.exports = { + preset: '@kbn/test/jest_integration_node', + rootDir: '../..', + roots: ['/packages/kbn-import-resolver'], +}; diff --git a/packages/kbn-import-resolver/package.json b/packages/kbn-import-resolver/package.json new file mode 100644 index 0000000000000..d8a6e72792399 --- /dev/null +++ b/packages/kbn-import-resolver/package.json @@ -0,0 +1,10 @@ +{ + "name": "@kbn/import-resolver", + "private": true, + "version": "1.0.0", + "main": "./target_node/index.js", + "license": "SSPL-1.0 OR Elastic License 2.0", + "kibana": { + "devOnly": true + } +} diff --git a/packages/kbn-import-resolver/src/__fixtures__/node_modules/@pkg/box/index.js b/packages/kbn-import-resolver/src/__fixtures__/node_modules/@pkg/box/index.js new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/packages/kbn-import-resolver/src/__fixtures__/node_modules/foo/index.js b/packages/kbn-import-resolver/src/__fixtures__/node_modules/foo/index.js new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/packages/kbn-pm/cli.js b/packages/kbn-import-resolver/src/__fixtures__/packages/box/index.js similarity index 88% rename from packages/kbn-pm/cli.js rename to packages/kbn-import-resolver/src/__fixtures__/packages/box/index.js index 41b533ee87d8b..5c2d5b68ae2e0 100644 --- a/packages/kbn-pm/cli.js +++ b/packages/kbn-import-resolver/src/__fixtures__/packages/box/index.js @@ -5,5 +5,3 @@ * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ - -require('./dist').run(process.argv.slice(2)); diff --git a/packages/kbn-config/src/plugins/index.ts b/packages/kbn-import-resolver/src/__fixtures__/src/bar/bar.js similarity index 84% rename from packages/kbn-config/src/plugins/index.ts rename to packages/kbn-import-resolver/src/__fixtures__/src/bar/bar.js index fdb459b5f412e..5c2d5b68ae2e0 100644 --- a/packages/kbn-config/src/plugins/index.ts +++ b/packages/kbn-import-resolver/src/__fixtures__/src/bar/bar.js @@ -5,5 +5,3 @@ * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ - -export { getPluginSearchPaths } from './plugin_search_paths'; diff --git a/packages/kbn-import-resolver/src/__fixtures__/src/bar/index.js b/packages/kbn-import-resolver/src/__fixtures__/src/bar/index.js new file mode 100644 index 0000000000000..5c2d5b68ae2e0 --- /dev/null +++ b/packages/kbn-import-resolver/src/__fixtures__/src/bar/index.js @@ -0,0 +1,7 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ diff --git a/packages/kbn-import-resolver/src/__fixtures__/src/index.js b/packages/kbn-import-resolver/src/__fixtures__/src/index.js new file mode 100644 index 0000000000000..5c2d5b68ae2e0 --- /dev/null +++ b/packages/kbn-import-resolver/src/__fixtures__/src/index.js @@ -0,0 +1,7 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ diff --git a/packages/kbn-eslint-plugin-imports/src/helpers/fs.ts b/packages/kbn-import-resolver/src/helpers/fs.ts similarity index 55% rename from packages/kbn-eslint-plugin-imports/src/helpers/fs.ts rename to packages/kbn-import-resolver/src/helpers/fs.ts index 98b26bd1336ed..d1897ed9247eb 100644 --- a/packages/kbn-eslint-plugin-imports/src/helpers/fs.ts +++ b/packages/kbn-import-resolver/src/helpers/fs.ts @@ -8,11 +8,7 @@ import Fs from 'fs'; -import { memoize } from './memoize'; - -const runningInEditor = !!process.env.VSCODE_CWD; - -const safeStat = (path: string) => { +export function safeStat(path: string) { try { return Fs.statSync(path); } catch (error) { @@ -22,15 +18,8 @@ const safeStat = (path: string) => { throw error; } -}; - -function _isDirectory(path: string) { - return !!safeStat(path)?.isDirectory(); } -function _isFile(path: string) { - return !!safeStat(path)?.isFile(); +export function readFileSync(path: string) { + return Fs.readFileSync(path, 'utf8'); } - -export const isDirectory = runningInEditor ? _isDirectory : memoize(_isDirectory); -export const isFile = runningInEditor ? _isFile : memoize(_isFile); diff --git a/packages/kbn-import-resolver/src/helpers/import_req.ts b/packages/kbn-import-resolver/src/helpers/import_req.ts new file mode 100644 index 0000000000000..5844f47e880fe --- /dev/null +++ b/packages/kbn-import-resolver/src/helpers/import_req.ts @@ -0,0 +1,100 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import Path from 'path'; + +import normalizePath from 'normalize-path'; + +export type ImportType = 'esm' | 'require' | 'require-resolve' | 'jest'; + +interface WrapOptions { + prefix?: string; + postfix?: string; +} +function wrap(req: string, options: WrapOptions) { + return `${options.prefix ?? ''}${req}${options.postfix ?? ''}`; +} + +const EXT_RE = /\.(jsx?|(d\.)?tsx?)$/; +const INDEX_IN_INDEX_RE = /\/index\/index(\.jsx?|\.d\.tsx?|\.tsx?)$/; +const INCLUDES_FILENAME_RE = /\/.*\..{2,4}$/; + +export function reduceImportRequest(req: string, type: ImportType, original?: string) { + let reduced = req; + + if (type === 'require-resolve' && original && original.match(INCLUDES_FILENAME_RE)) { + // require.resolve() can be a complicated, it's often used in config files and + // sometimes we don't have babel to help resolve .ts to .js, so we try to rely + // on the original request and keep the filename listed if it's in the original + return req; + } + + const indexInIndexMatch = req.match(INDEX_IN_INDEX_RE); + if (indexInIndexMatch) { + if (indexInIndexMatch[1] !== '.ts' && indexInIndexMatch[1] !== '.tsx') { + // this is a very ambiguous request, leave the whole import statement to make it less so + return req; + } + + // this is also a very ambiguous request, but TS complains about leaving .ts or .tsx on a request so strip it + return req.slice(0, -indexInIndexMatch[1].length); + } + + const extMatch = req.match(EXT_RE); + if (extMatch) { + reduced = reduced.slice(0, -extMatch[0].length); + } + + if (reduced === 'index') { + return ''; + } + + if (reduced.endsWith('/index')) { + reduced = reduced.slice(0, -6); + } + + return reduced; +} + +interface RelativeImportReqOptions extends WrapOptions { + dirname: string; + absolute: string; + type: ImportType; + original?: string; +} + +export function getRelativeImportReq(options: RelativeImportReqOptions) { + const relative = normalizePath(Path.relative(options.dirname, options.absolute)); + return wrap( + reduceImportRequest( + relative.startsWith('.') ? relative : `./${relative}`, + options.type, + options.original + ), + options + ); +} + +interface PackageRelativeImportReqOptions extends WrapOptions { + packageDir: string; + packageId: string; + absolute: string; + type: ImportType; +} + +export function getPackageRelativeImportReq(options: PackageRelativeImportReqOptions) { + const relative = normalizePath(Path.relative(options.packageDir, options.absolute)); + + if (!relative) { + return wrap(options.packageId, options); + } + + const subPath = reduceImportRequest(relative, options.type); + + return wrap(subPath ? `${options.packageId}/${subPath}` : options.packageId, options); +} diff --git a/packages/kbn-eslint-plugin-imports/src/helpers/memoize.ts b/packages/kbn-import-resolver/src/helpers/memoize.ts similarity index 100% rename from packages/kbn-eslint-plugin-imports/src/helpers/memoize.ts rename to packages/kbn-import-resolver/src/helpers/memoize.ts diff --git a/packages/kbn-import-resolver/src/import_resolver.ts b/packages/kbn-import-resolver/src/import_resolver.ts new file mode 100644 index 0000000000000..44114ce731e28 --- /dev/null +++ b/packages/kbn-import-resolver/src/import_resolver.ts @@ -0,0 +1,281 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import Path from 'path'; +import Fs from 'fs'; + +import Resolve from 'resolve'; +import { REPO_ROOT } from '@kbn/utils'; +import normalizePath from 'normalize-path'; +import { discoverBazelPackageLocations } from '@kbn/bazel-packages'; +import { readPackageMap, PackageMap } from '@kbn/synthetic-package-map'; + +import { safeStat, readFileSync } from './helpers/fs'; +import { ResolveResult } from './resolve_result'; +import { getRelativeImportReq } from './helpers/import_req'; +import { memoize } from './helpers/memoize'; + +const NODE_MODULE_SEG = Path.sep + 'node_modules' + Path.sep; + +export class ImportResolver { + static create(repoRoot: string) { + const pkgMap = new Map(); + for (const dir of discoverBazelPackageLocations(repoRoot)) { + const pkg = JSON.parse(Fs.readFileSync(Path.resolve(dir, 'package.json'), 'utf8')); + pkgMap.set(pkg.name, normalizePath(Path.relative(repoRoot, dir))); + } + + return new ImportResolver(repoRoot, pkgMap, readPackageMap()); + } + + private safeStat = memoize(safeStat); + + private baseResolveOpts = { + extensions: ['.js', '.json', '.ts', '.tsx', '.d.ts'], + isFile: (path: string) => !!this.safeStat(path)?.isFile(), + isDirectory: (path: string) => !!this.safeStat(path)?.isDirectory(), + readFileSync: memoize(readFileSync), + packageFilter(pkg: Record) { + if (!pkg.main && pkg.types) { + // for the purpose of resolving files, a "types" file is adequate + return { + ...pkg, + main: pkg.types, + }; + } + + return pkg; + }, + }; + + constructor( + /** + * Root directory that all source files for packages are expected to be + * in, also the directory that package maps are resolved against. + */ + private readonly cwd: string, + /** + * Map of actual package names to normalized root-relative directories + * for each package + */ + private readonly pkgMap: PackageMap, + /** + * Map of synthetic package names to normalized root-relative directories + * for each simulated package + */ + private readonly synthPkgMap: PackageMap + ) {} + + getPackageIdForPath(path: string) { + const relative = normalizePath(Path.relative(this.cwd, path)); + if (relative.startsWith('..')) { + throw new Error(`path is outside of cwd [${this.cwd}]`); + } + + for (const [synthPkgId, dir] of this.synthPkgMap) { + if (relative === dir || relative.startsWith(dir + '/')) { + return synthPkgId; + } + } + + for (const [pkgId, dir] of this.pkgMap) { + if (relative === dir || relative.startsWith(dir + '/')) { + return pkgId; + } + } + + return null; + } + + getAbsolutePackageDir(pkgId: string) { + const dir = this.synthPkgMap.get(pkgId) ?? this.pkgMap.get(pkgId); + if (!dir) { + return null; + } + return Path.resolve(this.cwd, dir); + } + + isBazelPackage(pkgId: string) { + return this.pkgMap.has(pkgId); + } + + isSyntheticPackage(pkgId: string) { + return this.synthPkgMap.has(pkgId); + } + + private shouldIgnore(req: string): boolean { + // this library is only installed on CI and never resolvable + if (req === 'kibana-buildkite-library') { + return true; + } + + // these are special webpack-aliases only used in storybooks, ignore them + if (req === 'core_styles' || req === 'core_app_image_assets') { + return true; + } + + // ignore amd require done by ace syntax plugin + if (req === 'ace/lib/dom') { + return true; + } + + // ignore requests to grammar/built_grammar.js files or bazel target dirs, these files are only + // available in the build output and will never resolve in dev. We will validate that people don't + // import these files from outside the package in another rule + if ( + req.endsWith('grammar/built_grammar.js') || + req.includes('/target_workers/') || + req.includes('/target_node/') + ) { + return true; + } + + // typescript validates these imports fine and they're purely virtual thanks to ambient type definitions in @elastic/eui so /shrug + if ( + req.startsWith('@elastic/eui/src/components/') || + req.startsWith('@elastic/eui/src/services/') + ) { + return true; + } + + return false; + } + + private adaptReq(req: string, dirname: string): string | undefined { + // handle typescript aliases + if (req === 'kibana/public') { + return this.adaptReq('src/core/public', dirname); + } + if (req === 'kibana/server') { + return this.adaptReq('src/core/server', dirname); + } + + // turn root-relative paths into relative paths + if ( + req.startsWith('src/') || + req.startsWith('x-pack/') || + req.startsWith('examples/') || + req.startsWith('test/') + ) { + return getRelativeImportReq({ + dirname, + absolute: Path.resolve(REPO_ROOT, req), + type: 'esm', + }); + } + } + + private tryNodeResolve(req: string, dirname: string): ResolveResult | null { + try { + const path = Resolve.sync(req, { + basedir: dirname, + ...this.baseResolveOpts, + }); + + if (!Path.isAbsolute(path)) { + return { + type: 'built-in', + }; + } + + const lastNmSeg = path.lastIndexOf(NODE_MODULE_SEG); + if (lastNmSeg !== -1) { + const segs = path.slice(lastNmSeg + NODE_MODULE_SEG.length).split(Path.sep); + const moduleId = segs[0].startsWith('@') ? `${segs[0]}/${segs[1]}` : segs[0]; + + return { + type: 'file', + absolute: path, + nodeModule: moduleId, + }; + } + + return { + type: 'file', + absolute: path, + }; + } catch (error) { + if (error && error.code === 'MODULE_NOT_FOUND') { + if (req === 'fsevents') { + return { + type: 'optional-and-missing', + }; + } + return null; + } + + throw error; + } + } + + private tryTypesResolve(req: string, dirname: string): ResolveResult | null { + const parts = req.split('/'); + const nmParts = parts[0].startsWith('@') ? [parts[0].slice(1), parts[1]] : [parts[0]]; + const typesReq = `@types/${nmParts.join('__')}`; + const result = this.tryNodeResolve(typesReq, dirname); + + if (result) { + return { + type: '@types', + module: typesReq, + }; + } + + return null; + } + + /** + * Resolve an import request from a file in the given dirname + */ + resolve(req: string, dirname: string): ResolveResult | null { + // transform webpack loader requests and focus on the actual file selected + const lastExI = req.lastIndexOf('!'); + if (lastExI > -1) { + const quesI = req.lastIndexOf('?'); + const prefix = req.slice(0, lastExI + 1); + const postfix = quesI > -1 ? req.slice(quesI) : ''; + const result = this.resolve(req.slice(lastExI + 1, quesI > -1 ? quesI : undefined), dirname); + + if (result?.type !== 'file') { + return result; + } + + return { + ...result, + prefix, + postfix, + }; + } + + if (req[0] !== '.') { + const parts = req.split('/'); + const pkgId = parts[0].startsWith('@') ? `${parts[0]}/${parts[1]}` : `${parts[0]}`; + if (this.synthPkgMap.has(pkgId)) { + const pkgDir = this.getAbsolutePackageDir(pkgId); + if (pkgDir) { + return this.resolve( + getRelativeImportReq({ + absolute: parts.length > 2 ? Path.resolve(pkgDir, ...parts.slice(2)) : pkgDir, + dirname, + type: 'esm', + }), + dirname + ); + } + } + } + + req = this.adaptReq(req, dirname) ?? req; + + if (this.shouldIgnore(req)) { + return { type: 'ignore' }; + } + + return this.tryNodeResolve(req, dirname) ?? this.tryTypesResolve(req, dirname); + } +} diff --git a/packages/kbn-import-resolver/src/index.ts b/packages/kbn-import-resolver/src/index.ts new file mode 100644 index 0000000000000..63b551bac9f96 --- /dev/null +++ b/packages/kbn-import-resolver/src/index.ts @@ -0,0 +1,11 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +export * from './import_resolver'; +export * from './helpers/import_req'; +export * from './resolve_result'; diff --git a/packages/kbn-import-resolver/src/integration_tests/import_resolver.test.ts b/packages/kbn-import-resolver/src/integration_tests/import_resolver.test.ts new file mode 100644 index 0000000000000..b811151942bc5 --- /dev/null +++ b/packages/kbn-import-resolver/src/integration_tests/import_resolver.test.ts @@ -0,0 +1,192 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import Path from 'path'; +import { createAbsolutePathSerializer } from '@kbn/dev-utils'; + +import { ImportResolver } from '../import_resolver'; + +const FIXTURES_DIR = Path.resolve(__dirname, '../__fixtures__'); + +expect.addSnapshotSerializer(createAbsolutePathSerializer()); + +const resolver = new ImportResolver( + FIXTURES_DIR, + new Map([['@pkg/box', 'packages/box']]), + new Map([['@synth/bar', 'src/bar']]) +); + +describe('#resolve()', () => { + it('resolves imports to synth packages', () => { + expect(resolver.resolve('@synth/bar', FIXTURES_DIR)).toMatchInlineSnapshot(` + Object { + "absolute": /packages/kbn-import-resolver/src/__fixtures__/src/bar/index.js, + "type": "file", + } + `); + }); + + it('resolves imports to bazel packages that are also found in node_modules', () => { + expect(resolver.resolve('@pkg/box', FIXTURES_DIR)).toMatchInlineSnapshot(` + Object { + "absolute": /packages/kbn-import-resolver/src/__fixtures__/node_modules/@pkg/box/index.js, + "nodeModule": "@pkg/box", + "type": "file", + } + `); + }); + + it('resolves node_module imports', () => { + expect(resolver.resolve('foo', FIXTURES_DIR)).toMatchInlineSnapshot(` + Object { + "absolute": /packages/kbn-import-resolver/src/__fixtures__/node_modules/foo/index.js, + "nodeModule": "foo", + "type": "file", + } + `); + }); + + it('resolves requests to src/', () => { + expect(resolver.resolve('src/core/public', FIXTURES_DIR)).toMatchInlineSnapshot(` + Object { + "absolute": /src/core/public/index.ts, + "type": "file", + } + `); + }); + + it('resolves relative paths', () => { + expect(resolver.resolve('./bar', Path.resolve(FIXTURES_DIR, 'src/bar'))).toMatchInlineSnapshot(` + Object { + "absolute": /packages/kbn-import-resolver/src/__fixtures__/src/bar/bar.js, + "type": "file", + } + `); + }); + + it('returns null when the import cannot be resolved', () => { + expect(resolver.resolve('../../../../invalid', FIXTURES_DIR)).toMatchInlineSnapshot(`null`); + expect(resolver.resolve('src/invalid', FIXTURES_DIR)).toMatchInlineSnapshot(`null`); + expect(resolver.resolve('kibana/invalid', FIXTURES_DIR)).toMatchInlineSnapshot(`null`); + expect(resolver.resolve('@kbn/invalid', FIXTURES_DIR)).toMatchInlineSnapshot(`null`); + }); + + it('returns ignore results for known unresolvable but okay import statements', () => { + expect(resolver.resolve('../../grammar/built_grammar.js', FIXTURES_DIR)).toMatchInlineSnapshot(` + Object { + "type": "ignore", + } + `); + + expect(resolver.resolve('kibana-buildkite-library', FIXTURES_DIR)).toMatchInlineSnapshot(` + Object { + "type": "ignore", + } + `); + + expect(resolver.resolve('core_styles', FIXTURES_DIR)).toMatchInlineSnapshot(` + Object { + "type": "ignore", + } + `); + + expect(resolver.resolve('core_app_image_assets', FIXTURES_DIR)).toMatchInlineSnapshot(` + Object { + "type": "ignore", + } + `); + + expect(resolver.resolve('ace/lib/dom', FIXTURES_DIR)).toMatchInlineSnapshot(` + Object { + "type": "ignore", + } + `); + + expect(resolver.resolve('@elastic/eui/src/components/foo', FIXTURES_DIR)) + .toMatchInlineSnapshot(` + Object { + "type": "ignore", + } + `); + + expect(resolver.resolve('@elastic/eui/src/services/foo', FIXTURES_DIR)).toMatchInlineSnapshot(` + Object { + "type": "ignore", + } + `); + }); +}); + +describe('#getPackageIdForPath()', () => { + it('returns package id for bazel package', () => { + expect( + resolver.getPackageIdForPath(Path.resolve(FIXTURES_DIR, 'packages/box/index.js')) + ).toMatchInlineSnapshot(`"@pkg/box"`); + }); + + it('returns package id for synth package', () => { + expect( + resolver.getPackageIdForPath(Path.resolve(FIXTURES_DIR, 'src/bar/index.js')) + ).toMatchInlineSnapshot(`"@synth/bar"`); + }); + + it('returns null for files outside of a package', () => { + expect( + resolver.getPackageIdForPath(Path.resolve(FIXTURES_DIR, 'src/index.js')) + ).toMatchInlineSnapshot(`null`); + }); +}); + +describe('#getAbsolutePackageDir()', () => { + it('returns path for bazel package', () => { + expect(resolver.getAbsolutePackageDir('@pkg/box')).toMatchInlineSnapshot( + `/packages/kbn-import-resolver/src/__fixtures__/packages/box` + ); + }); + it('returns path for synth package', () => { + expect(resolver.getAbsolutePackageDir('@synth/bar')).toMatchInlineSnapshot( + `/packages/kbn-import-resolver/src/__fixtures__/src/bar` + ); + }); + it('returns null for node_modules', () => { + expect(resolver.getAbsolutePackageDir('foo')).toMatchInlineSnapshot(`null`); + }); + it('returns null for unknown packages', () => { + expect(resolver.getAbsolutePackageDir('@kbn/invalid')).toMatchInlineSnapshot(`null`); + }); +}); + +describe('#isBazelPackage()', () => { + it('returns true for bazel packages', () => { + expect(resolver.isBazelPackage('@pkg/box')).toBe(true); + }); + it('returns false for synth packages', () => { + expect(resolver.isBazelPackage('@synth/bar')).toBe(false); + }); + it('returns false for node_modules packages', () => { + expect(resolver.isBazelPackage('foo')).toBe(false); + }); + it('returns false for unknown packages', () => { + expect(resolver.isBazelPackage('@kbn/invalid')).toBe(false); + }); +}); + +describe('#isSyntheticPackage()', () => { + it('returns true for synth packages', () => { + expect(resolver.isSyntheticPackage('@synth/bar')).toBe(true); + }); + it('returns false for bazel packages', () => { + expect(resolver.isSyntheticPackage('@pkg/box')).toBe(false); + }); + it('returns false for node_modules packages', () => { + expect(resolver.isSyntheticPackage('foo')).toBe(false); + }); + it('returns false for unknown packages', () => { + expect(resolver.isSyntheticPackage('@kbn/invalid')).toBe(false); + }); +}); diff --git a/packages/kbn-eslint-plugin-imports/src/resolve_result.ts b/packages/kbn-import-resolver/src/resolve_result.ts similarity index 74% rename from packages/kbn-eslint-plugin-imports/src/resolve_result.ts rename to packages/kbn-import-resolver/src/resolve_result.ts index 688683c9ae860..3174da55fb58a 100644 --- a/packages/kbn-eslint-plugin-imports/src/resolve_result.ts +++ b/packages/kbn-import-resolver/src/resolve_result.ts @@ -6,6 +6,21 @@ * Side Public License, v 1. */ +/** + * Resolution result indicating that the import request resolves to a built-in node library + */ +export interface BuiltInResult { + type: 'built-in'; +} + +/** + * Resolution result indicating that the import request resolves to an npm dep which isn't + * currently installed so assumed to be optional + */ +export interface OptionalDepResult { + type: 'optional-and-missing'; +} + /** * Resolution result indicating that the import request can't be resolved, but it shouldn't need to be * because the file that is imported can't be resolved from the source alone, usually because it is explicitly @@ -35,9 +50,16 @@ export interface FileResult { type: 'file'; absolute: string; nodeModule?: string; + prefix?: string; + postfix?: string; } /** * Possible resolve result types */ -export type ResolveResult = IgnoreResult | TypesResult | FileResult; +export type ResolveResult = + | BuiltInResult + | IgnoreResult + | TypesResult + | FileResult + | OptionalDepResult; diff --git a/packages/kbn-import-resolver/tsconfig.json b/packages/kbn-import-resolver/tsconfig.json new file mode 100644 index 0000000000000..a8cfc2cceb08b --- /dev/null +++ b/packages/kbn-import-resolver/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../tsconfig.bazel.json", + "compilerOptions": { + "declaration": true, + "emitDeclarationOnly": true, + "outDir": "target_types", + "rootDir": "src", + "stripInternal": false, + "types": [ + "jest", + "node" + ] + }, + "include": [ + "src/**/*" + ] +} diff --git a/packages/kbn-optimizer/BUILD.bazel b/packages/kbn-optimizer/BUILD.bazel index 057e00066ddfa..94da078df54b2 100644 --- a/packages/kbn-optimizer/BUILD.bazel +++ b/packages/kbn-optimizer/BUILD.bazel @@ -38,6 +38,7 @@ RUNTIME_DEPS = [ "//packages/kbn-ui-shared-deps-npm", "//packages/kbn-ui-shared-deps-src", "//packages/kbn-utils", + "//packages/kbn-synthetic-package-map", "@npm//@babel/core", "@npm//chalk", "@npm//clean-webpack-plugin", @@ -70,6 +71,7 @@ TYPES_DEPS = [ "//packages/kbn-ui-shared-deps-npm:npm_module_types", "//packages/kbn-ui-shared-deps-src:npm_module_types", "//packages/kbn-utils:npm_module_types", + "//packages/kbn-synthetic-package-map:npm_module_types", "@npm//chalk", "@npm//clean-webpack-plugin", "@npm//cpy", diff --git a/packages/kbn-optimizer/src/cli.ts b/packages/kbn-optimizer/src/cli.ts index 5dba6305d5bb2..6da282b8995db 100644 --- a/packages/kbn-optimizer/src/cli.ts +++ b/packages/kbn-optimizer/src/cli.ts @@ -68,6 +68,11 @@ export function runKbnOptimizerCli(options: { defaultLimitsPath: string }) { throw createFlagError('expected --no-examples to have no value'); } + const testPlugins = flags['test-plugins'] ?? false; + if (typeof testPlugins !== 'boolean') { + throw createFlagError('expected --test-plugins to have no value'); + } + const profileWebpack = flags.profile ?? false; if (typeof profileWebpack !== 'boolean') { throw createFlagError('expected --profile to have no value'); @@ -133,6 +138,7 @@ export function runKbnOptimizerCli(options: { defaultLimitsPath: string }) { dist: dist || updateLimits, cache, examples: examples && !(validateLimits || updateLimits), + testPlugins: testPlugins && !(validateLimits || updateLimits), profileWebpack, extraPluginScanDirs, inspectWorkers, @@ -173,6 +179,7 @@ export function runKbnOptimizerCli(options: { defaultLimitsPath: string }) { 'watch', 'oss', 'examples', + 'test-plugins', 'dist', 'cache', 'profile', @@ -202,6 +209,7 @@ export function runKbnOptimizerCli(options: { defaultLimitsPath: string }) { --focus just like --filter, except dependencies are automatically included, --filter applies to result --filter comma-separated list of bundle id filters, results from multiple flags are merged, * and ! are supported --no-examples don't build the example plugins + --test-plugins build test plugins too --dist create bundles that are suitable for inclusion in the Kibana distributable, enabled when running with --update-limits --scan-dir add a directory to the list of directories scanned for plugins (specify as many times as necessary) --no-inspect-workers when inspecting the parent process, don't inspect the workers diff --git a/packages/kbn-optimizer/src/optimizer/optimizer_cache_key.test.ts b/packages/kbn-optimizer/src/optimizer/optimizer_cache_key.test.ts index 3670a6af2cbe5..b8a2aaa592a5c 100644 --- a/packages/kbn-optimizer/src/optimizer/optimizer_cache_key.test.ts +++ b/packages/kbn-optimizer/src/optimizer/optimizer_cache_key.test.ts @@ -12,6 +12,14 @@ import { createAbsolutePathSerializer } from '@kbn/dev-utils'; import { getOptimizerCacheKey } from './optimizer_cache_key'; import { OptimizerConfig } from './optimizer_config'; +jest.mock('@kbn/synthetic-package-map', () => { + return { + readHashOfPackageMap() { + return ''; + }, + }; +}); + jest.mock('../common/hashes', () => { return { Hashes: class MockHashes { @@ -68,6 +76,7 @@ describe('getOptimizerCacheKey()', () => { "checksums": Object { "foo": "bar", }, + "synthPackages": "", "workerConfig": Object { "browserslistEnv": "dev", "dist": false, diff --git a/packages/kbn-optimizer/src/optimizer/optimizer_cache_key.ts b/packages/kbn-optimizer/src/optimizer/optimizer_cache_key.ts index 1c955e18c10ce..586846653802c 100644 --- a/packages/kbn-optimizer/src/optimizer/optimizer_cache_key.ts +++ b/packages/kbn-optimizer/src/optimizer/optimizer_cache_key.ts @@ -6,6 +6,8 @@ * Side Public License, v 1. */ +import { readHashOfPackageMap } from '@kbn/synthetic-package-map'; + import { CacheableWorkerConfig, Hashes } from '../common'; import { OptimizerConfig } from './optimizer_config'; import { getOptimizerBuiltPaths } from './optimizer_built_paths'; @@ -13,6 +15,7 @@ import { getOptimizerBuiltPaths } from './optimizer_built_paths'; export interface OptimizerCacheKey { readonly workerConfig: CacheableWorkerConfig; readonly checksums: Record; + readonly synthPackages: string; } /** @@ -25,5 +28,6 @@ export async function getOptimizerCacheKey(config: OptimizerConfig): Promise Path.isAbsolute(p))) { diff --git a/packages/kbn-plugin-discovery/src/plugin_search_paths.ts b/packages/kbn-plugin-discovery/src/plugin_search_paths.ts index fe6f0a44b044e..5d46c0c8de868 100644 --- a/packages/kbn-plugin-discovery/src/plugin_search_paths.ts +++ b/packages/kbn-plugin-discovery/src/plugin_search_paths.ts @@ -12,9 +12,10 @@ export interface SearchOptions { rootDir: string; oss: boolean; examples: boolean; + testPlugins?: boolean; } -export function getPluginSearchPaths({ rootDir, oss, examples }: SearchOptions) { +export function getPluginSearchPaths({ rootDir, oss, examples, testPlugins }: SearchOptions) { return [ resolve(rootDir, 'src', 'plugins'), ...(oss ? [] : [resolve(rootDir, 'x-pack', 'plugins')]), @@ -22,5 +23,25 @@ export function getPluginSearchPaths({ rootDir, oss, examples }: SearchOptions) ...(examples ? [resolve(rootDir, 'examples')] : []), ...(examples && !oss ? [resolve(rootDir, 'x-pack', 'examples')] : []), resolve(rootDir, '..', 'kibana-extra'), + ...(testPlugins + ? [ + resolve(rootDir, 'test/analytics/__fixtures__/plugins'), + resolve(rootDir, 'test/plugin_functional/plugins'), + resolve(rootDir, 'test/interpreter_functional/plugins'), + resolve(rootDir, 'test/common/fixtures/plugins'), + ] + : []), + ...(testPlugins && !oss + ? [ + resolve(rootDir, 'x-pack/test/plugin_functional/plugins'), + resolve(rootDir, 'x-pack/test/functional_with_es_ssl/fixtures/plugins'), + resolve(rootDir, 'x-pack/test/alerting_api_integration/plugins'), + resolve(rootDir, 'x-pack/test/plugin_api_integration/plugins'), + resolve(rootDir, 'x-pack/test/plugin_api_perf/plugins'), + resolve(rootDir, 'x-pack/test/licensing_plugin/plugins'), + resolve(rootDir, 'x-pack/test/usage_collection/plugins'), + resolve(rootDir, 'x-pack/test/security_functional/fixtures/common'), + ] + : []), ]; } diff --git a/packages/kbn-pm/dist/index.js b/packages/kbn-pm/dist/index.js index 691495e0a7922..3997f688aa2fc 100644 --- a/packages/kbn-pm/dist/index.js +++ b/packages/kbn-pm/dist/index.js @@ -94,7 +94,7 @@ __webpack_require__.r(__webpack_exports__); /* harmony import */ var _cli__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "run", function() { return _cli__WEBPACK_IMPORTED_MODULE_0__["run"]; }); -/* harmony import */ var _production__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(591); +/* harmony import */ var _production__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(629); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "buildBazelProductionProjects", function() { return _production__WEBPACK_IMPORTED_MODULE_1__["buildBazelProductionProjects"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "buildNonBazelProductionProjects", function() { return _production__WEBPACK_IMPORTED_MODULE_1__["buildNonBazelProductionProjects"]; }); @@ -108,7 +108,7 @@ __webpack_require__.r(__webpack_exports__); /* harmony import */ var _utils_package_json__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(464); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "transformDependencies", function() { return _utils_package_json__WEBPACK_IMPORTED_MODULE_4__["transformDependencies"]; }); -/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(590); +/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(628); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getProjectPaths", function() { return _config__WEBPACK_IMPORTED_MODULE_5__["getProjectPaths"]; }); /* @@ -141,7 +141,7 @@ __webpack_require__.r(__webpack_exports__); /* harmony import */ var _kbn_dev_utils_tooling_log__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(5); /* harmony import */ var _kbn_dev_utils_tooling_log__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_kbn_dev_utils_tooling_log__WEBPACK_IMPORTED_MODULE_3__); /* harmony import */ var _commands__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(250); -/* harmony import */ var _run__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(585); +/* harmony import */ var _run__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(576); /* harmony import */ var _utils_log__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(341); /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one @@ -11746,11 +11746,11 @@ exports.ToolingLogCollectingWriter = ToolingLogCollectingWriter; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "commands", function() { return commands; }); /* harmony import */ var _bootstrap__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(251); -/* harmony import */ var _build__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(556); -/* harmony import */ var _clean__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(557); -/* harmony import */ var _reset__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(581); -/* harmony import */ var _run__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(582); -/* harmony import */ var _watch__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(584); +/* harmony import */ var _build__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(547); +/* harmony import */ var _clean__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(548); +/* harmony import */ var _reset__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(572); +/* harmony import */ var _run__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(573); +/* harmony import */ var _watch__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(575); /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License @@ -11789,10 +11789,9 @@ __webpack_require__.r(__webpack_exports__); /* harmony import */ var _utils_link_project_executables__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(351); /* harmony import */ var _utils_projects__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(461); /* harmony import */ var _utils_yarn_lock__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(530); -/* harmony import */ var _utils_sort_package_json__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(533); -/* harmony import */ var _utils_validate_dependencies__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(542); -/* harmony import */ var _utils_bazel__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(544); -/* harmony import */ var _utils_bazel_setup_remote_cache__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(555); +/* harmony import */ var _utils_validate_dependencies__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(533); +/* harmony import */ var _utils_bazel__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(535); +/* harmony import */ var _utils_bazel_setup_remote_cache__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(546); function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } @@ -11816,7 +11815,6 @@ function _defineProperty(obj, key, value) { if (key in obj) { Object.definePrope - const BootstrapCommand = { description: 'Install dependencies and crosslink projects', name: 'bootstrap', @@ -11855,9 +11853,9 @@ const BootstrapCommand = { const forceInstall = !!options && options['force-install'] === true; // Install bazel machinery tools if needed - await Object(_utils_bazel__WEBPACK_IMPORTED_MODULE_9__["installBazelTools"])(rootPath); // Setup remote cache settings in .bazelrc.cache if needed + await Object(_utils_bazel__WEBPACK_IMPORTED_MODULE_8__["installBazelTools"])(rootPath); // Setup remote cache settings in .bazelrc.cache if needed - await Object(_utils_bazel_setup_remote_cache__WEBPACK_IMPORTED_MODULE_10__["setupRemoteCache"])(rootPath); // Bootstrap process for Bazel packages + await Object(_utils_bazel_setup_remote_cache__WEBPACK_IMPORTED_MODULE_9__["setupRemoteCache"])(rootPath); // Bootstrap process for Bazel packages // Bazel is now managing dependencies so yarn install // will happen as part of this // @@ -11869,9 +11867,9 @@ const BootstrapCommand = { if (forceInstall) { await time('force install dependencies', async () => { - await Object(_utils_bazel__WEBPACK_IMPORTED_MODULE_9__["removeYarnIntegrityFileIfExists"])(Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(kibanaProjectPath, 'node_modules')); - await Object(_utils_bazel__WEBPACK_IMPORTED_MODULE_9__["runBazel"])(['clean', '--expunge']); - await Object(_utils_bazel__WEBPACK_IMPORTED_MODULE_9__["runBazel"])(['run', '@nodejs//:yarn'], runOffline, { + await Object(_utils_bazel__WEBPACK_IMPORTED_MODULE_8__["removeYarnIntegrityFileIfExists"])(Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(kibanaProjectPath, 'node_modules')); + await Object(_utils_bazel__WEBPACK_IMPORTED_MODULE_8__["runBazel"])(['clean', '--expunge']); + await Object(_utils_bazel__WEBPACK_IMPORTED_MODULE_8__["runBazel"])(['run', '@nodejs//:yarn'], runOffline, { env: { SASS_BINARY_SITE: 'https://us-central1-elastic-kibana-184716.cloudfunctions.net/kibana-ci-proxy-cache/node-sass', RE2_DOWNLOAD_MIRROR: 'https://us-central1-elastic-kibana-184716.cloudfunctions.net/kibana-ci-proxy-cache/node-re2' @@ -11882,7 +11880,7 @@ const BootstrapCommand = { await time('build packages', async () => { - await Object(_utils_bazel__WEBPACK_IMPORTED_MODULE_9__["runBazel"])(['build', '//packages:build', '--show_result=1'], runOffline); + await Object(_utils_bazel__WEBPACK_IMPORTED_MODULE_8__["runBazel"])(['build', '//packages:build', '--show_result=1'], runOffline); }); // Install monorepo npm dependencies outside of the Bazel managed ones for (const batch of batchedNonBazelProjects) { @@ -11904,14 +11902,11 @@ const BootstrapCommand = { } } - await time('sort package json', async () => { - await Object(_utils_sort_package_json__WEBPACK_IMPORTED_MODULE_7__["sortPackageJson"])(kbn); - }); const yarnLock = await time('read yarn.lock', async () => await Object(_utils_yarn_lock__WEBPACK_IMPORTED_MODULE_6__["readYarnLock"])(kbn)); if (options.validate) { await time('validate dependencies', async () => { - await Object(_utils_validate_dependencies__WEBPACK_IMPORTED_MODULE_8__["validateDependencies"])(kbn, yarnLock); + await Object(_utils_validate_dependencies__WEBPACK_IMPORTED_MODULE_7__["validateDependencies"])(kbn, yarnLock); }); } // Assure all kbn projects with bin defined scripts // copy those scripts into the top level node_modules folder @@ -54621,11 +54616,19 @@ module.exports = require("buffer"); "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sortPackageJson", function() { return sortPackageJson; }); -/* harmony import */ var fs_promises__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(534); -/* harmony import */ var fs_promises__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs_promises__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _kbn_dev_utils_sort_package_json__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(535); -/* harmony import */ var _kbn_dev_utils_sort_package_json__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_kbn_dev_utils_sort_package_json__WEBPACK_IMPORTED_MODULE_1__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "validateDependencies", function() { return validateDependencies; }); +/* harmony import */ var _yarnpkg_lockfile__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(531); +/* harmony import */ var _yarnpkg_lockfile__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_yarnpkg_lockfile__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var dedent__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2); +/* harmony import */ var dedent__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(dedent__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(235); +/* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(chalk__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_3__); +/* harmony import */ var _fs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(352); +/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(341); +/* harmony import */ var _package_json__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(464); +/* harmony import */ var _projects_tree__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(534); /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License @@ -54633,838 +54636,161 @@ __webpack_require__.r(__webpack_exports__); * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ +// @ts-expect-error published types are useless -async function sortPackageJson(kbn) { - const packageJsonPath = kbn.getAbsolute('package.json'); - await fs_promises__WEBPACK_IMPORTED_MODULE_0___default.a.writeFile(packageJsonPath, Object(_kbn_dev_utils_sort_package_json__WEBPACK_IMPORTED_MODULE_1__["sortPackageJson"])(await fs_promises__WEBPACK_IMPORTED_MODULE_0___default.a.readFile(packageJsonPath, 'utf-8'))); -} -/***/ }), -/* 534 */ -/***/ (function(module, exports) { -module.exports = require("fs/promises"); -/***/ }), -/* 535 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; -var _interopRequireDefault = __webpack_require__(7); +async function validateDependencies(kbn, yarnLock) { + // look through all of the packages in the yarn.lock file to see if + // we have accidentally installed multiple lodash v4 versions + const lodash4Versions = new Set(); + const lodash4Reqs = new Set(); -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.sortPackageJson = sortPackageJson; + for (const [req, dep] of Object.entries(yarnLock)) { + if (req.startsWith('lodash@') && dep.version.startsWith('4.')) { + lodash4Reqs.add(req); + lodash4Versions.add(dep.version); + } + } // if we find more than one lodash v4 version installed then delete + // lodash v4 requests from the yarn.lock file and prompt the user to + // retry bootstrap so that a single v4 version will be installed -var _sortPackageJson = _interopRequireDefault(__webpack_require__(536)); -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ -function sortPackageJson(json) { - return JSON.stringify((0, _sortPackageJson.default)(JSON.parse(json), { - // top level keys in the order they were written when this was implemented - sortOrder: ['name', 'description', 'keywords', 'private', 'version', 'branch', 'main', 'browser', 'types', 'tsdocMetadata', 'build', 'homepage', 'bugs', 'license', 'kibana', 'author', 'scripts', 'repository', 'engines', 'resolutions'] - }), null, 2) + '\n'; -} + if (lodash4Versions.size > 1) { + for (const req of lodash4Reqs) { + delete yarnLock[req]; + } -/***/ }), -/* 536 */ -/***/ (function(module, exports, __webpack_require__) { + await Object(_fs__WEBPACK_IMPORTED_MODULE_4__["writeFile"])(kbn.getAbsolute('yarn.lock'), Object(_yarnpkg_lockfile__WEBPACK_IMPORTED_MODULE_0__["stringify"])(yarnLock), 'utf8'); + _log__WEBPACK_IMPORTED_MODULE_5__["log"].error(dedent__WEBPACK_IMPORTED_MODULE_1___default.a` -const sortObjectKeys = __webpack_require__(537) -const detectIndent = __webpack_require__(538) -const detectNewline = __webpack_require__(539).graceful -const gitHooks = __webpack_require__(540) -const isPlainObject = __webpack_require__(541) + Multiple version of lodash v4 were detected, so they have been removed + from the yarn.lock file. Please rerun yarn kbn bootstrap to coalese the + lodash versions installed. -const hasOwnProperty = (object, property) => - Object.prototype.hasOwnProperty.call(object, property) -const pipe = (fns) => (x, ...args) => - fns.reduce((result, fn) => fn(result, ...args), x) -const onArray = (fn) => (x) => (Array.isArray(x) ? fn(x) : x) -const onStringArray = (fn) => (x) => - Array.isArray(x) && x.every((item) => typeof item === 'string') ? fn(x) : x -const uniq = onStringArray((xs) => xs.filter((x, i) => i === xs.indexOf(x))) -const sortArray = onStringArray((array) => [...array].sort()) -const uniqAndSortArray = pipe([uniq, sortArray]) -const onObject = (fn) => (x, ...args) => (isPlainObject(x) ? fn(x, ...args) : x) -const sortObjectBy = (comparator, deep) => { - const over = onObject((object) => { - object = sortObjectKeys(object, comparator) - if (deep) { - for (const [key, value] of Object.entries(object)) { - object[key] = over(value) - } - } - return object - }) + If you still see this error when you re-bootstrap then you might need + to force a new dependency to use the latest version of lodash via the + "resolutions" field in package.json. - return over -} -const sortObject = sortObjectBy() -const sortURLObject = sortObjectBy(['type', 'url']) -const sortPeopleObject = sortObjectBy(['name', 'email', 'url']) -const sortDirectories = sortObjectBy([ - 'lib', - 'bin', - 'man', - 'doc', - 'example', - 'test', -]) -const overProperty = (property, over) => (object, ...args) => - hasOwnProperty(object, property) - ? Object.assign(object, { [property]: over(object[property], ...args) }) - : object -const sortGitHooks = sortObjectBy(gitHooks) + If you have questions about this please reach out to the operations team. -// https://github.com/eslint/eslint/blob/acc0e47572a9390292b4e313b4a4bf360d236358/conf/config-schema.js -const eslintBaseConfigProperties = [ - // `files` and `excludedFiles` are only on `overrides[]` - // for easier sort `overrides[]`, - // add them to here, so we don't need sort `overrides[]` twice - 'files', - 'excludedFiles', - // baseConfig - 'env', - 'parser', - 'parserOptions', - 'settings', - 'plugins', - 'extends', - 'rules', - 'overrides', - 'globals', - 'processor', - 'noInlineConfig', - 'reportUnusedDisableDirectives', -] -const sortEslintConfig = onObject( - pipe([ - sortObjectBy(eslintBaseConfigProperties), - overProperty('env', sortObject), - overProperty('globals', sortObject), - overProperty( - 'overrides', - onArray((overrides) => overrides.map(sortEslintConfig)), - ), - overProperty('parserOptions', sortObject), - overProperty( - 'rules', - sortObjectBy( - (rule1, rule2) => - rule1.split('/').length - rule2.split('/').length || - rule1.localeCompare(rule2), - ), - ), - overProperty('settings', sortObject), - ]), -) -const sortVSCodeBadgeObject = sortObjectBy(['description', 'url', 'href']) + `); + process.exit(1); + } // look through all the dependencies of production packages and production + // dependencies of those packages to determine if we're shipping any versions + // of lodash v3 in the distributable -const sortPrettierConfig = onObject( - pipe([ - // sort keys alphabetically, but put `overrides` at bottom - (config) => - sortObjectKeys(config, [ - ...Object.keys(config) - .filter((key) => key !== 'overrides') - .sort(), - 'overrides', - ]), - // if `config.overrides` exists - overProperty( - 'overrides', - // and `config.overrides` is an array - onArray((overrides) => - overrides.map( - pipe([ - // sort `config.overrides[]` alphabetically - sortObject, - // sort `config.overrides[].options` alphabetically - overProperty('options', sortObject), - ]), - ), - ), - ), - ]), -) -// See https://docs.npmjs.com/misc/scripts -const defaultNpmScripts = new Set([ - 'install', - 'pack', - 'prepare', - 'publish', - 'restart', - 'shrinkwrap', - 'start', - 'stop', - 'test', - 'uninstall', - 'version', -]) + const prodDependencies = kbn.resolveAllProductionDependencies(yarnLock, _log__WEBPACK_IMPORTED_MODULE_5__["log"]); + const lodash3Versions = new Set(); -const hasDevDependency = (dependency, packageJson) => { - return ( - 'devDependencies' in packageJson && - !!packageJson.devDependencies[dependency] - ) -} + for (const dep of prodDependencies.values()) { + if (dep.name === 'lodash' && dep.version.startsWith('3.')) { + lodash3Versions.add(dep.version); + } + } // if any lodash v3 packages were found we abort and tell the user to fix things -const sortScripts = onObject((scripts, packageJson) => { - const names = Object.keys(scripts) - const prefixable = new Set() - const keys = names.map((name) => { - const omitted = name.replace(/^(?:pre|post)/, '') - if (defaultNpmScripts.has(omitted) || names.includes(omitted)) { - prefixable.add(omitted) - return omitted - } - return name - }) + if (lodash3Versions.size) { + _log__WEBPACK_IMPORTED_MODULE_5__["log"].error(dedent__WEBPACK_IMPORTED_MODULE_1___default.a` - if (!hasDevDependency('npm-run-all', packageJson)) { - keys.sort() - } + Due to changes in the yarn.lock file and/or package.json files a version of + lodash 3 is now included in the production dependencies. To reduce the size of + our distributable and especially our front-end bundles we have decided to + prevent adding any new instances of lodash 3. - const order = keys.reduce( - (order, key) => - order.concat( - prefixable.has(key) ? [`pre${key}`, key, `post${key}`] : [key], - ), - [], - ) + Please inspect the changes to yarn.lock or package.json files to identify where + the lodash 3 version is coming from and remove it. - return sortObjectKeys(scripts, order) -}) + If you have questions about this please reack out to the operations team. -// fields marked `vscode` are for `Visual Studio Code extension manifest` only -// https://code.visualstudio.com/api/references/extension-manifest -// Supported fields: -// publisher, displayName, categories, galleryBanner, preview, contributes, -// activationEvents, badges, markdown, qna, extensionPack, -// extensionDependencies, icon + `); + process.exit(1); + } // TODO: remove this once we move into a single package.json + // look through all the package.json files to find packages which have mismatched version ranges -// field.key{string}: field name -// field.over{function}: sort field subKey -const fields = [ - { key: '$schema' }, - { key: 'name' }, - /* vscode */ { key: 'displayName' }, - { key: 'version' }, - { key: 'private' }, - { key: 'description' }, - /* vscode */ { key: 'categories', over: uniq }, - { key: 'keywords', over: uniq }, - { key: 'homepage' }, - { key: 'bugs', over: sortObjectBy(['url', 'email']) }, - { key: 'repository', over: sortURLObject }, - { key: 'funding', over: sortURLObject }, - { key: 'license', over: sortURLObject }, - /* vscode */ { key: 'qna' }, - { key: 'author', over: sortPeopleObject }, - { - key: 'maintainers', - over: onArray((maintainers) => maintainers.map(sortPeopleObject)), - }, - { - key: 'contributors', - over: onArray((contributors) => contributors.map(sortPeopleObject)), - }, - /* vscode */ { key: 'publisher' }, - { key: 'sideEffects' }, - { key: 'type' }, - { key: 'imports' }, - { key: 'exports' }, - { key: 'main' }, - { key: 'umd:main' }, - { key: 'jsdelivr' }, - { key: 'unpkg' }, - { key: 'module' }, - { key: 'source' }, - { key: 'jsnext:main' }, - { key: 'browser' }, - { key: 'types' }, - { key: 'typesVersions' }, - { key: 'typings' }, - { key: 'style' }, - { key: 'example' }, - { key: 'examplestyle' }, - { key: 'assets' }, - { key: 'bin', over: sortObject }, - { key: 'man' }, - { key: 'directories', over: sortDirectories }, - { key: 'files', over: uniq }, - { key: 'workspaces' }, - // node-pre-gyp https://www.npmjs.com/package/node-pre-gyp#1-add-new-entries-to-your-packagejson - { - key: 'binary', - over: sortObjectBy([ - 'module_name', - 'module_path', - 'remote_path', - 'package_name', - 'host', - ]), - }, - { key: 'scripts', over: sortScripts }, - { key: 'betterScripts', over: sortScripts }, - /* vscode */ { key: 'contributes', over: sortObject }, - /* vscode */ { key: 'activationEvents', over: uniq }, - { key: 'husky', over: overProperty('hooks', sortGitHooks) }, - { key: 'simple-git-hooks', over: sortGitHooks }, - { key: 'pre-commit' }, - { key: 'commitlint', over: sortObject }, - { key: 'lint-staged' }, - { key: 'config', over: sortObject }, - { key: 'nodemonConfig', over: sortObject }, - { key: 'browserify', over: sortObject }, - { key: 'babel', over: sortObject }, - { key: 'browserslist' }, - { key: 'xo', over: sortObject }, - { key: 'prettier', over: sortPrettierConfig }, - { key: 'eslintConfig', over: sortEslintConfig }, - { key: 'eslintIgnore' }, - { key: 'npmpkgjsonlint', over: sortObject }, - { key: 'npmPackageJsonLintConfig', over: sortObject }, - { key: 'npmpackagejsonlint', over: sortObject }, - { key: 'release', over: sortObject }, - { key: 'remarkConfig', over: sortObject }, - { key: 'stylelint' }, - { key: 'ava', over: sortObject }, - { key: 'jest', over: sortObject }, - { key: 'mocha', over: sortObject }, - { key: 'nyc', over: sortObject }, - { key: 'c8', over: sortObject }, - { key: 'tap', over: sortObject }, - { key: 'resolutions', over: sortObject }, - { key: 'dependencies', over: sortObject }, - { key: 'devDependencies', over: sortObject }, - { key: 'dependenciesMeta', over: sortObjectBy(undefined, true) }, - { key: 'peerDependencies', over: sortObject }, - // TODO: only sort depth = 2 - { key: 'peerDependenciesMeta', over: sortObjectBy(undefined, true) }, - { key: 'optionalDependencies', over: sortObject }, - { key: 'bundledDependencies', over: uniqAndSortArray }, - { key: 'bundleDependencies', over: uniqAndSortArray }, - /* vscode */ { key: 'extensionPack', over: uniqAndSortArray }, - /* vscode */ { key: 'extensionDependencies', over: uniqAndSortArray }, - { key: 'flat' }, - { key: 'engines', over: sortObject }, - { key: 'engineStrict', over: sortObject }, - { key: 'languageName' }, - { key: 'os' }, - { key: 'cpu' }, - { key: 'preferGlobal', over: sortObject }, - { key: 'publishConfig', over: sortObject }, - /* vscode */ { key: 'icon' }, - /* vscode */ { - key: 'badges', - over: onArray((badge) => badge.map(sortVSCodeBadgeObject)), - }, - /* vscode */ { key: 'galleryBanner', over: sortObject }, - /* vscode */ { key: 'preview' }, - /* vscode */ { key: 'markdown' }, -] -const defaultSortOrder = fields.map(({ key }) => key) -const overFields = pipe( - fields.reduce((fns, { key, over }) => { - if (over) { - fns.push(overProperty(key, over)) - } - return fns - }, []), -) + const depRanges = new Map(); -function editStringJSON(json, over) { - if (typeof json === 'string') { - const { indent } = detectIndent(json) - const endCharacters = json.slice(-1) === '\n' ? '\n' : '' - const newline = detectNewline(json) - json = JSON.parse(json) + for (const project of kbn.getAllProjects().values()) { + var _kbn$kibanaProject; - let result = JSON.stringify(over(json), null, indent) + endCharacters - if (newline === '\r\n') { - result = result.replace(/\n/g, newline) + // Skip if this is an external plugin + if (project.path.includes(`${(_kbn$kibanaProject = kbn.kibanaProject) === null || _kbn$kibanaProject === void 0 ? void 0 : _kbn$kibanaProject.path}${path__WEBPACK_IMPORTED_MODULE_3__["sep"]}plugins`)) { + continue; } - return result - } - return over(json) -} + for (const [dep, range] of Object.entries(project.allDependencies)) { + const existingDep = depRanges.get(dep); -const isPrivateKey = (key) => key[0] === '_' -const partition = (array, predicate) => - array.reduce( - (result, value) => { - result[predicate(value) ? 0 : 1].push(value) - return result - }, - [[], []], - ) -function sortPackageJson(jsonIsh, options = {}) { - return editStringJSON( - jsonIsh, - onObject((json) => { - let sortOrder = options.sortOrder ? options.sortOrder : defaultSortOrder + if (!existingDep) { + depRanges.set(dep, [{ + range, + projects: [project] + }]); + continue; + } - if (Array.isArray(sortOrder)) { - const keys = Object.keys(json) - const [privateKeys, publicKeys] = partition(keys, isPrivateKey) - sortOrder = [ - ...sortOrder, - ...defaultSortOrder, - ...publicKeys.sort(), - ...privateKeys.sort(), - ] + const existingRange = existingDep.find(existing => existing.range === range); + + if (!existingRange) { + existingDep.push({ + range, + projects: [project] + }); + continue; } - return overFields(sortObjectKeys(json, sortOrder), json) - }), - ) -} + existingRange.projects.push(project); + } + } -module.exports = sortPackageJson -module.exports.sortPackageJson = sortPackageJson -module.exports.sortOrder = defaultSortOrder -module.exports.default = sortPackageJson + const duplicateRanges = Array.from(depRanges.entries()).filter(([, ranges]) => ranges.length > 1 && !ranges.every(rng => Object(_package_json__WEBPACK_IMPORTED_MODULE_6__["isLinkDependency"])(rng.range))).reduce((acc, [dep, ranges]) => [...acc, dep, ...ranges.map(({ + range, + projects + }) => ` ${range} => ${projects.map(p => p.name).join(', ')}`)], []).join('\n '); + if (duplicateRanges) { + _log__WEBPACK_IMPORTED_MODULE_5__["log"].error(dedent__WEBPACK_IMPORTED_MODULE_1___default.a` -/***/ }), -/* 537 */ -/***/ (function(module, exports) { + [single_version_dependencies] Multiple version ranges for the same dependency + were found declared across different package.json files. Please consolidate + those to match across all package.json files. Different versions for the + same dependency is not supported. -module.exports = function sortObjectByKeyNameList(object, sortWith) { - var keys; - var sortFn; + If you have questions about this please reach out to the operations team. - if (typeof sortWith === 'function') { - sortFn = sortWith; - } else { - keys = sortWith; - } + The conflicting dependencies are: - var objectKeys = Object.keys(object); - return (keys || []).concat(objectKeys.sort(sortFn)).reduce(function(total, key) { - if (objectKeys.indexOf(key) !== -1) { - total[key] = object[key]; - } - return total; - }, Object.create(null)); -} + ${duplicateRanges} + `); + process.exit(1); + } // look for packages that have the the `kibana.devOnly` flag in their package.json + // and make sure they aren't included in the production dependencies of Kibana -/***/ }), -/* 538 */ -/***/ (function(module, exports, __webpack_require__) { + const devOnlyProjectsInProduction = getDevOnlyProductionDepsTree(kbn, 'kibana'); -"use strict"; + if (devOnlyProjectsInProduction) { + _log__WEBPACK_IMPORTED_MODULE_5__["log"].error(dedent__WEBPACK_IMPORTED_MODULE_1___default.a` + Some of the packages in the production dependency chain for Kibana and X-Pack are + flagged with "kibana.devOnly" in their package.json. Please check changes made to + packages and their dependencies to ensure they don't end up in production. + The devOnly dependencies that are being dependend on in production are: -// Detect either spaces or tabs but not both to properly handle tabs for indentation and spaces for alignment -const INDENT_REGEX = /^(?:( )+|\t+)/; + ${Object(_projects_tree__WEBPACK_IMPORTED_MODULE_7__["treeToString"])(devOnlyProjectsInProduction).split('\n').join('\n ')} + `); + process.exit(1); + } -const INDENT_TYPE_SPACE = 'space'; -const INDENT_TYPE_TAB = 'tab'; - -// Make a Map that counts how many indents/unindents have occurred for a given size and how many lines follow a given indentation. -// The key is a concatenation of the indentation type (s = space and t = tab) and the size of the indents/unindents. -// -// indents = { -// t3: [1, 0], -// t4: [1, 5], -// s5: [1, 0], -// s12: [1, 0], -// } -function makeIndentsMap(string, ignoreSingleSpaces) { - const indents = new Map(); - - // Remember the size of previous line's indentation - let previousSize = 0; - let previousIndentType; - - // Indents key (ident type + size of the indents/unindents) - let key; - - for (const line of string.split(/\n/g)) { - if (!line) { - // Ignore empty lines - continue; - } - - let indent; - let indentType; - let weight; - let entry; - const matches = line.match(INDENT_REGEX); - - if (matches === null) { - previousSize = 0; - previousIndentType = ''; - } else { - indent = matches[0].length; - - if (matches[1]) { - indentType = INDENT_TYPE_SPACE; - } else { - indentType = INDENT_TYPE_TAB; - } - - // Ignore single space unless it's the only indent detected to prevent common false positives - if (ignoreSingleSpaces && indentType === INDENT_TYPE_SPACE && indent === 1) { - continue; - } - - if (indentType !== previousIndentType) { - previousSize = 0; - } - - previousIndentType = indentType; - - weight = 0; - - const indentDifference = indent - previousSize; - previousSize = indent; - - // Previous line have same indent? - if (indentDifference === 0) { - weight++; - // We use the key from previous loop - } else { - const absoluteIndentDifference = indentDifference > 0 ? indentDifference : -indentDifference; - key = encodeIndentsKey(indentType, absoluteIndentDifference); - } - - // Update the stats - entry = indents.get(key); - - if (entry === undefined) { - entry = [1, 0]; // Init - } else { - entry = [++entry[0], entry[1] + weight]; - } - - indents.set(key, entry); - } - } - - return indents; -} - -// Encode the indent type and amount as a string (e.g. 's4') for use as a compound key in the indents Map. -function encodeIndentsKey(indentType, indentAmount) { - const typeCharacter = indentType === INDENT_TYPE_SPACE ? 's' : 't'; - return typeCharacter + String(indentAmount); -} - -// Extract the indent type and amount from a key of the indents Map. -function decodeIndentsKey(indentsKey) { - const keyHasTypeSpace = indentsKey[0] === 's'; - const type = keyHasTypeSpace ? INDENT_TYPE_SPACE : INDENT_TYPE_TAB; - - const amount = Number(indentsKey.slice(1)); - - return {type, amount}; -} - -// Return the key (e.g. 's4') from the indents Map that represents the most common indent, -// or return undefined if there are no indents. -function getMostUsedKey(indents) { - let result; - let maxUsed = 0; - let maxWeight = 0; - - for (const [key, [usedCount, weight]] of indents) { - if (usedCount > maxUsed || (usedCount === maxUsed && weight > maxWeight)) { - maxUsed = usedCount; - maxWeight = weight; - result = key; - } - } - - return result; -} - -function makeIndentString(type, amount) { - const indentCharacter = type === INDENT_TYPE_SPACE ? ' ' : '\t'; - return indentCharacter.repeat(amount); -} - -module.exports = string => { - if (typeof string !== 'string') { - throw new TypeError('Expected a string'); - } - - // Identify indents while skipping single space indents to avoid common edge cases (e.g. code comments) - // If no indents are identified, run again and include all indents for comprehensive detection - let indents = makeIndentsMap(string, true); - if (indents.size === 0) { - indents = makeIndentsMap(string, false); - } - - const keyOfMostUsedIndent = getMostUsedKey(indents); - - let type; - let amount = 0; - let indent = ''; - - if (keyOfMostUsedIndent !== undefined) { - ({type, amount} = decodeIndentsKey(keyOfMostUsedIndent)); - indent = makeIndentString(type, amount); - } - - return { - amount, - type, - indent - }; -}; - - -/***/ }), -/* 539 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const detectNewline = string => { - if (typeof string !== 'string') { - throw new TypeError('Expected a string'); - } - - const newlines = string.match(/(?:\r?\n)/g) || []; - - if (newlines.length === 0) { - return; - } - - const crlf = newlines.filter(newline => newline === '\r\n').length; - const lf = newlines.length - crlf; - - return crlf > lf ? '\r\n' : '\n'; -}; - -module.exports = detectNewline; -module.exports.graceful = string => (typeof string === 'string' && detectNewline(string)) || '\n'; - - -/***/ }), -/* 540 */ -/***/ (function(module) { - -module.exports = JSON.parse("[\"applypatch-msg\",\"pre-applypatch\",\"post-applypatch\",\"pre-commit\",\"pre-merge-commit\",\"prepare-commit-msg\",\"commit-msg\",\"post-commit\",\"pre-rebase\",\"post-checkout\",\"post-merge\",\"pre-push\",\"pre-receive\",\"update\",\"post-receive\",\"post-update\",\"push-to-checkout\",\"pre-auto-gc\",\"post-rewrite\",\"sendemail-validate\",\"fsmonitor-watchman\",\"p4-pre-submit\",\"post-index-change\"]"); - -/***/ }), -/* 541 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -module.exports = value => { - if (Object.prototype.toString.call(value) !== '[object Object]') { - return false; - } - - const prototype = Object.getPrototypeOf(value); - return prototype === null || prototype === Object.prototype; -}; - - -/***/ }), -/* 542 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "validateDependencies", function() { return validateDependencies; }); -/* harmony import */ var _yarnpkg_lockfile__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(531); -/* harmony import */ var _yarnpkg_lockfile__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_yarnpkg_lockfile__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var dedent__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2); -/* harmony import */ var dedent__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(dedent__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(235); -/* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(chalk__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var _fs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(352); -/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(341); -/* harmony import */ var _package_json__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(464); -/* harmony import */ var _projects_tree__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(543); -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ -// @ts-expect-error published types are useless - - - - - - - - -async function validateDependencies(kbn, yarnLock) { - // look through all of the packages in the yarn.lock file to see if - // we have accidentally installed multiple lodash v4 versions - const lodash4Versions = new Set(); - const lodash4Reqs = new Set(); - - for (const [req, dep] of Object.entries(yarnLock)) { - if (req.startsWith('lodash@') && dep.version.startsWith('4.')) { - lodash4Reqs.add(req); - lodash4Versions.add(dep.version); - } - } // if we find more than one lodash v4 version installed then delete - // lodash v4 requests from the yarn.lock file and prompt the user to - // retry bootstrap so that a single v4 version will be installed - - - if (lodash4Versions.size > 1) { - for (const req of lodash4Reqs) { - delete yarnLock[req]; - } - - await Object(_fs__WEBPACK_IMPORTED_MODULE_4__["writeFile"])(kbn.getAbsolute('yarn.lock'), Object(_yarnpkg_lockfile__WEBPACK_IMPORTED_MODULE_0__["stringify"])(yarnLock), 'utf8'); - _log__WEBPACK_IMPORTED_MODULE_5__["log"].error(dedent__WEBPACK_IMPORTED_MODULE_1___default.a` - - Multiple version of lodash v4 were detected, so they have been removed - from the yarn.lock file. Please rerun yarn kbn bootstrap to coalese the - lodash versions installed. - - If you still see this error when you re-bootstrap then you might need - to force a new dependency to use the latest version of lodash via the - "resolutions" field in package.json. - - If you have questions about this please reach out to the operations team. - - `); - process.exit(1); - } // look through all the dependencies of production packages and production - // dependencies of those packages to determine if we're shipping any versions - // of lodash v3 in the distributable - - - const prodDependencies = kbn.resolveAllProductionDependencies(yarnLock, _log__WEBPACK_IMPORTED_MODULE_5__["log"]); - const lodash3Versions = new Set(); - - for (const dep of prodDependencies.values()) { - if (dep.name === 'lodash' && dep.version.startsWith('3.')) { - lodash3Versions.add(dep.version); - } - } // if any lodash v3 packages were found we abort and tell the user to fix things - - - if (lodash3Versions.size) { - _log__WEBPACK_IMPORTED_MODULE_5__["log"].error(dedent__WEBPACK_IMPORTED_MODULE_1___default.a` - - Due to changes in the yarn.lock file and/or package.json files a version of - lodash 3 is now included in the production dependencies. To reduce the size of - our distributable and especially our front-end bundles we have decided to - prevent adding any new instances of lodash 3. - - Please inspect the changes to yarn.lock or package.json files to identify where - the lodash 3 version is coming from and remove it. - - If you have questions about this please reack out to the operations team. - - `); - process.exit(1); - } // TODO: remove this once we move into a single package.json - // look through all the package.json files to find packages which have mismatched version ranges - - - const depRanges = new Map(); - - for (const project of kbn.getAllProjects().values()) { - var _kbn$kibanaProject; - - // Skip if this is an external plugin - if (project.path.includes(`${(_kbn$kibanaProject = kbn.kibanaProject) === null || _kbn$kibanaProject === void 0 ? void 0 : _kbn$kibanaProject.path}${path__WEBPACK_IMPORTED_MODULE_3__["sep"]}plugins`)) { - continue; - } - - for (const [dep, range] of Object.entries(project.allDependencies)) { - const existingDep = depRanges.get(dep); - - if (!existingDep) { - depRanges.set(dep, [{ - range, - projects: [project] - }]); - continue; - } - - const existingRange = existingDep.find(existing => existing.range === range); - - if (!existingRange) { - existingDep.push({ - range, - projects: [project] - }); - continue; - } - - existingRange.projects.push(project); - } - } - - const duplicateRanges = Array.from(depRanges.entries()).filter(([, ranges]) => ranges.length > 1 && !ranges.every(rng => Object(_package_json__WEBPACK_IMPORTED_MODULE_6__["isLinkDependency"])(rng.range))).reduce((acc, [dep, ranges]) => [...acc, dep, ...ranges.map(({ - range, - projects - }) => ` ${range} => ${projects.map(p => p.name).join(', ')}`)], []).join('\n '); - - if (duplicateRanges) { - _log__WEBPACK_IMPORTED_MODULE_5__["log"].error(dedent__WEBPACK_IMPORTED_MODULE_1___default.a` - - [single_version_dependencies] Multiple version ranges for the same dependency - were found declared across different package.json files. Please consolidate - those to match across all package.json files. Different versions for the - same dependency is not supported. - - If you have questions about this please reach out to the operations team. - - The conflicting dependencies are: - - ${duplicateRanges} - `); - process.exit(1); - } // look for packages that have the the `kibana.devOnly` flag in their package.json - // and make sure they aren't included in the production dependencies of Kibana - - - const devOnlyProjectsInProduction = getDevOnlyProductionDepsTree(kbn, 'kibana'); - - if (devOnlyProjectsInProduction) { - _log__WEBPACK_IMPORTED_MODULE_5__["log"].error(dedent__WEBPACK_IMPORTED_MODULE_1___default.a` - Some of the packages in the production dependency chain for Kibana and X-Pack are - flagged with "kibana.devOnly" in their package.json. Please check changes made to - packages and their dependencies to ensure they don't end up in production. - - The devOnly dependencies that are being dependend on in production are: - - ${Object(_projects_tree__WEBPACK_IMPORTED_MODULE_7__["treeToString"])(devOnlyProjectsInProduction).split('\n').join('\n ')} - `); - process.exit(1); - } - - _log__WEBPACK_IMPORTED_MODULE_5__["log"].success('yarn.lock analysis completed without any issues'); -} + _log__WEBPACK_IMPORTED_MODULE_5__["log"].success('yarn.lock analysis completed without any issues'); +} function getDevOnlyProductionDepsTree(kbn, projectName) { const project = kbn.getProject(projectName); @@ -55483,7 +54809,7 @@ function getDevOnlyProductionDepsTree(kbn, projectName) { } /***/ }), -/* 543 */ +/* 534 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -55625,27 +54951,27 @@ function addProjectToTree(tree, pathParts, project) { } /***/ }), -/* 544 */ +/* 535 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony import */ var _get_cache_folders__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(545); +/* harmony import */ var _get_cache_folders__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(536); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getBazelDiskCacheFolder", function() { return _get_cache_folders__WEBPACK_IMPORTED_MODULE_0__["getBazelDiskCacheFolder"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getBazelRepositoryCacheFolder", function() { return _get_cache_folders__WEBPACK_IMPORTED_MODULE_0__["getBazelRepositoryCacheFolder"]; }); -/* harmony import */ var _install_tools__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(546); +/* harmony import */ var _install_tools__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(537); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isBazelBinAvailable", function() { return _install_tools__WEBPACK_IMPORTED_MODULE_1__["isBazelBinAvailable"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "installBazelTools", function() { return _install_tools__WEBPACK_IMPORTED_MODULE_1__["installBazelTools"]; }); -/* harmony import */ var _run__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(547); +/* harmony import */ var _run__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(538); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "runBazel", function() { return _run__WEBPACK_IMPORTED_MODULE_2__["runBazel"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "runIBazel", function() { return _run__WEBPACK_IMPORTED_MODULE_2__["runIBazel"]; }); -/* harmony import */ var _yarn_integrity__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(554); +/* harmony import */ var _yarn_integrity__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(545); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "removeYarnIntegrityFileIfExists", function() { return _yarn_integrity__WEBPACK_IMPORTED_MODULE_3__["removeYarnIntegrityFileIfExists"]; }); /* @@ -55661,7 +54987,7 @@ __webpack_require__.r(__webpack_exports__); /***/ }), -/* 545 */ +/* 536 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -55698,7 +55024,7 @@ async function getBazelRepositoryCacheFolder() { } /***/ }), -/* 546 */ +/* 537 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -55809,7 +55135,7 @@ async function installBazelTools(repoRootPath) { } /***/ }), -/* 547 */ +/* 538 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -55819,8 +55145,8 @@ __webpack_require__.r(__webpack_exports__); /* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(235); /* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(chalk__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9); -/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(548); -/* harmony import */ var _kbn_dev_utils_stdio__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(551); +/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(539); +/* harmony import */ var _kbn_dev_utils_stdio__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(542); /* harmony import */ var _kbn_dev_utils_stdio__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_kbn_dev_utils_stdio__WEBPACK_IMPORTED_MODULE_3__); /* harmony import */ var _child_process__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(342); /* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(341); @@ -55887,7 +55213,7 @@ async function runIBazel(bazelArgs, offline = false, runOpts = {}) { } /***/ }), -/* 548 */ +/* 539 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -56072,7 +55398,7 @@ __webpack_require__.r(__webpack_exports__); /* harmony import */ var _internal_operators_pairwise__WEBPACK_IMPORTED_MODULE_59__ = __webpack_require__(189); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "pairwise", function() { return _internal_operators_pairwise__WEBPACK_IMPORTED_MODULE_59__["pairwise"]; }); -/* harmony import */ var _internal_operators_partition__WEBPACK_IMPORTED_MODULE_60__ = __webpack_require__(549); +/* harmony import */ var _internal_operators_partition__WEBPACK_IMPORTED_MODULE_60__ = __webpack_require__(540); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "partition", function() { return _internal_operators_partition__WEBPACK_IMPORTED_MODULE_60__["partition"]; }); /* harmony import */ var _internal_operators_pluck__WEBPACK_IMPORTED_MODULE_61__ = __webpack_require__(190); @@ -56090,7 +55416,7 @@ __webpack_require__.r(__webpack_exports__); /* harmony import */ var _internal_operators_publishReplay__WEBPACK_IMPORTED_MODULE_65__ = __webpack_require__(194); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "publishReplay", function() { return _internal_operators_publishReplay__WEBPACK_IMPORTED_MODULE_65__["publishReplay"]; }); -/* harmony import */ var _internal_operators_race__WEBPACK_IMPORTED_MODULE_66__ = __webpack_require__(550); +/* harmony import */ var _internal_operators_race__WEBPACK_IMPORTED_MODULE_66__ = __webpack_require__(541); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "race", function() { return _internal_operators_race__WEBPACK_IMPORTED_MODULE_66__["race"]; }); /* harmony import */ var _internal_operators_raceWith__WEBPACK_IMPORTED_MODULE_67__ = __webpack_require__(195); @@ -56347,7 +55673,7 @@ __webpack_require__.r(__webpack_exports__); //# sourceMappingURL=index.js.map /***/ }), -/* 549 */ +/* 540 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -56365,7 +55691,7 @@ function partition(predicate, thisArg) { //# sourceMappingURL=partition.js.map /***/ }), -/* 550 */ +/* 541 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -56387,7 +55713,7 @@ function race() { //# sourceMappingURL=race.js.map /***/ }), -/* 551 */ +/* 542 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -56397,7 +55723,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); -var _observe_lines = __webpack_require__(552); +var _observe_lines = __webpack_require__(543); Object.keys(_observe_lines).forEach(function (key) { if (key === "default" || key === "__esModule") return; @@ -56410,7 +55736,7 @@ Object.keys(_observe_lines).forEach(function (key) { }); }); -var _observe_readable = __webpack_require__(553); +var _observe_readable = __webpack_require__(544); Object.keys(_observe_readable).forEach(function (key) { if (key === "default" || key === "__esModule") return; @@ -56424,7 +55750,7 @@ Object.keys(_observe_readable).forEach(function (key) { }); /***/ }), -/* 552 */ +/* 543 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -56437,9 +55763,9 @@ exports.observeLines = observeLines; var Rx = _interopRequireWildcard(__webpack_require__(9)); -var _operators = __webpack_require__(548); +var _operators = __webpack_require__(539); -var _observe_readable = __webpack_require__(553); +var _observe_readable = __webpack_require__(544); function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } @@ -56502,7 +55828,7 @@ function observeLines(readable) { } /***/ }), -/* 553 */ +/* 544 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -56515,7 +55841,7 @@ exports.observeReadable = observeReadable; var Rx = _interopRequireWildcard(__webpack_require__(9)); -var _operators = __webpack_require__(548); +var _operators = __webpack_require__(539); function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } @@ -56539,7 +55865,7 @@ function observeReadable(readable) { } /***/ }), -/* 554 */ +/* 545 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -56570,7 +55896,7 @@ async function removeYarnIntegrityFileIfExists(nodeModulesPath) { } /***/ }), -/* 555 */ +/* 546 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -56674,13 +56000,13 @@ async function setupRemoteCache(repoRootPath) { } /***/ }), -/* 556 */ +/* 547 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BuildCommand", function() { return BuildCommand; }); -/* harmony import */ var _utils_bazel__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(544); +/* harmony import */ var _utils_bazel__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(535); /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License @@ -56708,7 +56034,7 @@ const BuildCommand = { }; /***/ }), -/* 557 */ +/* 548 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -56718,11 +56044,11 @@ __webpack_require__.r(__webpack_exports__); /* harmony import */ var dedent__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(dedent__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var del__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(361); /* harmony import */ var del__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(del__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var ora__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(558); +/* harmony import */ var ora__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(549); /* harmony import */ var ora__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(ora__WEBPACK_IMPORTED_MODULE_2__); /* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4); /* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var _utils_bazel__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(544); +/* harmony import */ var _utils_bazel__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(535); /* harmony import */ var _utils_fs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(352); /* harmony import */ var _utils_log__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(341); /* @@ -56822,20 +56148,20 @@ const CleanCommand = { }; /***/ }), -/* 558 */ +/* 549 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const readline = __webpack_require__(559); -const chalk = __webpack_require__(560); -const cliCursor = __webpack_require__(563); -const cliSpinners = __webpack_require__(565); -const logSymbols = __webpack_require__(567); -const stripAnsi = __webpack_require__(573); -const wcwidth = __webpack_require__(575); -const isInteractive = __webpack_require__(579); -const MuteStream = __webpack_require__(580); +const readline = __webpack_require__(550); +const chalk = __webpack_require__(551); +const cliCursor = __webpack_require__(554); +const cliSpinners = __webpack_require__(556); +const logSymbols = __webpack_require__(558); +const stripAnsi = __webpack_require__(564); +const wcwidth = __webpack_require__(566); +const isInteractive = __webpack_require__(570); +const MuteStream = __webpack_require__(571); const TEXT = Symbol('text'); const PREFIX_TEXT = Symbol('prefixText'); @@ -57188,13 +56514,13 @@ module.exports.promise = (action, options) => { /***/ }), -/* 559 */ +/* 550 */ /***/ (function(module, exports) { module.exports = require("readline"); /***/ }), -/* 560 */ +/* 551 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -57204,7 +56530,7 @@ const {stdout: stdoutColor, stderr: stderrColor} = __webpack_require__(242); const { stringReplaceAll, stringEncaseCRLFWithFirstIndex -} = __webpack_require__(561); +} = __webpack_require__(552); // `supportsColor.level` → `ansiStyles.color[name]` mapping const levelMapping = [ @@ -57405,7 +56731,7 @@ const chalkTag = (chalk, ...strings) => { } if (template === undefined) { - template = __webpack_require__(562); + template = __webpack_require__(553); } return template(chalk, parts.join('')); @@ -57434,7 +56760,7 @@ module.exports = chalk; /***/ }), -/* 561 */ +/* 552 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -57480,7 +56806,7 @@ module.exports = { /***/ }), -/* 562 */ +/* 553 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -57621,12 +56947,12 @@ module.exports = (chalk, temporary) => { /***/ }), -/* 563 */ +/* 554 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const restoreCursor = __webpack_require__(564); +const restoreCursor = __webpack_require__(555); let isHidden = false; @@ -57663,7 +56989,7 @@ exports.toggle = (force, writableStream) => { /***/ }), -/* 564 */ +/* 555 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -57679,13 +57005,13 @@ module.exports = onetime(() => { /***/ }), -/* 565 */ +/* 556 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const spinners = Object.assign({}, __webpack_require__(566)); +const spinners = Object.assign({}, __webpack_require__(557)); const spinnersList = Object.keys(spinners); @@ -57703,18 +57029,18 @@ module.exports.default = spinners; /***/ }), -/* 566 */ +/* 557 */ /***/ (function(module) { module.exports = JSON.parse("{\"dots\":{\"interval\":80,\"frames\":[\"⠋\",\"⠙\",\"⠹\",\"⠸\",\"⠼\",\"⠴\",\"⠦\",\"⠧\",\"⠇\",\"⠏\"]},\"dots2\":{\"interval\":80,\"frames\":[\"⣾\",\"⣽\",\"⣻\",\"⢿\",\"⡿\",\"⣟\",\"⣯\",\"⣷\"]},\"dots3\":{\"interval\":80,\"frames\":[\"⠋\",\"⠙\",\"⠚\",\"⠞\",\"⠖\",\"⠦\",\"⠴\",\"⠲\",\"⠳\",\"⠓\"]},\"dots4\":{\"interval\":80,\"frames\":[\"⠄\",\"⠆\",\"⠇\",\"⠋\",\"⠙\",\"⠸\",\"⠰\",\"⠠\",\"⠰\",\"⠸\",\"⠙\",\"⠋\",\"⠇\",\"⠆\"]},\"dots5\":{\"interval\":80,\"frames\":[\"⠋\",\"⠙\",\"⠚\",\"⠒\",\"⠂\",\"⠂\",\"⠒\",\"⠲\",\"⠴\",\"⠦\",\"⠖\",\"⠒\",\"⠐\",\"⠐\",\"⠒\",\"⠓\",\"⠋\"]},\"dots6\":{\"interval\":80,\"frames\":[\"⠁\",\"⠉\",\"⠙\",\"⠚\",\"⠒\",\"⠂\",\"⠂\",\"⠒\",\"⠲\",\"⠴\",\"⠤\",\"⠄\",\"⠄\",\"⠤\",\"⠴\",\"⠲\",\"⠒\",\"⠂\",\"⠂\",\"⠒\",\"⠚\",\"⠙\",\"⠉\",\"⠁\"]},\"dots7\":{\"interval\":80,\"frames\":[\"⠈\",\"⠉\",\"⠋\",\"⠓\",\"⠒\",\"⠐\",\"⠐\",\"⠒\",\"⠖\",\"⠦\",\"⠤\",\"⠠\",\"⠠\",\"⠤\",\"⠦\",\"⠖\",\"⠒\",\"⠐\",\"⠐\",\"⠒\",\"⠓\",\"⠋\",\"⠉\",\"⠈\"]},\"dots8\":{\"interval\":80,\"frames\":[\"⠁\",\"⠁\",\"⠉\",\"⠙\",\"⠚\",\"⠒\",\"⠂\",\"⠂\",\"⠒\",\"⠲\",\"⠴\",\"⠤\",\"⠄\",\"⠄\",\"⠤\",\"⠠\",\"⠠\",\"⠤\",\"⠦\",\"⠖\",\"⠒\",\"⠐\",\"⠐\",\"⠒\",\"⠓\",\"⠋\",\"⠉\",\"⠈\",\"⠈\"]},\"dots9\":{\"interval\":80,\"frames\":[\"⢹\",\"⢺\",\"⢼\",\"⣸\",\"⣇\",\"⡧\",\"⡗\",\"⡏\"]},\"dots10\":{\"interval\":80,\"frames\":[\"⢄\",\"⢂\",\"⢁\",\"⡁\",\"⡈\",\"⡐\",\"⡠\"]},\"dots11\":{\"interval\":100,\"frames\":[\"⠁\",\"⠂\",\"⠄\",\"⡀\",\"⢀\",\"⠠\",\"⠐\",\"⠈\"]},\"dots12\":{\"interval\":80,\"frames\":[\"⢀⠀\",\"⡀⠀\",\"⠄⠀\",\"⢂⠀\",\"⡂⠀\",\"⠅⠀\",\"⢃⠀\",\"⡃⠀\",\"⠍⠀\",\"⢋⠀\",\"⡋⠀\",\"⠍⠁\",\"⢋⠁\",\"⡋⠁\",\"⠍⠉\",\"⠋⠉\",\"⠋⠉\",\"⠉⠙\",\"⠉⠙\",\"⠉⠩\",\"⠈⢙\",\"⠈⡙\",\"⢈⠩\",\"⡀⢙\",\"⠄⡙\",\"⢂⠩\",\"⡂⢘\",\"⠅⡘\",\"⢃⠨\",\"⡃⢐\",\"⠍⡐\",\"⢋⠠\",\"⡋⢀\",\"⠍⡁\",\"⢋⠁\",\"⡋⠁\",\"⠍⠉\",\"⠋⠉\",\"⠋⠉\",\"⠉⠙\",\"⠉⠙\",\"⠉⠩\",\"⠈⢙\",\"⠈⡙\",\"⠈⠩\",\"⠀⢙\",\"⠀⡙\",\"⠀⠩\",\"⠀⢘\",\"⠀⡘\",\"⠀⠨\",\"⠀⢐\",\"⠀⡐\",\"⠀⠠\",\"⠀⢀\",\"⠀⡀\"]},\"dots8Bit\":{\"interval\":80,\"frames\":[\"⠀\",\"⠁\",\"⠂\",\"⠃\",\"⠄\",\"⠅\",\"⠆\",\"⠇\",\"⡀\",\"⡁\",\"⡂\",\"⡃\",\"⡄\",\"⡅\",\"⡆\",\"⡇\",\"⠈\",\"⠉\",\"⠊\",\"⠋\",\"⠌\",\"⠍\",\"⠎\",\"⠏\",\"⡈\",\"⡉\",\"⡊\",\"⡋\",\"⡌\",\"⡍\",\"⡎\",\"⡏\",\"⠐\",\"⠑\",\"⠒\",\"⠓\",\"⠔\",\"⠕\",\"⠖\",\"⠗\",\"⡐\",\"⡑\",\"⡒\",\"⡓\",\"⡔\",\"⡕\",\"⡖\",\"⡗\",\"⠘\",\"⠙\",\"⠚\",\"⠛\",\"⠜\",\"⠝\",\"⠞\",\"⠟\",\"⡘\",\"⡙\",\"⡚\",\"⡛\",\"⡜\",\"⡝\",\"⡞\",\"⡟\",\"⠠\",\"⠡\",\"⠢\",\"⠣\",\"⠤\",\"⠥\",\"⠦\",\"⠧\",\"⡠\",\"⡡\",\"⡢\",\"⡣\",\"⡤\",\"⡥\",\"⡦\",\"⡧\",\"⠨\",\"⠩\",\"⠪\",\"⠫\",\"⠬\",\"⠭\",\"⠮\",\"⠯\",\"⡨\",\"⡩\",\"⡪\",\"⡫\",\"⡬\",\"⡭\",\"⡮\",\"⡯\",\"⠰\",\"⠱\",\"⠲\",\"⠳\",\"⠴\",\"⠵\",\"⠶\",\"⠷\",\"⡰\",\"⡱\",\"⡲\",\"⡳\",\"⡴\",\"⡵\",\"⡶\",\"⡷\",\"⠸\",\"⠹\",\"⠺\",\"⠻\",\"⠼\",\"⠽\",\"⠾\",\"⠿\",\"⡸\",\"⡹\",\"⡺\",\"⡻\",\"⡼\",\"⡽\",\"⡾\",\"⡿\",\"⢀\",\"⢁\",\"⢂\",\"⢃\",\"⢄\",\"⢅\",\"⢆\",\"⢇\",\"⣀\",\"⣁\",\"⣂\",\"⣃\",\"⣄\",\"⣅\",\"⣆\",\"⣇\",\"⢈\",\"⢉\",\"⢊\",\"⢋\",\"⢌\",\"⢍\",\"⢎\",\"⢏\",\"⣈\",\"⣉\",\"⣊\",\"⣋\",\"⣌\",\"⣍\",\"⣎\",\"⣏\",\"⢐\",\"⢑\",\"⢒\",\"⢓\",\"⢔\",\"⢕\",\"⢖\",\"⢗\",\"⣐\",\"⣑\",\"⣒\",\"⣓\",\"⣔\",\"⣕\",\"⣖\",\"⣗\",\"⢘\",\"⢙\",\"⢚\",\"⢛\",\"⢜\",\"⢝\",\"⢞\",\"⢟\",\"⣘\",\"⣙\",\"⣚\",\"⣛\",\"⣜\",\"⣝\",\"⣞\",\"⣟\",\"⢠\",\"⢡\",\"⢢\",\"⢣\",\"⢤\",\"⢥\",\"⢦\",\"⢧\",\"⣠\",\"⣡\",\"⣢\",\"⣣\",\"⣤\",\"⣥\",\"⣦\",\"⣧\",\"⢨\",\"⢩\",\"⢪\",\"⢫\",\"⢬\",\"⢭\",\"⢮\",\"⢯\",\"⣨\",\"⣩\",\"⣪\",\"⣫\",\"⣬\",\"⣭\",\"⣮\",\"⣯\",\"⢰\",\"⢱\",\"⢲\",\"⢳\",\"⢴\",\"⢵\",\"⢶\",\"⢷\",\"⣰\",\"⣱\",\"⣲\",\"⣳\",\"⣴\",\"⣵\",\"⣶\",\"⣷\",\"⢸\",\"⢹\",\"⢺\",\"⢻\",\"⢼\",\"⢽\",\"⢾\",\"⢿\",\"⣸\",\"⣹\",\"⣺\",\"⣻\",\"⣼\",\"⣽\",\"⣾\",\"⣿\"]},\"line\":{\"interval\":130,\"frames\":[\"-\",\"\\\\\",\"|\",\"/\"]},\"line2\":{\"interval\":100,\"frames\":[\"⠂\",\"-\",\"–\",\"—\",\"–\",\"-\"]},\"pipe\":{\"interval\":100,\"frames\":[\"┤\",\"┘\",\"┴\",\"└\",\"├\",\"┌\",\"┬\",\"┐\"]},\"simpleDots\":{\"interval\":400,\"frames\":[\". \",\".. \",\"...\",\" \"]},\"simpleDotsScrolling\":{\"interval\":200,\"frames\":[\". \",\".. \",\"...\",\" ..\",\" .\",\" \"]},\"star\":{\"interval\":70,\"frames\":[\"✶\",\"✸\",\"✹\",\"✺\",\"✹\",\"✷\"]},\"star2\":{\"interval\":80,\"frames\":[\"+\",\"x\",\"*\"]},\"flip\":{\"interval\":70,\"frames\":[\"_\",\"_\",\"_\",\"-\",\"`\",\"`\",\"'\",\"´\",\"-\",\"_\",\"_\",\"_\"]},\"hamburger\":{\"interval\":100,\"frames\":[\"☱\",\"☲\",\"☴\"]},\"growVertical\":{\"interval\":120,\"frames\":[\"▁\",\"▃\",\"▄\",\"▅\",\"▆\",\"▇\",\"▆\",\"▅\",\"▄\",\"▃\"]},\"growHorizontal\":{\"interval\":120,\"frames\":[\"▏\",\"▎\",\"▍\",\"▌\",\"▋\",\"▊\",\"▉\",\"▊\",\"▋\",\"▌\",\"▍\",\"▎\"]},\"balloon\":{\"interval\":140,\"frames\":[\" \",\".\",\"o\",\"O\",\"@\",\"*\",\" \"]},\"balloon2\":{\"interval\":120,\"frames\":[\".\",\"o\",\"O\",\"°\",\"O\",\"o\",\".\"]},\"noise\":{\"interval\":100,\"frames\":[\"▓\",\"▒\",\"░\"]},\"bounce\":{\"interval\":120,\"frames\":[\"⠁\",\"⠂\",\"⠄\",\"⠂\"]},\"boxBounce\":{\"interval\":120,\"frames\":[\"▖\",\"▘\",\"▝\",\"▗\"]},\"boxBounce2\":{\"interval\":100,\"frames\":[\"▌\",\"▀\",\"▐\",\"▄\"]},\"triangle\":{\"interval\":50,\"frames\":[\"◢\",\"◣\",\"◤\",\"◥\"]},\"arc\":{\"interval\":100,\"frames\":[\"◜\",\"◠\",\"◝\",\"◞\",\"◡\",\"◟\"]},\"circle\":{\"interval\":120,\"frames\":[\"◡\",\"⊙\",\"◠\"]},\"squareCorners\":{\"interval\":180,\"frames\":[\"◰\",\"◳\",\"◲\",\"◱\"]},\"circleQuarters\":{\"interval\":120,\"frames\":[\"◴\",\"◷\",\"◶\",\"◵\"]},\"circleHalves\":{\"interval\":50,\"frames\":[\"◐\",\"◓\",\"◑\",\"◒\"]},\"squish\":{\"interval\":100,\"frames\":[\"╫\",\"╪\"]},\"toggle\":{\"interval\":250,\"frames\":[\"⊶\",\"⊷\"]},\"toggle2\":{\"interval\":80,\"frames\":[\"▫\",\"▪\"]},\"toggle3\":{\"interval\":120,\"frames\":[\"□\",\"■\"]},\"toggle4\":{\"interval\":100,\"frames\":[\"■\",\"□\",\"▪\",\"▫\"]},\"toggle5\":{\"interval\":100,\"frames\":[\"▮\",\"▯\"]},\"toggle6\":{\"interval\":300,\"frames\":[\"ဝ\",\"၀\"]},\"toggle7\":{\"interval\":80,\"frames\":[\"⦾\",\"⦿\"]},\"toggle8\":{\"interval\":100,\"frames\":[\"◍\",\"◌\"]},\"toggle9\":{\"interval\":100,\"frames\":[\"◉\",\"◎\"]},\"toggle10\":{\"interval\":100,\"frames\":[\"㊂\",\"㊀\",\"㊁\"]},\"toggle11\":{\"interval\":50,\"frames\":[\"⧇\",\"⧆\"]},\"toggle12\":{\"interval\":120,\"frames\":[\"☗\",\"☖\"]},\"toggle13\":{\"interval\":80,\"frames\":[\"=\",\"*\",\"-\"]},\"arrow\":{\"interval\":100,\"frames\":[\"←\",\"↖\",\"↑\",\"↗\",\"→\",\"↘\",\"↓\",\"↙\"]},\"arrow2\":{\"interval\":80,\"frames\":[\"⬆️ \",\"↗️ \",\"➡️ \",\"↘️ \",\"⬇️ \",\"↙️ \",\"⬅️ \",\"↖️ \"]},\"arrow3\":{\"interval\":120,\"frames\":[\"▹▹▹▹▹\",\"▸▹▹▹▹\",\"▹▸▹▹▹\",\"▹▹▸▹▹\",\"▹▹▹▸▹\",\"▹▹▹▹▸\"]},\"bouncingBar\":{\"interval\":80,\"frames\":[\"[ ]\",\"[= ]\",\"[== ]\",\"[=== ]\",\"[ ===]\",\"[ ==]\",\"[ =]\",\"[ ]\",\"[ =]\",\"[ ==]\",\"[ ===]\",\"[====]\",\"[=== ]\",\"[== ]\",\"[= ]\"]},\"bouncingBall\":{\"interval\":80,\"frames\":[\"( ● )\",\"( ● )\",\"( ● )\",\"( ● )\",\"( ●)\",\"( ● )\",\"( ● )\",\"( ● )\",\"( ● )\",\"(● )\"]},\"smiley\":{\"interval\":200,\"frames\":[\"😄 \",\"😝 \"]},\"monkey\":{\"interval\":300,\"frames\":[\"🙈 \",\"🙈 \",\"🙉 \",\"🙊 \"]},\"hearts\":{\"interval\":100,\"frames\":[\"💛 \",\"💙 \",\"💜 \",\"💚 \",\"❤️ \"]},\"clock\":{\"interval\":100,\"frames\":[\"🕛 \",\"🕐 \",\"🕑 \",\"🕒 \",\"🕓 \",\"🕔 \",\"🕕 \",\"🕖 \",\"🕗 \",\"🕘 \",\"🕙 \",\"🕚 \"]},\"earth\":{\"interval\":180,\"frames\":[\"🌍 \",\"🌎 \",\"🌏 \"]},\"material\":{\"interval\":17,\"frames\":[\"█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁\",\"██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁\",\"███▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁\",\"████▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁\",\"██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁\",\"██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁\",\"███████▁▁▁▁▁▁▁▁▁▁▁▁▁\",\"████████▁▁▁▁▁▁▁▁▁▁▁▁\",\"█████████▁▁▁▁▁▁▁▁▁▁▁\",\"█████████▁▁▁▁▁▁▁▁▁▁▁\",\"██████████▁▁▁▁▁▁▁▁▁▁\",\"███████████▁▁▁▁▁▁▁▁▁\",\"█████████████▁▁▁▁▁▁▁\",\"██████████████▁▁▁▁▁▁\",\"██████████████▁▁▁▁▁▁\",\"▁██████████████▁▁▁▁▁\",\"▁██████████████▁▁▁▁▁\",\"▁██████████████▁▁▁▁▁\",\"▁▁██████████████▁▁▁▁\",\"▁▁▁██████████████▁▁▁\",\"▁▁▁▁█████████████▁▁▁\",\"▁▁▁▁██████████████▁▁\",\"▁▁▁▁██████████████▁▁\",\"▁▁▁▁▁██████████████▁\",\"▁▁▁▁▁██████████████▁\",\"▁▁▁▁▁██████████████▁\",\"▁▁▁▁▁▁██████████████\",\"▁▁▁▁▁▁██████████████\",\"▁▁▁▁▁▁▁█████████████\",\"▁▁▁▁▁▁▁█████████████\",\"▁▁▁▁▁▁▁▁████████████\",\"▁▁▁▁▁▁▁▁████████████\",\"▁▁▁▁▁▁▁▁▁███████████\",\"▁▁▁▁▁▁▁▁▁███████████\",\"▁▁▁▁▁▁▁▁▁▁██████████\",\"▁▁▁▁▁▁▁▁▁▁██████████\",\"▁▁▁▁▁▁▁▁▁▁▁▁████████\",\"▁▁▁▁▁▁▁▁▁▁▁▁▁███████\",\"▁▁▁▁▁▁▁▁▁▁▁▁▁▁██████\",\"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████\",\"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████\",\"█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████\",\"██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███\",\"██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███\",\"███▁▁▁▁▁▁▁▁▁▁▁▁▁▁███\",\"████▁▁▁▁▁▁▁▁▁▁▁▁▁▁██\",\"█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█\",\"█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█\",\"██████▁▁▁▁▁▁▁▁▁▁▁▁▁█\",\"████████▁▁▁▁▁▁▁▁▁▁▁▁\",\"█████████▁▁▁▁▁▁▁▁▁▁▁\",\"█████████▁▁▁▁▁▁▁▁▁▁▁\",\"█████████▁▁▁▁▁▁▁▁▁▁▁\",\"█████████▁▁▁▁▁▁▁▁▁▁▁\",\"███████████▁▁▁▁▁▁▁▁▁\",\"████████████▁▁▁▁▁▁▁▁\",\"████████████▁▁▁▁▁▁▁▁\",\"██████████████▁▁▁▁▁▁\",\"██████████████▁▁▁▁▁▁\",\"▁██████████████▁▁▁▁▁\",\"▁██████████████▁▁▁▁▁\",\"▁▁▁█████████████▁▁▁▁\",\"▁▁▁▁▁████████████▁▁▁\",\"▁▁▁▁▁████████████▁▁▁\",\"▁▁▁▁▁▁███████████▁▁▁\",\"▁▁▁▁▁▁▁▁█████████▁▁▁\",\"▁▁▁▁▁▁▁▁█████████▁▁▁\",\"▁▁▁▁▁▁▁▁▁█████████▁▁\",\"▁▁▁▁▁▁▁▁▁█████████▁▁\",\"▁▁▁▁▁▁▁▁▁▁█████████▁\",\"▁▁▁▁▁▁▁▁▁▁▁████████▁\",\"▁▁▁▁▁▁▁▁▁▁▁████████▁\",\"▁▁▁▁▁▁▁▁▁▁▁▁███████▁\",\"▁▁▁▁▁▁▁▁▁▁▁▁███████▁\",\"▁▁▁▁▁▁▁▁▁▁▁▁▁███████\",\"▁▁▁▁▁▁▁▁▁▁▁▁▁███████\",\"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████\",\"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████\",\"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████\",\"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████\",\"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███\",\"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███\",\"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██\",\"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██\",\"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██\",\"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█\",\"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█\",\"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█\",\"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁\",\"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁\",\"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁\",\"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁\"]},\"moon\":{\"interval\":80,\"frames\":[\"🌑 \",\"🌒 \",\"🌓 \",\"🌔 \",\"🌕 \",\"🌖 \",\"🌗 \",\"🌘 \"]},\"runner\":{\"interval\":140,\"frames\":[\"🚶 \",\"🏃 \"]},\"pong\":{\"interval\":80,\"frames\":[\"▐⠂ ▌\",\"▐⠈ ▌\",\"▐ ⠂ ▌\",\"▐ ⠠ ▌\",\"▐ ⡀ ▌\",\"▐ ⠠ ▌\",\"▐ ⠂ ▌\",\"▐ ⠈ ▌\",\"▐ ⠂ ▌\",\"▐ ⠠ ▌\",\"▐ ⡀ ▌\",\"▐ ⠠ ▌\",\"▐ ⠂ ▌\",\"▐ ⠈ ▌\",\"▐ ⠂▌\",\"▐ ⠠▌\",\"▐ ⡀▌\",\"▐ ⠠ ▌\",\"▐ ⠂ ▌\",\"▐ ⠈ ▌\",\"▐ ⠂ ▌\",\"▐ ⠠ ▌\",\"▐ ⡀ ▌\",\"▐ ⠠ ▌\",\"▐ ⠂ ▌\",\"▐ ⠈ ▌\",\"▐ ⠂ ▌\",\"▐ ⠠ ▌\",\"▐ ⡀ ▌\",\"▐⠠ ▌\"]},\"shark\":{\"interval\":120,\"frames\":[\"▐|\\\\____________▌\",\"▐_|\\\\___________▌\",\"▐__|\\\\__________▌\",\"▐___|\\\\_________▌\",\"▐____|\\\\________▌\",\"▐_____|\\\\_______▌\",\"▐______|\\\\______▌\",\"▐_______|\\\\_____▌\",\"▐________|\\\\____▌\",\"▐_________|\\\\___▌\",\"▐__________|\\\\__▌\",\"▐___________|\\\\_▌\",\"▐____________|\\\\▌\",\"▐____________/|▌\",\"▐___________/|_▌\",\"▐__________/|__▌\",\"▐_________/|___▌\",\"▐________/|____▌\",\"▐_______/|_____▌\",\"▐______/|______▌\",\"▐_____/|_______▌\",\"▐____/|________▌\",\"▐___/|_________▌\",\"▐__/|__________▌\",\"▐_/|___________▌\",\"▐/|____________▌\"]},\"dqpb\":{\"interval\":100,\"frames\":[\"d\",\"q\",\"p\",\"b\"]},\"weather\":{\"interval\":100,\"frames\":[\"☀️ \",\"☀️ \",\"☀️ \",\"🌤 \",\"⛅️ \",\"🌥 \",\"☁️ \",\"🌧 \",\"🌨 \",\"🌧 \",\"🌨 \",\"🌧 \",\"🌨 \",\"⛈ \",\"🌨 \",\"🌧 \",\"🌨 \",\"☁️ \",\"🌥 \",\"⛅️ \",\"🌤 \",\"☀️ \",\"☀️ \"]},\"christmas\":{\"interval\":400,\"frames\":[\"🌲\",\"🎄\"]},\"grenade\":{\"interval\":80,\"frames\":[\"، \",\"′ \",\" ´ \",\" ‾ \",\" ⸌\",\" ⸊\",\" |\",\" ⁎\",\" ⁕\",\" ෴ \",\" ⁓\",\" \",\" \",\" \"]},\"point\":{\"interval\":125,\"frames\":[\"∙∙∙\",\"●∙∙\",\"∙●∙\",\"∙∙●\",\"∙∙∙\"]},\"layer\":{\"interval\":150,\"frames\":[\"-\",\"=\",\"≡\"]},\"betaWave\":{\"interval\":80,\"frames\":[\"ρββββββ\",\"βρβββββ\",\"ββρββββ\",\"βββρβββ\",\"ββββρββ\",\"βββββρβ\",\"ββββββρ\"]},\"aesthetic\":{\"interval\":80,\"frames\":[\"▰▱▱▱▱▱▱\",\"▰▰▱▱▱▱▱\",\"▰▰▰▱▱▱▱\",\"▰▰▰▰▱▱▱\",\"▰▰▰▰▰▱▱\",\"▰▰▰▰▰▰▱\",\"▰▰▰▰▰▰▰\",\"▰▱▱▱▱▱▱\"]}}"); /***/ }), -/* 567 */ +/* 558 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const chalk = __webpack_require__(568); +const chalk = __webpack_require__(559); const isSupported = process.platform !== 'win32' || process.env.CI || process.env.TERM === 'xterm-256color'; @@ -57736,16 +57062,16 @@ module.exports = isSupported ? main : fallbacks; /***/ }), -/* 568 */ +/* 559 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; const escapeStringRegexp = __webpack_require__(478); -const ansiStyles = __webpack_require__(569); -const stdoutColor = __webpack_require__(570).stdout; +const ansiStyles = __webpack_require__(560); +const stdoutColor = __webpack_require__(561).stdout; -const template = __webpack_require__(572); +const template = __webpack_require__(563); const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); @@ -57971,7 +57297,7 @@ module.exports.default = module.exports; // For TypeScript /***/ }), -/* 569 */ +/* 560 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -58144,13 +57470,13 @@ Object.defineProperty(module, 'exports', { /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(237)(module))) /***/ }), -/* 570 */ +/* 561 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; const os = __webpack_require__(243); -const hasFlag = __webpack_require__(571); +const hasFlag = __webpack_require__(562); const env = process.env; @@ -58282,7 +57608,7 @@ module.exports = { /***/ }), -/* 571 */ +/* 562 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -58297,7 +57623,7 @@ module.exports = (flag, argv) => { /***/ }), -/* 572 */ +/* 563 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -58432,18 +57758,18 @@ module.exports = (chalk, tmp) => { /***/ }), -/* 573 */ +/* 564 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const ansiRegex = __webpack_require__(574); +const ansiRegex = __webpack_require__(565); module.exports = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; /***/ }), -/* 574 */ +/* 565 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -58460,14 +57786,14 @@ module.exports = ({onlyFirst = false} = {}) => { /***/ }), -/* 575 */ +/* 566 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var defaults = __webpack_require__(576) -var combining = __webpack_require__(578) +var defaults = __webpack_require__(567) +var combining = __webpack_require__(569) var DEFAULTS = { nul: 0, @@ -58566,10 +57892,10 @@ function bisearch(ucs) { /***/ }), -/* 576 */ +/* 567 */ /***/ (function(module, exports, __webpack_require__) { -var clone = __webpack_require__(577); +var clone = __webpack_require__(568); module.exports = function(options, defaults) { options = options || {}; @@ -58584,7 +57910,7 @@ module.exports = function(options, defaults) { }; /***/ }), -/* 577 */ +/* 568 */ /***/ (function(module, exports, __webpack_require__) { var clone = (function() { @@ -58756,7 +58082,7 @@ if ( true && module.exports) { /***/ }), -/* 578 */ +/* 569 */ /***/ (function(module, exports) { module.exports = [ @@ -58812,7 +58138,7 @@ module.exports = [ /***/ }), -/* 579 */ +/* 570 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -58828,7 +58154,7 @@ module.exports = ({stream = process.stdout} = {}) => { /***/ }), -/* 580 */ +/* 571 */ /***/ (function(module, exports, __webpack_require__) { var Stream = __webpack_require__(294) @@ -58979,7 +58305,7 @@ MuteStream.prototype.close = proxy('close') /***/ }), -/* 581 */ +/* 572 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -58989,11 +58315,11 @@ __webpack_require__.r(__webpack_exports__); /* harmony import */ var dedent__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(dedent__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var del__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(361); /* harmony import */ var del__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(del__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var ora__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(558); +/* harmony import */ var ora__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(549); /* harmony import */ var ora__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(ora__WEBPACK_IMPORTED_MODULE_2__); /* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4); /* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var _utils_bazel__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(544); +/* harmony import */ var _utils_bazel__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(535); /* harmony import */ var _utils_fs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(352); /* harmony import */ var _utils_log__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(341); /* @@ -59105,7 +58431,7 @@ const ResetCommand = { }; /***/ }), -/* 582 */ +/* 573 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -59115,7 +58441,7 @@ __webpack_require__.r(__webpack_exports__); /* harmony import */ var dedent__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(dedent__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var _utils_errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(462); /* harmony import */ var _utils_log__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(341); -/* harmony import */ var _utils_parallelize__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(583); +/* harmony import */ var _utils_parallelize__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(574); /* harmony import */ var _utils_projects__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(461); /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one @@ -59174,7 +58500,7 @@ const RunCommand = { }; /***/ }), -/* 583 */ +/* 574 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -59229,13 +58555,13 @@ async function parallelize(items, fn, concurrency = 4) { } /***/ }), -/* 584 */ +/* 575 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WatchCommand", function() { return WatchCommand; }); -/* harmony import */ var _utils_bazel__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(544); +/* harmony import */ var _utils_bazel__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(535); /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License @@ -59266,7 +58592,7 @@ const WatchCommand = { }; /***/ }), -/* 585 */ +/* 576 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -59274,11 +58600,16 @@ __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "runCommand", function() { return runCommand; }); /* harmony import */ var _kbn_dev_utils_ci_stats_reporter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(252); /* harmony import */ var _kbn_dev_utils_ci_stats_reporter__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_kbn_dev_utils_ci_stats_reporter__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _utils_errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(462); -/* harmony import */ var _utils_log__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(341); -/* harmony import */ var _utils_projects__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(461); -/* harmony import */ var _utils_projects_tree__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(543); -/* harmony import */ var _utils_kibana__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(586); +/* harmony import */ var _kbn_plugin_discovery__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(577); +/* harmony import */ var _kbn_plugin_discovery__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_kbn_plugin_discovery__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _utils_errors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(462); +/* harmony import */ var _utils_log__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(341); +/* harmony import */ var _utils_projects__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(461); +/* harmony import */ var _utils_projects_tree__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(534); +/* harmony import */ var _utils_regenerate_package_json__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(612); +/* harmony import */ var _utils_regenerate_synthetic_package_map__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(621); +/* harmony import */ var _utils_regenerate_base_tsconfig__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(623); +/* harmony import */ var _utils_kibana__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(624); function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } @@ -59298,14 +58629,77 @@ function _defineProperty(obj, key, value) { if (key in obj) { Object.definePrope + + + + process.env.CI_STATS_NESTED_TIMING = 'true'; async function runCommand(command, config) { const runStartTime = Date.now(); let kbn; + const timings = []; + + async function time(id, block) { + const start = Date.now(); + let success = true; + + try { + return await block(); + } catch (error) { + success = false; + throw error; + } finally { + timings.push({ + id, + ms: Date.now() - start, + meta: { + success + } + }); + } + } + + async function reportTimes(timingConfig, error) { + if (!kbn) { + // things are too broken to report remotely + return; + } + + const reporter = _kbn_dev_utils_ci_stats_reporter__WEBPACK_IMPORTED_MODULE_0__["CiStatsReporter"].fromEnv(_utils_log__WEBPACK_IMPORTED_MODULE_3__["log"]); + + try { + await reporter.timings({ + upstreamBranch: kbn.kibanaProject.json.branch, + // prevent loading @kbn/utils by passing null + kibanaUuid: kbn.getUuid() || null, + timings: [...timings.map(t => _objectSpread(_objectSpread({}, timingConfig), t)), { + group: timingConfig.group, + id: timingConfig.id, + ms: Date.now() - runStartTime, + meta: { + success: !error + } + }] + }); + } catch (e) { + // prevent hiding bootstrap errors + _utils_log__WEBPACK_IMPORTED_MODULE_3__["log"].error('failed to report timings:'); + _utils_log__WEBPACK_IMPORTED_MODULE_3__["log"].error(e); + } + } try { - _utils_log__WEBPACK_IMPORTED_MODULE_2__["log"].debug(`Running [${command.name}] command from [${config.rootPath}]`); - kbn = await _utils_kibana__WEBPACK_IMPORTED_MODULE_5__["Kibana"].loadFrom(config.rootPath); + _utils_log__WEBPACK_IMPORTED_MODULE_3__["log"].debug(`Running [${command.name}] command from [${config.rootPath}]`); + await time('regenerate package.json, synthetic-package map and tsconfig', async () => { + const plugins = Object(_kbn_plugin_discovery__WEBPACK_IMPORTED_MODULE_1__["simpleKibanaPlatformPluginDiscovery"])(Object(_kbn_plugin_discovery__WEBPACK_IMPORTED_MODULE_1__["getPluginSearchPaths"])({ + rootDir: config.rootPath, + oss: false, + examples: true, + testPlugins: true + }), []); + await Promise.all([Object(_utils_regenerate_package_json__WEBPACK_IMPORTED_MODULE_6__["regeneratePackageJson"])(config.rootPath), Object(_utils_regenerate_synthetic_package_map__WEBPACK_IMPORTED_MODULE_7__["regenerateSyntheticPackageMap"])(plugins, config.rootPath), Object(_utils_regenerate_base_tsconfig__WEBPACK_IMPORTED_MODULE_8__["regenerateBaseTsconfig"])(plugins, config.rootPath)]); + }); + kbn = await time('load Kibana project', async () => await _utils_kibana__WEBPACK_IMPORTED_MODULE_9__["Kibana"].loadFrom(config.rootPath)); const projects = kbn.getFilteredProjects({ skipKibanaPlugins: Boolean(config.options['skip-kibana-plugins']), ossOnly: Boolean(config.options.oss), @@ -59314,74 +58708,39 @@ async function runCommand(command, config) { }); if (projects.size === 0) { - _utils_log__WEBPACK_IMPORTED_MODULE_2__["log"].error(`There are no projects found. Double check project name(s) in '-i/--include' and '-e/--exclude' filters.`); + _utils_log__WEBPACK_IMPORTED_MODULE_3__["log"].error(`There are no projects found. Double check project name(s) in '-i/--include' and '-e/--exclude' filters.`); return process.exit(1); } - const projectGraph = Object(_utils_projects__WEBPACK_IMPORTED_MODULE_3__["buildProjectGraph"])(projects); - _utils_log__WEBPACK_IMPORTED_MODULE_2__["log"].debug(`Found ${projects.size.toString()} projects`); - _utils_log__WEBPACK_IMPORTED_MODULE_2__["log"].debug(Object(_utils_projects_tree__WEBPACK_IMPORTED_MODULE_4__["renderProjectsTree"])(config.rootPath, projects)); + const projectGraph = Object(_utils_projects__WEBPACK_IMPORTED_MODULE_4__["buildProjectGraph"])(projects); + _utils_log__WEBPACK_IMPORTED_MODULE_3__["log"].debug(`Found ${projects.size.toString()} projects`); + _utils_log__WEBPACK_IMPORTED_MODULE_3__["log"].debug(Object(_utils_projects_tree__WEBPACK_IMPORTED_MODULE_5__["renderProjectsTree"])(config.rootPath, projects)); await command.run(projects, projectGraph, _objectSpread(_objectSpread({}, config), {}, { kbn })); if (command.reportTiming) { - const reporter = _kbn_dev_utils_ci_stats_reporter__WEBPACK_IMPORTED_MODULE_0__["CiStatsReporter"].fromEnv(_utils_log__WEBPACK_IMPORTED_MODULE_2__["log"]); - await reporter.timings({ - upstreamBranch: kbn.kibanaProject.json.branch, - // prevent loading @kbn/utils by passing null - kibanaUuid: kbn.getUuid() || null, - timings: [{ - group: command.reportTiming.group, - id: command.reportTiming.id, - ms: Date.now() - runStartTime, - meta: { - success: true - } - }] - }); + await reportTimes(command.reportTiming); } } catch (error) { if (command.reportTiming) { - // if we don't have a kbn object then things are too broken to report on - if (kbn) { - try { - const reporter = _kbn_dev_utils_ci_stats_reporter__WEBPACK_IMPORTED_MODULE_0__["CiStatsReporter"].fromEnv(_utils_log__WEBPACK_IMPORTED_MODULE_2__["log"]); - await reporter.timings({ - upstreamBranch: kbn.kibanaProject.json.branch, - // prevent loading @kbn/utils by passing null - kibanaUuid: kbn.getUuid() || null, - timings: [{ - group: command.reportTiming.group, - id: command.reportTiming.id, - ms: Date.now() - runStartTime, - meta: { - success: false - } - }] - }); - } catch (e) { - // prevent hiding bootstrap errors - _utils_log__WEBPACK_IMPORTED_MODULE_2__["log"].error('failed to report timings:'); - _utils_log__WEBPACK_IMPORTED_MODULE_2__["log"].error(e); - } - } + await reportTimes(command.reportTiming, error); } - _utils_log__WEBPACK_IMPORTED_MODULE_2__["log"].error(`[${command.name}] failed:`); + _utils_log__WEBPACK_IMPORTED_MODULE_3__["log"].error(`[${command.name}] failed:`); - if (error instanceof _utils_errors__WEBPACK_IMPORTED_MODULE_1__["CliError"]) { - _utils_log__WEBPACK_IMPORTED_MODULE_2__["log"].error(error.message); + if (error instanceof _utils_errors__WEBPACK_IMPORTED_MODULE_2__["CliError"]) { + _utils_log__WEBPACK_IMPORTED_MODULE_3__["log"].error(error.message); const metaOutput = Object.entries(error.meta).map(([key, value]) => `${key}: ${value}`).join('\n'); if (metaOutput) { - _utils_log__WEBPACK_IMPORTED_MODULE_2__["log"].info('Additional debugging info:\n'); - _utils_log__WEBPACK_IMPORTED_MODULE_2__["log"].indent(2); - _utils_log__WEBPACK_IMPORTED_MODULE_2__["log"].info(metaOutput); - _utils_log__WEBPACK_IMPORTED_MODULE_2__["log"].indent(-2); + _utils_log__WEBPACK_IMPORTED_MODULE_3__["log"].info('Additional debugging info:\n'); + _utils_log__WEBPACK_IMPORTED_MODULE_3__["log"].indent(2); + _utils_log__WEBPACK_IMPORTED_MODULE_3__["log"].info(metaOutput); + _utils_log__WEBPACK_IMPORTED_MODULE_3__["log"].indent(-2); } } else { - _utils_log__WEBPACK_IMPORTED_MODULE_2__["log"].error(error); + _utils_log__WEBPACK_IMPORTED_MODULE_3__["log"].error(error); } process.exit(1); @@ -59397,271 +58756,196 @@ function toArray(value) { } /***/ }), -/* 586 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 577 */ +/***/ (function(module, exports, __webpack_require__) { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Kibana", function() { return Kibana; }); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(253); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var multimatch__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(587); -/* harmony import */ var multimatch__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(multimatch__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var is_path_inside__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(454); -/* harmony import */ var is_path_inside__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(is_path_inside__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var _yarn_lock__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(530); -/* harmony import */ var _projects__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(461); -/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(590); -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } - -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - - - - - - -/** - * Helper class for dealing with a set of projects as children of - * the Kibana project. The kbn/pm is currently implemented to be - * more generic, where everything is an operation of generic projects, - * but that leads to exceptions where we need the kibana project and - * do things like `project.get('kibana')!`. - * - * Using this helper we can restructre the generic list of projects - * as a Kibana object which encapulates all the projects in the - * workspace and knows about the root Kibana project. - */ - -class Kibana { - static async loadFrom(rootPath) { - return new Kibana(await Object(_projects__WEBPACK_IMPORTED_MODULE_5__["getProjects"])(rootPath, Object(_config__WEBPACK_IMPORTED_MODULE_6__["getProjectPaths"])({ - rootPath - }))); - } - - constructor(allWorkspaceProjects) { - this.allWorkspaceProjects = allWorkspaceProjects; - _defineProperty(this, "kibanaProject", void 0); +Object.defineProperty(exports, "__esModule", { + value: true +}); - const kibanaProject = allWorkspaceProjects.get('kibana'); +var _parse_kibana_platform_plugin = __webpack_require__(578); - if (!kibanaProject) { - throw new TypeError('Unable to create Kibana object without all projects, including the Kibana project.'); +Object.keys(_parse_kibana_platform_plugin).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _parse_kibana_platform_plugin[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _parse_kibana_platform_plugin[key]; } + }); +}); - this.kibanaProject = kibanaProject; - } - /** make an absolute path by resolving subPath relative to the kibana repo */ +var _plugin_search_paths = __webpack_require__(581); +Object.keys(_plugin_search_paths).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _plugin_search_paths[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _plugin_search_paths[key]; + } + }); +}); - getAbsolute(...subPath) { - return path__WEBPACK_IMPORTED_MODULE_0___default.a.resolve(this.kibanaProject.path, ...subPath); - } - /** convert an absolute path to a relative path, relative to the kibana repo */ +var _simple_kibana_platform_plugin_discovery = __webpack_require__(582); +Object.keys(_simple_kibana_platform_plugin_discovery).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _simple_kibana_platform_plugin_discovery[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _simple_kibana_platform_plugin_discovery[key]; + } + }); +}); - getRelative(absolute) { - return path__WEBPACK_IMPORTED_MODULE_0___default.a.relative(this.kibanaProject.path, absolute); - } - /** get a copy of the map of all projects in the kibana workspace */ +/***/ }), +/* 578 */ +/***/ (function(module, exports, __webpack_require__) { +"use strict"; - getAllProjects() { - return new Map(this.allWorkspaceProjects); - } - /** determine if a project with the given name exists */ +var _interopRequireDefault = __webpack_require__(7); - hasProject(name) { - return this.allWorkspaceProjects.has(name); - } - /** get a specific project, throws if the name is not known (use hasProject() first) */ +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.parseKibanaPlatformPlugin = parseKibanaPlatformPlugin; +var _path = _interopRequireDefault(__webpack_require__(4)); - getProject(name) { - const project = this.allWorkspaceProjects.get(name); +var _loadJsonFile = _interopRequireDefault(__webpack_require__(579)); - if (!project) { - throw new Error(`No package with name "${name}" in the workspace`); - } +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ +function isValidDepsDeclaration(input, type) { + if (typeof input === 'undefined') return []; - return project; + if (Array.isArray(input) && input.every(i => typeof i === 'string')) { + return input; } - /** get a project and all of the projects it depends on in a ProjectMap */ + throw new TypeError(`The "${type}" in plugin manifest should be an array of strings.`); +} - getProjectAndDeps(name) { - const project = this.getProject(name); - return Object(_projects__WEBPACK_IMPORTED_MODULE_5__["includeTransitiveProjects"])([project], this.allWorkspaceProjects); +function parseKibanaPlatformPlugin(manifestPath) { + if (!_path.default.isAbsolute(manifestPath)) { + throw new TypeError('expected new platform manifest path to be absolute'); } - /** filter the projects to just those matching certain paths/include/exclude tags */ - - getFilteredProjects(options) { - const allProjects = this.getAllProjects(); - const filteredProjects = new Map(); - const pkgJsonPaths = Array.from(allProjects.values()).map(p => p.packageJsonLocation); - const filteredPkgJsonGlobs = Object(_config__WEBPACK_IMPORTED_MODULE_6__["getProjectPaths"])(_objectSpread(_objectSpread({}, options), {}, { - rootPath: this.kibanaProject.path - })).map(g => path__WEBPACK_IMPORTED_MODULE_0___default.a.resolve(g, 'package.json')); - const matchingPkgJsonPaths = multimatch__WEBPACK_IMPORTED_MODULE_2___default()(pkgJsonPaths, filteredPkgJsonGlobs); - - for (const project of allProjects.values()) { - const pathMatches = matchingPkgJsonPaths.includes(project.packageJsonLocation); - const notExcluded = !options.exclude.includes(project.name); - const isIncluded = !options.include.length || options.include.includes(project.name); - - if (pathMatches && notExcluded && isIncluded) { - filteredProjects.set(project.name, project); - } - } + const manifest = _loadJsonFile.default.sync(manifestPath); - return filteredProjects; + if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) { + throw new TypeError('expected new platform plugin manifest to be a JSON encoded object'); } - isPartOfRepo(project) { - return project.path === this.kibanaProject.path || is_path_inside__WEBPACK_IMPORTED_MODULE_3___default()(project.path, this.kibanaProject.path); + if (typeof manifest.id !== 'string') { + throw new TypeError('expected new platform plugin manifest to have a string id'); } - isOutsideRepo(project) { - return !this.isPartOfRepo(project); + if (typeof manifest.version !== 'string') { + throw new TypeError('expected new platform plugin manifest to have a string version'); } - resolveAllProductionDependencies(yarnLock, log) { - const kibanaDeps = Object(_yarn_lock__WEBPACK_IMPORTED_MODULE_4__["resolveDepsForProject"])({ - project: this.kibanaProject, - yarnLock, - kbn: this, - includeDependentProject: true, - productionDepsOnly: true, - log - }); - const xpackDeps = Object(_yarn_lock__WEBPACK_IMPORTED_MODULE_4__["resolveDepsForProject"])({ - project: this.getProject('x-pack'), - yarnLock, - kbn: this, - includeDependentProject: true, - productionDepsOnly: true, - log - }); - return new Map([...kibanaDeps.entries(), ...xpackDeps.entries()]); + if (!manifest.owner || typeof manifest.owner.name !== 'string') { + throw new TypeError(`Expected plugin ${manifest.id} manifest to have an owner with name specified (${manifestPath})`); } - getUuid() { - try { - return fs__WEBPACK_IMPORTED_MODULE_1___default.a.readFileSync(this.getAbsolute('data/uuid'), 'utf-8').trim(); - } catch (error) { - if (error.code === 'ENOENT') { - return undefined; - } - - throw error; + return { + directory: _path.default.dirname(manifestPath), + manifestPath, + manifest: { ...manifest, + ui: !!manifest.ui, + server: !!manifest.server, + id: manifest.id, + version: manifest.version, + kibanaVersion: manifest.kibanaVersion || manifest.version, + serviceFolders: manifest.serviceFolders || [], + owner: manifest.owner, + description: manifest.description, + enabledOnAnonymousPages: Boolean(manifest.enabledOnAnonymousPages), + requiredPlugins: isValidDepsDeclaration(manifest.requiredPlugins, 'requiredPlugins'), + optionalPlugins: isValidDepsDeclaration(manifest.optionalPlugins, 'optionalPlugins'), + requiredBundles: isValidDepsDeclaration(manifest.requiredBundles, 'requiredBundles'), + extraPublicDirs: isValidDepsDeclaration(manifest.extraPublicDirs, 'extraPublicDirs') } - } - + }; } /***/ }), -/* 587 */ +/* 579 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const minimatch = __webpack_require__(368); -const arrayUnion = __webpack_require__(363); -const arrayDiffer = __webpack_require__(588); -const arrify = __webpack_require__(589); +const path = __webpack_require__(4); +const {promisify} = __webpack_require__(234); +const fs = __webpack_require__(354); +const stripBom = __webpack_require__(580); +const parseJson = __webpack_require__(466); -module.exports = (list, patterns, options = {}) => { - list = arrify(list); - patterns = arrify(patterns); +const parse = (data, filePath, options = {}) => { + data = stripBom(data); - if (list.length === 0 || patterns.length === 0) { - return []; + if (typeof options.beforeParse === 'function') { + data = options.beforeParse(data); } - return patterns.reduce((result, pattern) => { - let process = arrayUnion; - - if (pattern[0] === '!') { - pattern = pattern.slice(1); - process = arrayDiffer; - } - - return process(result, minimatch.match(list, pattern, options)); - }, []); -}; - - -/***/ }), -/* 588 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const arrayDiffer = (array, ...values) => { - const rest = new Set([].concat(...values)); - return array.filter(element => !rest.has(element)); + return parseJson(data, options.reviver, path.relative(process.cwd(), filePath)); }; -module.exports = arrayDiffer; +module.exports = async (filePath, options) => parse(await promisify(fs.readFile)(filePath, 'utf8'), filePath, options); +module.exports.sync = (filePath, options) => parse(fs.readFileSync(filePath, 'utf8'), filePath, options); /***/ }), -/* 589 */ +/* 580 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const arrify = value => { - if (value === null || value === undefined) { - return []; - } - - if (Array.isArray(value)) { - return value; - } - - if (typeof value === 'string') { - return [value]; +module.exports = string => { + if (typeof string !== 'string') { + throw new TypeError(`Expected a string, got ${typeof string}`); } - if (typeof value[Symbol.iterator] === 'function') { - return [...value]; + // Catches EFBBBF (UTF-8 BOM) because the buffer-to-string + // conversion translates it to FEFF (UTF-16 BOM) + if (string.charCodeAt(0) === 0xFEFF) { + return string.slice(1); } - return [value]; + return string; }; -module.exports = arrify; - /***/ }), -/* 590 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 581 */ +/***/ (function(module, exports, __webpack_require__) { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getProjectPaths", function() { return getProjectPaths; }); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_0__); + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getPluginSearchPaths = getPluginSearchPaths; + +var _path = __webpack_require__(4); + /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License @@ -59669,61 +58953,36 @@ __webpack_require__.r(__webpack_exports__); * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ +function getPluginSearchPaths({ + rootDir, + oss, + examples, + testPlugins +}) { + return [(0, _path.resolve)(rootDir, 'src', 'plugins'), ...(oss ? [] : [(0, _path.resolve)(rootDir, 'x-pack', 'plugins')]), (0, _path.resolve)(rootDir, 'plugins'), ...(examples ? [(0, _path.resolve)(rootDir, 'examples')] : []), ...(examples && !oss ? [(0, _path.resolve)(rootDir, 'x-pack', 'examples')] : []), (0, _path.resolve)(rootDir, '..', 'kibana-extra'), ...(testPlugins ? [(0, _path.resolve)(rootDir, 'test/analytics/__fixtures__/plugins'), (0, _path.resolve)(rootDir, 'test/plugin_functional/plugins'), (0, _path.resolve)(rootDir, 'test/interpreter_functional/plugins'), (0, _path.resolve)(rootDir, 'test/common/fixtures/plugins')] : []), ...(testPlugins && !oss ? [(0, _path.resolve)(rootDir, 'x-pack/test/plugin_functional/plugins'), (0, _path.resolve)(rootDir, 'x-pack/test/functional_with_es_ssl/fixtures/plugins'), (0, _path.resolve)(rootDir, 'x-pack/test/alerting_api_integration/plugins'), (0, _path.resolve)(rootDir, 'x-pack/test/plugin_api_integration/plugins'), (0, _path.resolve)(rootDir, 'x-pack/test/plugin_api_perf/plugins'), (0, _path.resolve)(rootDir, 'x-pack/test/licensing_plugin/plugins'), (0, _path.resolve)(rootDir, 'x-pack/test/usage_collection/plugins'), (0, _path.resolve)(rootDir, 'x-pack/test/security_functional/fixtures/common')] : [])]; +} +/***/ }), +/* 582 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * Returns all the paths where plugins are located - */ -function getProjectPaths({ - rootPath, - ossOnly, - skipKibanaPlugins -}) { - const projectPaths = [rootPath, Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(rootPath, 'packages/*')]; // This is needed in order to install the dependencies for the declared - // plugin functional used in the selenium functional tests. - // As we are now using the webpack dll for the client vendors dependencies - // when we run the plugin functional tests against the distributable - // dependencies used by such plugins like @eui, react and react-dom can't - // be loaded from the dll as the context is different from the one declared - // into the webpack dll reference plugin. - // In anyway, have a plugin declaring their own dependencies is the - // correct and the expect behavior. +"use strict"; - projectPaths.push(Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(rootPath, 'test/plugin_functional/plugins/*')); - projectPaths.push(Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(rootPath, 'test/interpreter_functional/plugins/*')); - projectPaths.push(Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(rootPath, 'test/server_integration/__fixtures__/plugins/*')); - projectPaths.push(Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(rootPath, 'examples/*')); - if (!ossOnly) { - projectPaths.push(Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(rootPath, 'x-pack')); - projectPaths.push(Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(rootPath, 'x-pack/plugins/*')); - projectPaths.push(Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(rootPath, 'x-pack/legacy/plugins/*')); - projectPaths.push(Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(rootPath, 'x-pack/test/functional_with_es_ssl/fixtures/plugins/*')); - } +var _interopRequireDefault = __webpack_require__(7); - if (!skipKibanaPlugins) { - projectPaths.push(Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(rootPath, '../kibana-extra/*')); - projectPaths.push(Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(rootPath, '../kibana-extra/*/packages/*')); - projectPaths.push(Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(rootPath, '../kibana-extra/*/plugins/*')); - projectPaths.push(Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(rootPath, 'plugins/*')); - projectPaths.push(Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(rootPath, 'plugins/*/packages/*')); - projectPaths.push(Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(rootPath, 'plugins/*/plugins/*')); - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.simpleKibanaPlatformPluginDiscovery = simpleKibanaPlatformPluginDiscovery; - return projectPaths; -} +var _path = _interopRequireDefault(__webpack_require__(4)); -/***/ }), -/* 591 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +var _globby = _interopRequireDefault(__webpack_require__(583)); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _build_bazel_production_projects__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(592); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "buildBazelProductionProjects", function() { return _build_bazel_production_projects__WEBPACK_IMPORTED_MODULE_0__["buildBazelProductionProjects"]; }); +var _normalizePath = _interopRequireDefault(__webpack_require__(611)); -/* harmony import */ var _build_non_bazel_production_projects__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(833); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "buildNonBazelProductionProjects", function() { return _build_non_bazel_production_projects__WEBPACK_IMPORTED_MODULE_1__["buildNonBazelProductionProjects"]; }); +var _parse_kibana_platform_plugin = __webpack_require__(578); /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one @@ -59733,9161 +58992,8703 @@ __webpack_require__.r(__webpack_exports__); * Side Public License, v 1. */ +/** + * Helper to find the new platform plugins. + */ +function simpleKibanaPlatformPluginDiscovery(scanDirs, pluginPaths) { + const patterns = Array.from(new Set([// find kibana.json files up to 5 levels within the scan dir + ...scanDirs.reduce((acc, dir) => [...acc, _path.default.resolve(dir, '*/kibana.json'), _path.default.resolve(dir, '*/*/kibana.json'), _path.default.resolve(dir, '*/*/*/kibana.json'), _path.default.resolve(dir, '*/*/*/*/kibana.json'), _path.default.resolve(dir, '*/*/*/*/*/kibana.json')], []), ...pluginPaths.map(path => _path.default.resolve(path, `kibana.json`))])).map(path => (0, _normalizePath.default)(path)); + + const manifestPaths = _globby.default.sync(patterns, { + absolute: true + }).map(path => // absolute paths returned from globby are using normalize or + // something so the path separators are `/` even on windows, + // Path.resolve solves this + _path.default.resolve(path)); + return manifestPaths.map(_parse_kibana_platform_plugin.parseKibanaPlatformPlugin); +} /***/ }), -/* 592 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 583 */ +/***/ (function(module, exports, __webpack_require__) { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "buildBazelProductionProjects", function() { return buildBazelProductionProjects; }); -/* harmony import */ var cpy__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(593); -/* harmony import */ var cpy__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(cpy__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var globby__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(805); -/* harmony import */ var globby__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(globby__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var _build_non_bazel_production_projects__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(833); -/* harmony import */ var _utils_bazel__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(544); -/* harmony import */ var _utils_fs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(352); -/* harmony import */ var _utils_log__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(341); -/* harmony import */ var _utils_package_json__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(464); -/* harmony import */ var _utils_projects__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(461); -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ +const fs = __webpack_require__(253); +const arrayUnion = __webpack_require__(363); +const merge2 = __webpack_require__(364); +const fastGlob = __webpack_require__(584); +const dirGlob = __webpack_require__(447); +const gitignore = __webpack_require__(609); +const {FilterStream, UniqueStream} = __webpack_require__(610); +const DEFAULT_FILTER = () => false; +const isNegative = pattern => pattern[0] === '!'; +const assertPatternsInput = patterns => { + if (!patterns.every(pattern => typeof pattern === 'string')) { + throw new TypeError('Patterns must be a string or an array of strings'); + } +}; +const checkCwdOption = (options = {}) => { + if (!options.cwd) { + return; + } + let stat; + try { + stat = fs.statSync(options.cwd); + } catch { + return; + } + if (!stat.isDirectory()) { + throw new Error('The `cwd` option must be a path to a directory'); + } +}; +const getPathString = p => p.stats instanceof fs.Stats ? p.path : p; -async function buildBazelProductionProjects({ - kibanaRoot, - buildRoot, - onlyOSS -}) { - const projects = await Object(_utils_projects__WEBPACK_IMPORTED_MODULE_8__["getBazelProjectsOnly"])(await Object(_build_non_bazel_production_projects__WEBPACK_IMPORTED_MODULE_3__["getProductionProjects"])(kibanaRoot, onlyOSS)); - const projectNames = [...projects.values()].map(project => project.name); - _utils_log__WEBPACK_IMPORTED_MODULE_6__["log"].info(`Preparing Bazel projects production build for [${projectNames.join(', ')}]`); - await Object(_utils_bazel__WEBPACK_IMPORTED_MODULE_4__["runBazel"])(['build', '//packages:build']); - _utils_log__WEBPACK_IMPORTED_MODULE_6__["log"].info(`All Bazel projects production builds for [${projectNames.join(', ')}] are complete`); +const generateGlobTasks = (patterns, taskOptions) => { + patterns = arrayUnion([].concat(patterns)); + assertPatternsInput(patterns); + checkCwdOption(taskOptions); - for (const project of projects.values()) { - await copyToBuild(project, kibanaRoot, buildRoot); - await applyCorrectPermissions(project, kibanaRoot, buildRoot); - } -} -/** - * Copy all the project's files from its Bazel dist directory into the - * project build folder. - * - * When copying all the files into the build, we exclude `node_modules` because - * we want the Kibana build to be responsible for actually installing all - * dependencies. The primary reason for allowing the Kibana build process to - * manage dependencies is that it will "dedupe" them, so we don't include - * unnecessary copies of dependencies. We also exclude every related Bazel build - * files in order to get the most cleaner package module we can in the final distributable. - */ - -async function copyToBuild(project, kibanaRoot, buildRoot) { - // We want the package to have the same relative location within the build - const relativeProjectPath = Object(path__WEBPACK_IMPORTED_MODULE_2__["relative"])(kibanaRoot, project.path); - const buildProjectPath = Object(path__WEBPACK_IMPORTED_MODULE_2__["resolve"])(buildRoot, relativeProjectPath); - await cpy__WEBPACK_IMPORTED_MODULE_0___default()(['**/*'], buildProjectPath, { - cwd: Object(path__WEBPACK_IMPORTED_MODULE_2__["join"])(kibanaRoot, 'bazel-bin', 'packages', Object(path__WEBPACK_IMPORTED_MODULE_2__["basename"])(buildProjectPath), 'npm_module'), - dot: true, - onlyFiles: true, - parents: true - }); // If a project is using an intermediate build directory, we special-case our - // handling of `package.json`, as the project build process might have copied - // (a potentially modified) `package.json` into the intermediate build - // directory already. If so, we want to use that `package.json` as the basis - // for creating the production-ready `package.json`. If it's not present in - // the intermediate build, we fall back to using the project's already defined - // `package.json`. - - const packageJson = (await Object(_utils_fs__WEBPACK_IMPORTED_MODULE_5__["isFile"])(Object(path__WEBPACK_IMPORTED_MODULE_2__["join"])(buildProjectPath, 'package.json'))) ? await Object(_utils_package_json__WEBPACK_IMPORTED_MODULE_7__["readPackageJson"])(buildProjectPath) : project.json; - const preparedPackageJson = Object(_utils_package_json__WEBPACK_IMPORTED_MODULE_7__["createProductionPackageJson"])(packageJson); - await Object(_utils_package_json__WEBPACK_IMPORTED_MODULE_7__["writePackageJson"])(buildProjectPath, preparedPackageJson); -} - -async function applyCorrectPermissions(project, kibanaRoot, buildRoot) { - const relativeProjectPath = Object(path__WEBPACK_IMPORTED_MODULE_2__["relative"])(kibanaRoot, project.path); - const buildProjectPath = Object(path__WEBPACK_IMPORTED_MODULE_2__["resolve"])(buildRoot, relativeProjectPath); - const allPluginPaths = await globby__WEBPACK_IMPORTED_MODULE_1___default()([`**/*`], { - onlyFiles: false, - cwd: buildProjectPath, - dot: true - }); - - for (const pluginPath of allPluginPaths) { - const resolvedPluginPath = Object(path__WEBPACK_IMPORTED_MODULE_2__["resolve"])(buildProjectPath, pluginPath); - - if (await Object(_utils_fs__WEBPACK_IMPORTED_MODULE_5__["isFile"])(resolvedPluginPath)) { - await Object(_utils_fs__WEBPACK_IMPORTED_MODULE_5__["chmod"])(resolvedPluginPath, 0o644); - } - - if (await Object(_utils_fs__WEBPACK_IMPORTED_MODULE_5__["isDirectory"])(resolvedPluginPath)) { - await Object(_utils_fs__WEBPACK_IMPORTED_MODULE_5__["chmod"])(resolvedPluginPath, 0o755); - } - } -} + const globTasks = []; -/***/ }), -/* 593 */ -/***/ (function(module, exports, __webpack_require__) { + taskOptions = { + ignore: [], + expandDirectories: true, + ...taskOptions + }; -"use strict"; + for (const [index, pattern] of patterns.entries()) { + if (isNegative(pattern)) { + continue; + } -const EventEmitter = __webpack_require__(285); -const path = __webpack_require__(4); -const os = __webpack_require__(243); -const pMap = __webpack_require__(594); -const arrify = __webpack_require__(589); -const globby = __webpack_require__(597); -const hasGlob = __webpack_require__(789); -const cpFile = __webpack_require__(791); -const junk = __webpack_require__(801); -const pFilter = __webpack_require__(802); -const CpyError = __webpack_require__(804); + const ignore = patterns + .slice(index) + .filter(pattern => isNegative(pattern)) + .map(pattern => pattern.slice(1)); -const defaultOptions = { - ignoreJunk: true -}; + const options = { + ...taskOptions, + ignore: taskOptions.ignore.concat(ignore) + }; -class SourceFile { - constructor(relativePath, path) { - this.path = path; - this.relativePath = relativePath; - Object.freeze(this); + globTasks.push({pattern, options}); } - get name() { - return path.basename(this.relativePath); - } + return globTasks; +}; - get nameWithoutExtension() { - return path.basename(this.relativePath, path.extname(this.relativePath)); +const globDirs = (task, fn) => { + let options = {}; + if (task.options.cwd) { + options.cwd = task.options.cwd; } - get extension() { - return path.extname(this.relativePath).slice(1); + if (Array.isArray(task.options.expandDirectories)) { + options = { + ...options, + files: task.options.expandDirectories + }; + } else if (typeof task.options.expandDirectories === 'object') { + options = { + ...options, + ...task.options.expandDirectories + }; } -} - -const preprocessSourcePath = (source, options) => path.resolve(options.cwd ? options.cwd : process.cwd(), source); -const preprocessDestinationPath = (source, destination, options) => { - let basename = path.basename(source); + return fn(task.pattern, options); +}; - if (typeof options.rename === 'string') { - basename = options.rename; - } else if (typeof options.rename === 'function') { - basename = options.rename(basename); - } +const getPattern = (task, fn) => task.options.expandDirectories ? globDirs(task, fn) : [task.pattern]; - if (options.cwd) { - destination = path.resolve(options.cwd, destination); - } +const getFilterSync = options => { + return options && options.gitignore ? + gitignore.sync({cwd: options.cwd, ignore: options.ignore}) : + DEFAULT_FILTER; +}; - if (options.parents) { - const dirname = path.dirname(source); - const parsedDirectory = path.parse(dirname); - return path.join(destination, dirname.replace(parsedDirectory.root, path.sep), basename); +const globToTask = task => glob => { + const {options} = task; + if (options.ignore && Array.isArray(options.ignore) && options.expandDirectories) { + options.ignore = dirGlob.sync(options.ignore); } - return path.join(destination, basename); + return { + pattern: glob, + options + }; }; -module.exports = (source, destination, { - concurrency = (os.cpus().length || 1) * 2, - ...options -} = {}) => { - const progressEmitter = new EventEmitter(); +module.exports = async (patterns, options) => { + const globTasks = generateGlobTasks(patterns, options); - options = { - ...defaultOptions, - ...options + const getFilter = async () => { + return options && options.gitignore ? + gitignore({cwd: options.cwd, ignore: options.ignore}) : + DEFAULT_FILTER; }; - const promise = (async () => { - source = arrify(source); - - if (source.length === 0 || !destination) { - throw new CpyError('`source` and `destination` required'); - } - - const copyStatus = new Map(); - let completedFiles = 0; - let completedSize = 0; - - let files; - try { - files = await globby(source, options); + const getTasks = async () => { + const tasks = await Promise.all(globTasks.map(async task => { + const globs = await getPattern(task, dirGlob); + return Promise.all(globs.map(globToTask(task))); + })); - if (options.ignoreJunk) { - files = files.filter(file => junk.not(path.basename(file))); - } - } catch (error) { - throw new CpyError(`Cannot glob \`${source}\`: ${error.message}`, error); - } + return arrayUnion(...tasks); + }; - if (files.length === 0 && !hasGlob(source)) { - throw new CpyError(`Cannot copy \`${source}\`: the file doesn't exist`); - } + const [filter, tasks] = await Promise.all([getFilter(), getTasks()]); + const paths = await Promise.all(tasks.map(task => fastGlob(task.pattern, task.options))); - let sources = files.map(sourcePath => new SourceFile(sourcePath, preprocessSourcePath(sourcePath, options))); + return arrayUnion(...paths).filter(path_ => !filter(getPathString(path_))); +}; - if (options.filter !== undefined) { - const filteredSources = await pFilter(sources, options.filter, {concurrency: 1024}); - sources = filteredSources; - } +module.exports.sync = (patterns, options) => { + const globTasks = generateGlobTasks(patterns, options); - if (sources.length === 0) { - progressEmitter.emit('progress', { - totalFiles: 0, - percent: 1, - completedFiles: 0, - completedSize: 0 - }); - } + const tasks = []; + for (const task of globTasks) { + const newTask = getPattern(task, dirGlob.sync).map(globToTask(task)); + tasks.push(...newTask); + } - const fileProgressHandler = event => { - const fileStatus = copyStatus.get(event.src) || {written: 0, percent: 0}; + const filter = getFilterSync(options); - if (fileStatus.written !== event.written || fileStatus.percent !== event.percent) { - completedSize -= fileStatus.written; - completedSize += event.written; + let matches = []; + for (const task of tasks) { + matches = arrayUnion(matches, fastGlob.sync(task.pattern, task.options)); + } - if (event.percent === 1 && fileStatus.percent !== 1) { - completedFiles++; - } + return matches.filter(path_ => !filter(path_)); +}; - copyStatus.set(event.src, { - written: event.written, - percent: event.percent - }); +module.exports.stream = (patterns, options) => { + const globTasks = generateGlobTasks(patterns, options); - progressEmitter.emit('progress', { - totalFiles: files.length, - percent: completedFiles / files.length, - completedFiles, - completedSize - }); - } - }; + const tasks = []; + for (const task of globTasks) { + const newTask = getPattern(task, dirGlob.sync).map(globToTask(task)); + tasks.push(...newTask); + } - return pMap(sources, async source => { - const to = preprocessDestinationPath(source.relativePath, destination, options); + const filter = getFilterSync(options); + const filterStream = new FilterStream(p => !filter(p)); + const uniqueStream = new UniqueStream(); - try { - await cpFile(source.path, to, options).on('progress', fileProgressHandler); - } catch (error) { - throw new CpyError(`Cannot copy from \`${source.relativePath}\` to \`${to}\`: ${error.message}`, error); - } + return merge2(tasks.map(task => fastGlob.stream(task.pattern, task.options))) + .pipe(filterStream) + .pipe(uniqueStream); +}; - return to; - }, {concurrency}); - })(); +module.exports.generateGlobTasks = generateGlobTasks; - promise.on = (...arguments_) => { - progressEmitter.on(...arguments_); - return promise; - }; +module.exports.hasMagic = (patterns, options) => [] + .concat(patterns) + .some(pattern => fastGlob.isDynamicPattern(pattern, options)); - return promise; -}; +module.exports.gitignore = gitignore; /***/ }), -/* 594 */ +/* 584 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const AggregateError = __webpack_require__(595); - -module.exports = async ( - iterable, - mapper, - { - concurrency = Infinity, - stopOnError = true - } = {} -) => { - return new Promise((resolve, reject) => { - if (typeof mapper !== 'function') { - throw new TypeError('Mapper function is required'); - } - - if (!(typeof concurrency === 'number' && concurrency >= 1)) { - throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${concurrency}\` (${typeof concurrency})`); - } - - const ret = []; - const errors = []; - const iterator = iterable[Symbol.iterator](); - let isRejected = false; - let isIterableDone = false; - let resolvingCount = 0; - let currentIndex = 0; - - const next = () => { - if (isRejected) { - return; - } +const taskManager = __webpack_require__(585); +const async_1 = __webpack_require__(595); +const stream_1 = __webpack_require__(605); +const sync_1 = __webpack_require__(606); +const settings_1 = __webpack_require__(608); +const utils = __webpack_require__(586); +async function FastGlob(source, options) { + assertPatternsInput(source); + const works = getWorks(source, async_1.default, options); + const result = await Promise.all(works); + return utils.array.flatten(result); +} +// https://github.com/typescript-eslint/typescript-eslint/issues/60 +// eslint-disable-next-line no-redeclare +(function (FastGlob) { + function sync(source, options) { + assertPatternsInput(source); + const works = getWorks(source, sync_1.default, options); + return utils.array.flatten(works); + } + FastGlob.sync = sync; + function stream(source, options) { + assertPatternsInput(source); + const works = getWorks(source, stream_1.default, options); + /** + * The stream returned by the provider cannot work with an asynchronous iterator. + * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams. + * This affects performance (+25%). I don't see best solution right now. + */ + return utils.stream.merge(works); + } + FastGlob.stream = stream; + function generateTasks(source, options) { + assertPatternsInput(source); + const patterns = [].concat(source); + const settings = new settings_1.default(options); + return taskManager.generate(patterns, settings); + } + FastGlob.generateTasks = generateTasks; + function isDynamicPattern(source, options) { + assertPatternsInput(source); + const settings = new settings_1.default(options); + return utils.pattern.isDynamicPattern(source, settings); + } + FastGlob.isDynamicPattern = isDynamicPattern; + function escapePath(source) { + assertPatternsInput(source); + return utils.path.escape(source); + } + FastGlob.escapePath = escapePath; +})(FastGlob || (FastGlob = {})); +function getWorks(source, _Provider, options) { + const patterns = [].concat(source); + const settings = new settings_1.default(options); + const tasks = taskManager.generate(patterns, settings); + const provider = new _Provider(settings); + return tasks.map(provider.read, provider); +} +function assertPatternsInput(input) { + const source = [].concat(input); + const isValidSource = source.every((item) => utils.string.isString(item) && !utils.string.isEmpty(item)); + if (!isValidSource) { + throw new TypeError('Patterns must be a string (non empty) or an array of strings'); + } +} +module.exports = FastGlob; - const nextItem = iterator.next(); - const i = currentIndex; - currentIndex++; - if (nextItem.done) { - isIterableDone = true; +/***/ }), +/* 585 */ +/***/ (function(module, exports, __webpack_require__) { - if (resolvingCount === 0) { - if (!stopOnError && errors.length !== 0) { - reject(new AggregateError(errors)); - } else { - resolve(ret); - } - } +"use strict"; - return; - } +Object.defineProperty(exports, "__esModule", { value: true }); +exports.convertPatternGroupToTask = exports.convertPatternGroupsToTasks = exports.groupPatternsByBaseDirectory = exports.getNegativePatternsAsPositive = exports.getPositivePatterns = exports.convertPatternsToTasks = exports.generate = void 0; +const utils = __webpack_require__(586); +function generate(patterns, settings) { + const positivePatterns = getPositivePatterns(patterns); + const negativePatterns = getNegativePatternsAsPositive(patterns, settings.ignore); + const staticPatterns = positivePatterns.filter((pattern) => utils.pattern.isStaticPattern(pattern, settings)); + const dynamicPatterns = positivePatterns.filter((pattern) => utils.pattern.isDynamicPattern(pattern, settings)); + const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false); + const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, /* dynamic */ true); + return staticTasks.concat(dynamicTasks); +} +exports.generate = generate; +/** + * Returns tasks grouped by basic pattern directories. + * + * Patterns that can be found inside (`./`) and outside (`../`) the current directory are handled separately. + * This is necessary because directory traversal starts at the base directory and goes deeper. + */ +function convertPatternsToTasks(positive, negative, dynamic) { + const tasks = []; + const patternsOutsideCurrentDirectory = utils.pattern.getPatternsOutsideCurrentDirectory(positive); + const patternsInsideCurrentDirectory = utils.pattern.getPatternsInsideCurrentDirectory(positive); + const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsOutsideCurrentDirectory); + const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsInsideCurrentDirectory); + tasks.push(...convertPatternGroupsToTasks(outsideCurrentDirectoryGroup, negative, dynamic)); + /* + * For the sake of reducing future accesses to the file system, we merge all tasks within the current directory + * into a global task, if at least one pattern refers to the root (`.`). In this case, the global task covers the rest. + */ + if ('.' in insideCurrentDirectoryGroup) { + tasks.push(convertPatternGroupToTask('.', patternsInsideCurrentDirectory, negative, dynamic)); + } + else { + tasks.push(...convertPatternGroupsToTasks(insideCurrentDirectoryGroup, negative, dynamic)); + } + return tasks; +} +exports.convertPatternsToTasks = convertPatternsToTasks; +function getPositivePatterns(patterns) { + return utils.pattern.getPositivePatterns(patterns); +} +exports.getPositivePatterns = getPositivePatterns; +function getNegativePatternsAsPositive(patterns, ignore) { + const negative = utils.pattern.getNegativePatterns(patterns).concat(ignore); + const positive = negative.map(utils.pattern.convertToPositivePattern); + return positive; +} +exports.getNegativePatternsAsPositive = getNegativePatternsAsPositive; +function groupPatternsByBaseDirectory(patterns) { + const group = {}; + return patterns.reduce((collection, pattern) => { + const base = utils.pattern.getBaseDirectory(pattern); + if (base in collection) { + collection[base].push(pattern); + } + else { + collection[base] = [pattern]; + } + return collection; + }, group); +} +exports.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory; +function convertPatternGroupsToTasks(positive, negative, dynamic) { + return Object.keys(positive).map((base) => { + return convertPatternGroupToTask(base, positive[base], negative, dynamic); + }); +} +exports.convertPatternGroupsToTasks = convertPatternGroupsToTasks; +function convertPatternGroupToTask(base, positive, negative, dynamic) { + return { + dynamic, + positive, + negative, + base, + patterns: [].concat(positive, negative.map(utils.pattern.convertToNegativePattern)) + }; +} +exports.convertPatternGroupToTask = convertPatternGroupToTask; - resolvingCount++; - (async () => { - try { - const element = await nextItem.value; - ret[i] = await mapper(element, i); - resolvingCount--; - next(); - } catch (error) { - if (stopOnError) { - isRejected = true; - reject(error); - } else { - errors.push(error); - resolvingCount--; - next(); - } - } - })(); - }; +/***/ }), +/* 586 */ +/***/ (function(module, exports, __webpack_require__) { - for (let i = 0; i < concurrency; i++) { - next(); +"use strict"; - if (isIterableDone) { - break; - } - } - }); -}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.string = exports.stream = exports.pattern = exports.path = exports.fs = exports.errno = exports.array = void 0; +const array = __webpack_require__(587); +exports.array = array; +const errno = __webpack_require__(588); +exports.errno = errno; +const fs = __webpack_require__(589); +exports.fs = fs; +const path = __webpack_require__(590); +exports.path = path; +const pattern = __webpack_require__(591); +exports.pattern = pattern; +const stream = __webpack_require__(593); +exports.stream = stream; +const string = __webpack_require__(594); +exports.string = string; /***/ }), -/* 595 */ +/* 587 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const indentString = __webpack_require__(596); -const cleanStack = __webpack_require__(459); - -const cleanInternalStack = stack => stack.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g, ''); - -class AggregateError extends Error { - constructor(errors) { - if (!Array.isArray(errors)) { - throw new TypeError(`Expected input to be an Array, got ${typeof errors}`); - } - - errors = [...errors].map(error => { - if (error instanceof Error) { - return error; - } - - if (error !== null && typeof error === 'object') { - // Handle plain error objects with message property and/or possibly other metadata - return Object.assign(new Error(error.message), error); - } - - return new Error(error); - }); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.splitWhen = exports.flatten = void 0; +function flatten(items) { + return items.reduce((collection, item) => [].concat(collection, item), []); +} +exports.flatten = flatten; +function splitWhen(items, predicate) { + const result = [[]]; + let groupIndex = 0; + for (const item of items) { + if (predicate(item)) { + groupIndex++; + result[groupIndex] = []; + } + else { + result[groupIndex].push(item); + } + } + return result; +} +exports.splitWhen = splitWhen; - let message = errors - .map(error => { - // The `stack` property is not standardized, so we can't assume it exists - return typeof error.stack === 'string' ? cleanInternalStack(cleanStack(error.stack)) : String(error); - }) - .join('\n'); - message = '\n' + indentString(message, 4); - super(message); - this.name = 'AggregateError'; +/***/ }), +/* 588 */ +/***/ (function(module, exports, __webpack_require__) { - Object.defineProperty(this, '_errors', {value: errors}); - } +"use strict"; - * [Symbol.iterator]() { - for (const error of this._errors) { - yield error; - } - } +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isEnoentCodeError = void 0; +function isEnoentCodeError(error) { + return error.code === 'ENOENT'; } - -module.exports = AggregateError; +exports.isEnoentCodeError = isEnoentCodeError; /***/ }), -/* 596 */ +/* 589 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createDirentFromStats = void 0; +class DirentFromStats { + constructor(name, stats) { + this.name = name; + this.isBlockDevice = stats.isBlockDevice.bind(stats); + this.isCharacterDevice = stats.isCharacterDevice.bind(stats); + this.isDirectory = stats.isDirectory.bind(stats); + this.isFIFO = stats.isFIFO.bind(stats); + this.isFile = stats.isFile.bind(stats); + this.isSocket = stats.isSocket.bind(stats); + this.isSymbolicLink = stats.isSymbolicLink.bind(stats); + } +} +function createDirentFromStats(name, stats) { + return new DirentFromStats(name, stats); +} +exports.createDirentFromStats = createDirentFromStats; -module.exports = (string, count = 1, options) => { - options = { - indent: ' ', - includeEmptyLines: false, - ...options - }; - - if (typeof string !== 'string') { - throw new TypeError( - `Expected \`input\` to be a \`string\`, got \`${typeof string}\`` - ); - } - - if (typeof count !== 'number') { - throw new TypeError( - `Expected \`count\` to be a \`number\`, got \`${typeof count}\`` - ); - } - - if (typeof options.indent !== 'string') { - throw new TypeError( - `Expected \`options.indent\` to be a \`string\`, got \`${typeof options.indent}\`` - ); - } - if (count === 0) { - return string; - } +/***/ }), +/* 590 */ +/***/ (function(module, exports, __webpack_require__) { - const regex = options.includeEmptyLines ? /^/gm : /^(?!\s*$)/gm; +"use strict"; - return string.replace(regex, options.indent.repeat(count)); -}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.removeLeadingDotSegment = exports.escape = exports.makeAbsolute = exports.unixify = void 0; +const path = __webpack_require__(4); +const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\ +const UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\())/g; +/** + * Designed to work only with simple paths: `dir\\file`. + */ +function unixify(filepath) { + return filepath.replace(/\\/g, '/'); +} +exports.unixify = unixify; +function makeAbsolute(cwd, filepath) { + return path.resolve(cwd, filepath); +} +exports.makeAbsolute = makeAbsolute; +function escape(pattern) { + return pattern.replace(UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); +} +exports.escape = escape; +function removeLeadingDotSegment(entry) { + // We do not use `startsWith` because this is 10x slower than current implementation for some cases. + // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with + if (entry.charAt(0) === '.') { + const secondCharactery = entry.charAt(1); + if (secondCharactery === '/' || secondCharactery === '\\') { + return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT); + } + } + return entry; +} +exports.removeLeadingDotSegment = removeLeadingDotSegment; /***/ }), -/* 597 */ +/* 591 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const fs = __webpack_require__(253); -const arrayUnion = __webpack_require__(598); -const glob = __webpack_require__(365); -const fastGlob = __webpack_require__(600); -const dirGlob = __webpack_require__(783); -const gitignore = __webpack_require__(786); - -const DEFAULT_FILTER = () => false; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.matchAny = exports.convertPatternsToRe = exports.makeRe = exports.getPatternParts = exports.expandBraceExpansion = exports.expandPatternsWithBraceExpansion = exports.isAffectDepthOfReadingPattern = exports.endsWithSlashGlobStar = exports.hasGlobStar = exports.getBaseDirectory = exports.isPatternRelatedToParentDirectory = exports.getPatternsOutsideCurrentDirectory = exports.getPatternsInsideCurrentDirectory = exports.getPositivePatterns = exports.getNegativePatterns = exports.isPositivePattern = exports.isNegativePattern = exports.convertToNegativePattern = exports.convertToPositivePattern = exports.isDynamicPattern = exports.isStaticPattern = void 0; +const path = __webpack_require__(4); +const globParent = __webpack_require__(386); +const micromatch = __webpack_require__(592); +const GLOBSTAR = '**'; +const ESCAPE_SYMBOL = '\\'; +const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/; +const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[.*]/; +const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\(.*\|.*\)/; +const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\(.*\)/; +const BRACE_EXPANSIONS_SYMBOLS_RE = /{.*(?:,|\.\.).*}/; +function isStaticPattern(pattern, options = {}) { + return !isDynamicPattern(pattern, options); +} +exports.isStaticPattern = isStaticPattern; +function isDynamicPattern(pattern, options = {}) { + /** + * A special case with an empty string is necessary for matching patterns that start with a forward slash. + * An empty string cannot be a dynamic pattern. + * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'. + */ + if (pattern === '') { + return false; + } + /** + * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check + * filepath directly (without read directory). + */ + if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) { + return true; + } + if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) { + return true; + } + if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) { + return true; + } + if (options.braceExpansion !== false && BRACE_EXPANSIONS_SYMBOLS_RE.test(pattern)) { + return true; + } + return false; +} +exports.isDynamicPattern = isDynamicPattern; +function convertToPositivePattern(pattern) { + return isNegativePattern(pattern) ? pattern.slice(1) : pattern; +} +exports.convertToPositivePattern = convertToPositivePattern; +function convertToNegativePattern(pattern) { + return '!' + pattern; +} +exports.convertToNegativePattern = convertToNegativePattern; +function isNegativePattern(pattern) { + return pattern.startsWith('!') && pattern[1] !== '('; +} +exports.isNegativePattern = isNegativePattern; +function isPositivePattern(pattern) { + return !isNegativePattern(pattern); +} +exports.isPositivePattern = isPositivePattern; +function getNegativePatterns(patterns) { + return patterns.filter(isNegativePattern); +} +exports.getNegativePatterns = getNegativePatterns; +function getPositivePatterns(patterns) { + return patterns.filter(isPositivePattern); +} +exports.getPositivePatterns = getPositivePatterns; +/** + * Returns patterns that can be applied inside the current directory. + * + * @example + * // ['./*', '*', 'a/*'] + * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) + */ +function getPatternsInsideCurrentDirectory(patterns) { + return patterns.filter((pattern) => !isPatternRelatedToParentDirectory(pattern)); +} +exports.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory; +/** + * Returns patterns to be expanded relative to (outside) the current directory. + * + * @example + * // ['../*', './../*'] + * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) + */ +function getPatternsOutsideCurrentDirectory(patterns) { + return patterns.filter(isPatternRelatedToParentDirectory); +} +exports.getPatternsOutsideCurrentDirectory = getPatternsOutsideCurrentDirectory; +function isPatternRelatedToParentDirectory(pattern) { + return pattern.startsWith('..') || pattern.startsWith('./..'); +} +exports.isPatternRelatedToParentDirectory = isPatternRelatedToParentDirectory; +function getBaseDirectory(pattern) { + return globParent(pattern, { flipBackslashes: false }); +} +exports.getBaseDirectory = getBaseDirectory; +function hasGlobStar(pattern) { + return pattern.includes(GLOBSTAR); +} +exports.hasGlobStar = hasGlobStar; +function endsWithSlashGlobStar(pattern) { + return pattern.endsWith('/' + GLOBSTAR); +} +exports.endsWithSlashGlobStar = endsWithSlashGlobStar; +function isAffectDepthOfReadingPattern(pattern) { + const basename = path.basename(pattern); + return endsWithSlashGlobStar(pattern) || isStaticPattern(basename); +} +exports.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern; +function expandPatternsWithBraceExpansion(patterns) { + return patterns.reduce((collection, pattern) => { + return collection.concat(expandBraceExpansion(pattern)); + }, []); +} +exports.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion; +function expandBraceExpansion(pattern) { + return micromatch.braces(pattern, { + expand: true, + nodupes: true + }); +} +exports.expandBraceExpansion = expandBraceExpansion; +function getPatternParts(pattern, options) { + let { parts } = micromatch.scan(pattern, Object.assign(Object.assign({}, options), { parts: true })); + /** + * The scan method returns an empty array in some cases. + * See micromatch/picomatch#58 for more details. + */ + if (parts.length === 0) { + parts = [pattern]; + } + /** + * The scan method does not return an empty part for the pattern with a forward slash. + * This is another part of micromatch/picomatch#58. + */ + if (parts[0].startsWith('/')) { + parts[0] = parts[0].slice(1); + parts.unshift(''); + } + return parts; +} +exports.getPatternParts = getPatternParts; +function makeRe(pattern, options) { + return micromatch.makeRe(pattern, options); +} +exports.makeRe = makeRe; +function convertPatternsToRe(patterns, options) { + return patterns.map((pattern) => makeRe(pattern, options)); +} +exports.convertPatternsToRe = convertPatternsToRe; +function matchAny(entry, patternsRe) { + return patternsRe.some((patternRe) => patternRe.test(entry)); +} +exports.matchAny = matchAny; -const isNegative = pattern => pattern[0] === '!'; -const assertPatternsInput = patterns => { - if (!patterns.every(x => typeof x === 'string')) { - throw new TypeError('Patterns must be a string or an array of strings'); - } -}; +/***/ }), +/* 592 */ +/***/ (function(module, exports, __webpack_require__) { -const checkCwdOption = options => { - if (options && options.cwd && !fs.statSync(options.cwd).isDirectory()) { - throw new Error('The `cwd` option must be a path to a directory'); - } -}; +"use strict"; -const generateGlobTasks = (patterns, taskOptions) => { - patterns = arrayUnion([].concat(patterns)); - assertPatternsInput(patterns); - checkCwdOption(taskOptions); - const globTasks = []; +const util = __webpack_require__(234); +const braces = __webpack_require__(390); +const picomatch = __webpack_require__(400); +const utils = __webpack_require__(403); +const isEmptyString = val => val === '' || val === './'; - taskOptions = Object.assign({ - ignore: [], - expandDirectories: true - }, taskOptions); +/** + * Returns an array of strings that match one or more glob patterns. + * + * ```js + * const mm = require('micromatch'); + * // mm(list, patterns[, options]); + * + * console.log(mm(['a.js', 'a.txt'], ['*.js'])); + * //=> [ 'a.js' ] + * ``` + * @param {String|Array} `list` List of strings to match. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) + * @return {Array} Returns an array of matches + * @summary false + * @api public + */ - patterns.forEach((pattern, i) => { - if (isNegative(pattern)) { - return; - } +const micromatch = (list, patterns, options) => { + patterns = [].concat(patterns); + list = [].concat(list); - const ignore = patterns - .slice(i) - .filter(isNegative) - .map(pattern => pattern.slice(1)); + let omit = new Set(); + let keep = new Set(); + let items = new Set(); + let negatives = 0; - const options = Object.assign({}, taskOptions, { - ignore: taskOptions.ignore.concat(ignore) - }); + let onResult = state => { + items.add(state.output); + if (options && options.onResult) { + options.onResult(state); + } + }; - globTasks.push({pattern, options}); - }); + for (let i = 0; i < patterns.length; i++) { + let isMatch = picomatch(String(patterns[i]), { ...options, onResult }, true); + let negated = isMatch.state.negated || isMatch.state.negatedExtglob; + if (negated) negatives++; - return globTasks; -}; + for (let item of list) { + let matched = isMatch(item, true); -const globDirs = (task, fn) => { - let options = {}; - if (task.options.cwd) { - options.cwd = task.options.cwd; - } + let match = negated ? !matched.isMatch : matched.isMatch; + if (!match) continue; - if (Array.isArray(task.options.expandDirectories)) { - options = Object.assign(options, {files: task.options.expandDirectories}); - } else if (typeof task.options.expandDirectories === 'object') { - options = Object.assign(options, task.options.expandDirectories); - } + if (negated) { + omit.add(matched.output); + } else { + omit.delete(matched.output); + keep.add(matched.output); + } + } + } - return fn(task.pattern, options); -}; + let result = negatives === patterns.length ? [...items] : [...keep]; + let matches = result.filter(item => !omit.has(item)); -const getPattern = (task, fn) => task.options.expandDirectories ? globDirs(task, fn) : [task.pattern]; + if (options && matches.length === 0) { + if (options.failglob === true) { + throw new Error(`No matches found for "${patterns.join(', ')}"`); + } -const globToTask = task => glob => { - const {options} = task; - if (options.ignore && Array.isArray(options.ignore) && options.expandDirectories) { - options.ignore = dirGlob.sync(options.ignore); - } + if (options.nonull === true || options.nullglob === true) { + return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns; + } + } - return { - pattern: glob, - options - }; + return matches; }; -const globby = (patterns, options) => { - let globTasks; +/** + * Backwards compatibility + */ - try { - globTasks = generateGlobTasks(patterns, options); - } catch (error) { - return Promise.reject(error); - } +micromatch.match = micromatch; - const getTasks = Promise.all(globTasks.map(task => Promise.resolve(getPattern(task, dirGlob)) - .then(globs => Promise.all(globs.map(globToTask(task)))) - )) - .then(tasks => arrayUnion(...tasks)); +/** + * Returns a matcher function from the given glob `pattern` and `options`. + * The returned function takes a string to match as its only argument and returns + * true if the string is a match. + * + * ```js + * const mm = require('micromatch'); + * // mm.matcher(pattern[, options]); + * + * const isMatch = mm.matcher('*.!(*a)'); + * console.log(isMatch('a.a')); //=> false + * console.log(isMatch('a.b')); //=> true + * ``` + * @param {String} `pattern` Glob pattern + * @param {Object} `options` + * @return {Function} Returns a matcher function. + * @api public + */ - const getFilter = () => { - return Promise.resolve( - options && options.gitignore ? - gitignore({cwd: options.cwd, ignore: options.ignore}) : - DEFAULT_FILTER - ); - }; +micromatch.matcher = (pattern, options) => picomatch(pattern, options); - return getFilter() - .then(filter => { - return getTasks - .then(tasks => Promise.all(tasks.map(task => fastGlob(task.pattern, task.options)))) - .then(paths => arrayUnion(...paths)) - .then(paths => paths.filter(p => !filter(p))); - }); -}; +/** + * Returns true if **any** of the given glob `patterns` match the specified `string`. + * + * ```js + * const mm = require('micromatch'); + * // mm.isMatch(string, patterns[, options]); + * + * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true + * console.log(mm.isMatch('a.a', 'b.*')); //=> false + * ``` + * @param {String} `str` The string to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `[options]` See available [options](#options). + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ -module.exports = globby; -// TODO: Remove this for the next major release -module.exports.default = globby; +micromatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); -module.exports.sync = (patterns, options) => { - const globTasks = generateGlobTasks(patterns, options); +/** + * Backwards compatibility + */ - const getFilter = () => { - return options && options.gitignore ? - gitignore.sync({cwd: options.cwd, ignore: options.ignore}) : - DEFAULT_FILTER; - }; +micromatch.any = micromatch.isMatch; - const tasks = globTasks.reduce((tasks, task) => { - const newTask = getPattern(task, dirGlob.sync).map(globToTask(task)); - return tasks.concat(newTask); - }, []); +/** + * Returns a list of strings that _**do not match any**_ of the given `patterns`. + * + * ```js + * const mm = require('micromatch'); + * // mm.not(list, patterns[, options]); + * + * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); + * //=> ['b.b', 'c.c'] + * ``` + * @param {Array} `list` Array of strings to match. + * @param {String|Array} `patterns` One or more glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array} Returns an array of strings that **do not match** the given patterns. + * @api public + */ - const filter = getFilter(); - return tasks.reduce( - (matches, task) => arrayUnion(matches, fastGlob.sync(task.pattern, task.options)), - [] - ).filter(p => !filter(p)); +micromatch.not = (list, patterns, options = {}) => { + patterns = [].concat(patterns).map(String); + let result = new Set(); + let items = []; + + let onResult = state => { + if (options.onResult) options.onResult(state); + items.push(state.output); + }; + + let matches = micromatch(list, patterns, { ...options, onResult }); + + for (let item of items) { + if (!matches.includes(item)) { + result.add(item); + } + } + return [...result]; }; -module.exports.generateGlobTasks = generateGlobTasks; +/** + * Returns true if the given `string` contains the given pattern. Similar + * to [.isMatch](#isMatch) but the pattern can match any part of the string. + * + * ```js + * var mm = require('micromatch'); + * // mm.contains(string, pattern[, options]); + * + * console.log(mm.contains('aa/bb/cc', '*b')); + * //=> true + * console.log(mm.contains('aa/bb/cc', '*d')); + * //=> false + * ``` + * @param {String} `str` The string to match. + * @param {String|Array} `patterns` Glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any of the patterns matches any part of `str`. + * @api public + */ -module.exports.hasMagic = (patterns, options) => [] - .concat(patterns) - .some(pattern => glob.hasMagic(pattern, options)); +micromatch.contains = (str, pattern, options) => { + if (typeof str !== 'string') { + throw new TypeError(`Expected a string: "${util.inspect(str)}"`); + } -module.exports.gitignore = gitignore; + if (Array.isArray(pattern)) { + return pattern.some(p => micromatch.contains(str, p, options)); + } + if (typeof pattern === 'string') { + if (isEmptyString(str) || isEmptyString(pattern)) { + return false; + } -/***/ }), -/* 598 */ -/***/ (function(module, exports, __webpack_require__) { + if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) { + return true; + } + } -"use strict"; + return micromatch.isMatch(str, pattern, { ...options, contains: true }); +}; -var arrayUniq = __webpack_require__(599); +/** + * Filter the keys of the given object with the given `glob` pattern + * and `options`. Does not attempt to match nested keys. If you need this feature, + * use [glob-object][] instead. + * + * ```js + * const mm = require('micromatch'); + * // mm.matchKeys(object, patterns[, options]); + * + * const obj = { aa: 'a', ab: 'b', ac: 'c' }; + * console.log(mm.matchKeys(obj, '*b')); + * //=> { ab: 'b' } + * ``` + * @param {Object} `object` The object with keys to filter. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Object} Returns an object with only keys that match the given patterns. + * @api public + */ -module.exports = function () { - return arrayUniq([].concat.apply([], arguments)); +micromatch.matchKeys = (obj, patterns, options) => { + if (!utils.isObject(obj)) { + throw new TypeError('Expected the first argument to be an object'); + } + let keys = micromatch(Object.keys(obj), patterns, options); + let res = {}; + for (let key of keys) res[key] = obj[key]; + return res; }; +/** + * Returns true if some of the strings in the given `list` match any of the given glob `patterns`. + * + * ```js + * const mm = require('micromatch'); + * // mm.some(list, patterns[, options]); + * + * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * // true + * console.log(mm.some(['foo.js'], ['*.js', '!foo.js'])); + * // false + * ``` + * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any `patterns` matches any of the strings in `list` + * @api public + */ -/***/ }), -/* 599 */ -/***/ (function(module, exports, __webpack_require__) { +micromatch.some = (list, patterns, options) => { + let items = [].concat(list); -"use strict"; + for (let pattern of [].concat(patterns)) { + let isMatch = picomatch(String(pattern), options); + if (items.some(item => isMatch(item))) { + return true; + } + } + return false; +}; +/** + * Returns true if every string in the given `list` matches + * any of the given glob `patterns`. + * + * ```js + * const mm = require('micromatch'); + * // mm.every(list, patterns[, options]); + * + * console.log(mm.every('foo.js', ['foo.js'])); + * // true + * console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); + * // true + * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * // false + * console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); + * // false + * ``` + * @param {String|Array} `list` The string or array of strings to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if all `patterns` matches all of the strings in `list` + * @api public + */ -// there's 3 implementations written in increasing order of efficiency +micromatch.every = (list, patterns, options) => { + let items = [].concat(list); -// 1 - no Set type is defined -function uniqNoSet(arr) { - var ret = []; + for (let pattern of [].concat(patterns)) { + let isMatch = picomatch(String(pattern), options); + if (!items.every(item => isMatch(item))) { + return false; + } + } + return true; +}; - for (var i = 0; i < arr.length; i++) { - if (ret.indexOf(arr[i]) === -1) { - ret.push(arr[i]); - } - } +/** + * Returns true if **all** of the given `patterns` match + * the specified string. + * + * ```js + * const mm = require('micromatch'); + * // mm.all(string, patterns[, options]); + * + * console.log(mm.all('foo.js', ['foo.js'])); + * // true + * + * console.log(mm.all('foo.js', ['*.js', '!foo.js'])); + * // false + * + * console.log(mm.all('foo.js', ['*.js', 'foo.js'])); + * // true + * + * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); + * // true + * ``` + * @param {String|Array} `str` The string to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ - return ret; -} +micromatch.all = (str, patterns, options) => { + if (typeof str !== 'string') { + throw new TypeError(`Expected a string: "${util.inspect(str)}"`); + } -// 2 - a simple Set type is defined -function uniqSet(arr) { - var seen = new Set(); - return arr.filter(function (el) { - if (!seen.has(el)) { - seen.add(el); - return true; - } + return [].concat(patterns).every(p => picomatch(p, options)(str)); +}; - return false; - }); -} +/** + * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match. + * + * ```js + * const mm = require('micromatch'); + * // mm.capture(pattern, string[, options]); + * + * console.log(mm.capture('test/*.js', 'test/foo.js')); + * //=> ['foo'] + * console.log(mm.capture('test/*.js', 'foo/bar.css')); + * //=> null + * ``` + * @param {String} `glob` Glob pattern to use for matching. + * @param {String} `input` String to match + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array|null} Returns an array of captures if the input matches the glob pattern, otherwise `null`. + * @api public + */ -// 3 - a standard Set type is defined and it has a forEach method -function uniqSetWithForEach(arr) { - var ret = []; +micromatch.capture = (glob, input, options) => { + let posix = utils.isWindows(options); + let regex = picomatch.makeRe(String(glob), { ...options, capture: true }); + let match = regex.exec(posix ? utils.toPosixSlashes(input) : input); - (new Set(arr)).forEach(function (el) { - ret.push(el); - }); + if (match) { + return match.slice(1).map(v => v === void 0 ? '' : v); + } +}; - return ret; -} +/** + * Create a regular expression from the given glob `pattern`. + * + * ```js + * const mm = require('micromatch'); + * // mm.makeRe(pattern[, options]); + * + * console.log(mm.makeRe('*.js')); + * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ + * ``` + * @param {String} `pattern` A glob pattern to convert to regex. + * @param {Object} `options` + * @return {RegExp} Returns a regex created from the given pattern. + * @api public + */ -// V8 currently has a broken implementation -// https://github.com/joyent/node/issues/8449 -function doesForEachActuallyWork() { - var ret = false; +micromatch.makeRe = (...args) => picomatch.makeRe(...args); - (new Set([true])).forEach(function (el) { - ret = el; - }); +/** + * Scan a glob pattern to separate the pattern into segments. Used + * by the [split](#split) method. + * + * ```js + * const mm = require('micromatch'); + * const state = mm.scan(pattern[, options]); + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {Object} Returns an object with + * @api public + */ - return ret === true; -} +micromatch.scan = (...args) => picomatch.scan(...args); -if ('Set' in global) { - if (typeof Set.prototype.forEach === 'function' && doesForEachActuallyWork()) { - module.exports = uniqSetWithForEach; - } else { - module.exports = uniqSet; - } -} else { - module.exports = uniqNoSet; -} +/** + * Parse a glob pattern to create the source string for a regular + * expression. + * + * ```js + * const mm = require('micromatch'); + * const state = mm(pattern[, options]); + * ``` + * @param {String} `glob` + * @param {Object} `options` + * @return {Object} Returns an object with useful properties and output to be used as regex source string. + * @api public + */ +micromatch.parse = (patterns, options) => { + let res = []; + for (let pattern of [].concat(patterns || [])) { + for (let str of braces(String(pattern), options)) { + res.push(picomatch.parse(str, options)); + } + } + return res; +}; -/***/ }), -/* 600 */ -/***/ (function(module, exports, __webpack_require__) { +/** + * Process the given brace `pattern`. + * + * ```js + * const { braces } = require('micromatch'); + * console.log(braces('foo/{a,b,c}/bar')); + * //=> [ 'foo/(a|b|c)/bar' ] + * + * console.log(braces('foo/{a,b,c}/bar', { expand: true })); + * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ] + * ``` + * @param {String} `pattern` String with brace pattern to process. + * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options. + * @return {Array} + * @api public + */ -const pkg = __webpack_require__(601); +micromatch.braces = (pattern, options) => { + if (typeof pattern !== 'string') throw new TypeError('Expected a string'); + if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) { + return [pattern]; + } + return braces(pattern, options); +}; -module.exports = pkg.async; -module.exports.default = pkg.async; +/** + * Expand braces + */ -module.exports.async = pkg.async; -module.exports.sync = pkg.sync; -module.exports.stream = pkg.stream; +micromatch.braceExpand = (pattern, options) => { + if (typeof pattern !== 'string') throw new TypeError('Expected a string'); + return micromatch.braces(pattern, { ...options, expand: true }); +}; -module.exports.generateTasks = pkg.generateTasks; +/** + * Expose micromatch + */ + +module.exports = micromatch; /***/ }), -/* 601 */ +/* 593 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var optionsManager = __webpack_require__(602); -var taskManager = __webpack_require__(603); -var reader_async_1 = __webpack_require__(754); -var reader_stream_1 = __webpack_require__(778); -var reader_sync_1 = __webpack_require__(779); -var arrayUtils = __webpack_require__(781); -var streamUtils = __webpack_require__(782); -/** - * Synchronous API. - */ -function sync(source, opts) { - assertPatternsInput(source); - var works = getWorks(source, reader_sync_1.default, opts); - return arrayUtils.flatten(works); -} -exports.sync = sync; -/** - * Asynchronous API. - */ -function async(source, opts) { - try { - assertPatternsInput(source); - } - catch (error) { - return Promise.reject(error); - } - var works = getWorks(source, reader_async_1.default, opts); - return Promise.all(works).then(arrayUtils.flatten); -} -exports.async = async; -/** - * Stream API. - */ -function stream(source, opts) { - assertPatternsInput(source); - var works = getWorks(source, reader_stream_1.default, opts); - return streamUtils.merge(works); -} -exports.stream = stream; -/** - * Return a set of tasks based on provided patterns. - */ -function generateTasks(source, opts) { - assertPatternsInput(source); - var patterns = [].concat(source); - var options = optionsManager.prepare(opts); - return taskManager.generate(patterns, options); -} -exports.generateTasks = generateTasks; -/** - * Returns a set of works based on provided tasks and class of the reader. - */ -function getWorks(source, _Reader, opts) { - var patterns = [].concat(source); - var options = optionsManager.prepare(opts); - var tasks = taskManager.generate(patterns, options); - var reader = new _Reader(options); - return tasks.map(reader.read, reader); -} -function assertPatternsInput(source) { - if ([].concat(source).every(isString)) { - return; - } - throw new TypeError('Patterns must be a string or an array of strings'); -} -function isString(source) { - /* tslint:disable-next-line strict-type-predicates */ - return typeof source === 'string'; -} + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.merge = void 0; +const merge2 = __webpack_require__(364); +function merge(streams) { + const mergedStream = merge2(streams); + streams.forEach((stream) => { + stream.once('error', (error) => mergedStream.emit('error', error)); + }); + mergedStream.once('close', () => propagateCloseEventToSources(streams)); + mergedStream.once('end', () => propagateCloseEventToSources(streams)); + return mergedStream; +} +exports.merge = merge; +function propagateCloseEventToSources(streams) { + streams.forEach((stream) => stream.emit('close')); +} /***/ }), -/* 602 */ +/* 594 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; - -var __assign = (this && this.__assign) || function () { - __assign = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -function prepare(options) { - var opts = __assign({ cwd: process.cwd(), deep: true, ignore: [], dot: false, stats: false, onlyFiles: true, onlyDirectories: false, followSymlinkedDirectories: true, unique: true, markDirectories: false, absolute: false, nobrace: false, brace: true, noglobstar: false, globstar: true, noext: false, extension: true, nocase: false, case: true, matchBase: false, transform: null }, options); - if (opts.onlyDirectories) { - opts.onlyFiles = false; - } - opts.brace = !opts.nobrace; - opts.globstar = !opts.noglobstar; - opts.extension = !opts.noext; - opts.case = !opts.nocase; - if (options) { - opts.brace = ('brace' in options ? options.brace : opts.brace); - opts.globstar = ('globstar' in options ? options.globstar : opts.globstar); - opts.extension = ('extension' in options ? options.extension : opts.extension); - opts.case = ('case' in options ? options.case : opts.case); - } - return opts; -} -exports.prepare = prepare; + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isEmpty = exports.isString = void 0; +function isString(input) { + return typeof input === 'string'; +} +exports.isString = isString; +function isEmpty(input) { + return input === ''; +} +exports.isEmpty = isEmpty; /***/ }), -/* 603 */ +/* 595 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var patternUtils = __webpack_require__(604); -/** - * Generate tasks based on parent directory of each pattern. - */ -function generate(patterns, options) { - var unixPatterns = patterns.map(patternUtils.unixifyPattern); - var unixIgnore = options.ignore.map(patternUtils.unixifyPattern); - var positivePatterns = getPositivePatterns(unixPatterns); - var negativePatterns = getNegativePatternsAsPositive(unixPatterns, unixIgnore); - /** - * When the `case` option is disabled, all patterns must be marked as dynamic, because we cannot check filepath - * directly (without read directory). - */ - var staticPatterns = !options.case ? [] : positivePatterns.filter(patternUtils.isStaticPattern); - var dynamicPatterns = !options.case ? positivePatterns : positivePatterns.filter(patternUtils.isDynamicPattern); - var staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false); - var dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, /* dynamic */ true); - return staticTasks.concat(dynamicTasks); -} -exports.generate = generate; -/** - * Convert patterns to tasks based on parent directory of each pattern. - */ -function convertPatternsToTasks(positive, negative, dynamic) { - var positivePatternsGroup = groupPatternsByBaseDirectory(positive); - // When we have a global group – there is no reason to divide the patterns into independent tasks. - // In this case, the global task covers the rest. - if ('.' in positivePatternsGroup) { - var task = convertPatternGroupToTask('.', positive, negative, dynamic); - return [task]; - } - return convertPatternGroupsToTasks(positivePatternsGroup, negative, dynamic); -} -exports.convertPatternsToTasks = convertPatternsToTasks; -/** - * Return only positive patterns. - */ -function getPositivePatterns(patterns) { - return patternUtils.getPositivePatterns(patterns); -} -exports.getPositivePatterns = getPositivePatterns; -/** - * Return only negative patterns. - */ -function getNegativePatternsAsPositive(patterns, ignore) { - var negative = patternUtils.getNegativePatterns(patterns).concat(ignore); - var positive = negative.map(patternUtils.convertToPositivePattern); - return positive; -} -exports.getNegativePatternsAsPositive = getNegativePatternsAsPositive; -/** - * Group patterns by base directory of each pattern. - */ -function groupPatternsByBaseDirectory(patterns) { - return patterns.reduce(function (collection, pattern) { - var base = patternUtils.getBaseDirectory(pattern); - if (base in collection) { - collection[base].push(pattern); - } - else { - collection[base] = [pattern]; - } - return collection; - }, {}); -} -exports.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory; -/** - * Convert group of patterns to tasks. - */ -function convertPatternGroupsToTasks(positive, negative, dynamic) { - return Object.keys(positive).map(function (base) { - return convertPatternGroupToTask(base, positive[base], negative, dynamic); - }); -} -exports.convertPatternGroupsToTasks = convertPatternGroupsToTasks; -/** - * Create a task for positive and negative patterns. - */ -function convertPatternGroupToTask(base, positive, negative, dynamic) { - return { - base: base, - dynamic: dynamic, - positive: positive, - negative: negative, - patterns: [].concat(positive, negative.map(patternUtils.convertToNegativePattern)) - }; -} -exports.convertPatternGroupToTask = convertPatternGroupToTask; + +Object.defineProperty(exports, "__esModule", { value: true }); +const stream_1 = __webpack_require__(596); +const provider_1 = __webpack_require__(598); +class ProviderAsync extends provider_1.default { + constructor() { + super(...arguments); + this._reader = new stream_1.default(this._settings); + } + read(task) { + const root = this._getRootDirectory(task); + const options = this._getReaderOptions(task); + const entries = []; + return new Promise((resolve, reject) => { + const stream = this.api(root, task, options); + stream.once('error', reject); + stream.on('data', (entry) => entries.push(options.transform(entry))); + stream.once('end', () => resolve(entries)); + }); + } + api(root, task, options) { + if (task.dynamic) { + return this._reader.dynamic(root, options); + } + return this._reader.static(task.patterns, options); + } +} +exports.default = ProviderAsync; /***/ }), -/* 604 */ +/* 596 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var path = __webpack_require__(4); -var globParent = __webpack_require__(605); -var isGlob = __webpack_require__(387); -var micromatch = __webpack_require__(608); -var GLOBSTAR = '**'; -/** - * Return true for static pattern. - */ -function isStaticPattern(pattern) { - return !isDynamicPattern(pattern); -} -exports.isStaticPattern = isStaticPattern; -/** - * Return true for pattern that looks like glob. - */ -function isDynamicPattern(pattern) { - return isGlob(pattern, { strict: false }); -} -exports.isDynamicPattern = isDynamicPattern; -/** - * Convert a windows «path» to a unix-style «path». - */ -function unixifyPattern(pattern) { - return pattern.replace(/\\/g, '/'); -} -exports.unixifyPattern = unixifyPattern; -/** - * Returns negative pattern as positive pattern. - */ -function convertToPositivePattern(pattern) { - return isNegativePattern(pattern) ? pattern.slice(1) : pattern; -} -exports.convertToPositivePattern = convertToPositivePattern; -/** - * Returns positive pattern as negative pattern. - */ -function convertToNegativePattern(pattern) { - return '!' + pattern; -} -exports.convertToNegativePattern = convertToNegativePattern; -/** - * Return true if provided pattern is negative pattern. - */ -function isNegativePattern(pattern) { - return pattern.startsWith('!') && pattern[1] !== '('; -} -exports.isNegativePattern = isNegativePattern; -/** - * Return true if provided pattern is positive pattern. - */ -function isPositivePattern(pattern) { - return !isNegativePattern(pattern); -} -exports.isPositivePattern = isPositivePattern; -/** - * Extracts negative patterns from array of patterns. - */ -function getNegativePatterns(patterns) { - return patterns.filter(isNegativePattern); -} -exports.getNegativePatterns = getNegativePatterns; -/** - * Extracts positive patterns from array of patterns. - */ -function getPositivePatterns(patterns) { - return patterns.filter(isPositivePattern); -} -exports.getPositivePatterns = getPositivePatterns; -/** - * Extract base directory from provided pattern. - */ -function getBaseDirectory(pattern) { - return globParent(pattern); -} -exports.getBaseDirectory = getBaseDirectory; -/** - * Return true if provided pattern has globstar. - */ -function hasGlobStar(pattern) { - return pattern.indexOf(GLOBSTAR) !== -1; -} -exports.hasGlobStar = hasGlobStar; -/** - * Return true if provided pattern ends with slash and globstar. - */ -function endsWithSlashGlobStar(pattern) { - return pattern.endsWith('/' + GLOBSTAR); -} -exports.endsWithSlashGlobStar = endsWithSlashGlobStar; -/** - * Returns «true» when pattern ends with a slash and globstar or the last partial of the pattern is static pattern. - */ -function isAffectDepthOfReadingPattern(pattern) { - var basename = path.basename(pattern); - return endsWithSlashGlobStar(pattern) || isStaticPattern(basename); -} -exports.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern; -/** - * Return naive depth of provided pattern without depth of the base directory. - */ -function getNaiveDepth(pattern) { - var base = getBaseDirectory(pattern); - var patternDepth = pattern.split('/').length; - var patternBaseDepth = base.split('/').length; - /** - * This is a hack for pattern that has no base directory. - * - * This is related to the `*\something\*` pattern. - */ - if (base === '.') { - return patternDepth - patternBaseDepth; - } - return patternDepth - patternBaseDepth - 1; -} -exports.getNaiveDepth = getNaiveDepth; -/** - * Return max naive depth of provided patterns without depth of the base directory. - */ -function getMaxNaivePatternsDepth(patterns) { - return patterns.reduce(function (max, pattern) { - var depth = getNaiveDepth(pattern); - return depth > max ? depth : max; - }, 0); -} -exports.getMaxNaivePatternsDepth = getMaxNaivePatternsDepth; -/** - * Make RegExp for provided pattern. - */ -function makeRe(pattern, options) { - return micromatch.makeRe(pattern, options); -} -exports.makeRe = makeRe; -/** - * Convert patterns to regexps. - */ -function convertPatternsToRe(patterns, options) { - return patterns.map(function (pattern) { return makeRe(pattern, options); }); -} -exports.convertPatternsToRe = convertPatternsToRe; -/** - * Returns true if the entry match any of the given RegExp's. - */ -function matchAny(entry, patternsRe) { - return patternsRe.some(function (patternRe) { return patternRe.test(entry); }); -} -exports.matchAny = matchAny; + +Object.defineProperty(exports, "__esModule", { value: true }); +const stream_1 = __webpack_require__(294); +const fsStat = __webpack_require__(410); +const fsWalk = __webpack_require__(415); +const reader_1 = __webpack_require__(597); +class ReaderStream extends reader_1.default { + constructor() { + super(...arguments); + this._walkStream = fsWalk.walkStream; + this._stat = fsStat.stat; + } + dynamic(root, options) { + return this._walkStream(root, options); + } + static(patterns, options) { + const filepaths = patterns.map(this._getFullEntryPath, this); + const stream = new stream_1.PassThrough({ objectMode: true }); + stream._write = (index, _enc, done) => { + return this._getEntry(filepaths[index], patterns[index], options) + .then((entry) => { + if (entry !== null && options.entryFilter(entry)) { + stream.push(entry); + } + if (index === filepaths.length - 1) { + stream.end(); + } + done(); + }) + .catch(done); + }; + for (let i = 0; i < filepaths.length; i++) { + stream.write(i); + } + return stream; + } + _getEntry(filepath, pattern, options) { + return this._getStat(filepath) + .then((stats) => this._makeEntry(stats, pattern)) + .catch((error) => { + if (options.errorFilter(error)) { + return null; + } + throw error; + }); + } + _getStat(filepath) { + return new Promise((resolve, reject) => { + this._stat(filepath, this._fsStatSettings, (error, stats) => { + return error === null ? resolve(stats) : reject(error); + }); + }); + } +} +exports.default = ReaderStream; /***/ }), -/* 605 */ +/* 597 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const path = __webpack_require__(4); +const fsStat = __webpack_require__(410); +const utils = __webpack_require__(586); +class Reader { + constructor(_settings) { + this._settings = _settings; + this._fsStatSettings = new fsStat.Settings({ + followSymbolicLink: this._settings.followSymbolicLinks, + fs: this._settings.fs, + throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks + }); + } + _getFullEntryPath(filepath) { + return path.resolve(this._settings.cwd, filepath); + } + _makeEntry(stats, pattern) { + const entry = { + name: pattern, + path: pattern, + dirent: utils.fs.createDirentFromStats(pattern, stats) + }; + if (this._settings.stats) { + entry.stats = stats; + } + return entry; + } + _isFatalError(error) { + return !utils.errno.isEnoentCodeError(error) && !this._settings.suppressErrors; + } +} +exports.default = Reader; -var path = __webpack_require__(4); -var isglob = __webpack_require__(606); -var pathDirname = __webpack_require__(607); -var isWin32 = __webpack_require__(243).platform() === 'win32'; - -module.exports = function globParent(str) { - // flip windows path separators - if (isWin32 && str.indexOf('/') < 0) str = str.split('\\').join('/'); - - // special case for strings ending in enclosure containing path separator - if (/[\{\[].*[\/]*.*[\}\]]$/.test(str)) str += '/'; - // preserves full path in case of trailing path separator - str += 'a'; +/***/ }), +/* 598 */ +/***/ (function(module, exports, __webpack_require__) { - // remove path parts that are globby - do {str = pathDirname.posix(str)} - while (isglob(str) || /(^|[^\\])([\{\[]|\([^\)]+$)/.test(str)); +"use strict"; - // remove escape chars and return result - return str.replace(/\\([\*\?\|\[\]\(\)\{\}])/g, '$1'); -}; +Object.defineProperty(exports, "__esModule", { value: true }); +const path = __webpack_require__(4); +const deep_1 = __webpack_require__(599); +const entry_1 = __webpack_require__(602); +const error_1 = __webpack_require__(603); +const entry_2 = __webpack_require__(604); +class Provider { + constructor(_settings) { + this._settings = _settings; + this.errorFilter = new error_1.default(this._settings); + this.entryFilter = new entry_1.default(this._settings, this._getMicromatchOptions()); + this.deepFilter = new deep_1.default(this._settings, this._getMicromatchOptions()); + this.entryTransformer = new entry_2.default(this._settings); + } + _getRootDirectory(task) { + return path.resolve(this._settings.cwd, task.base); + } + _getReaderOptions(task) { + const basePath = task.base === '.' ? '' : task.base; + return { + basePath, + pathSegmentSeparator: '/', + concurrency: this._settings.concurrency, + deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative), + entryFilter: this.entryFilter.getFilter(task.positive, task.negative), + errorFilter: this.errorFilter.getFilter(), + followSymbolicLinks: this._settings.followSymbolicLinks, + fs: this._settings.fs, + stats: this._settings.stats, + throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink, + transform: this.entryTransformer.getTransformer() + }; + } + _getMicromatchOptions() { + return { + dot: this._settings.dot, + matchBase: this._settings.baseNameMatch, + nobrace: !this._settings.braceExpansion, + nocase: !this._settings.caseSensitiveMatch, + noext: !this._settings.extglob, + noglobstar: !this._settings.globstar, + posix: true, + strictSlashes: false + }; + } +} +exports.default = Provider; /***/ }), -/* 606 */ +/* 599 */ /***/ (function(module, exports, __webpack_require__) { -/*! - * is-glob - * - * Copyright (c) 2014-2016, Jon Schlinkert. - * Licensed under the MIT License. - */ +"use strict"; -var isExtglob = __webpack_require__(388); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils = __webpack_require__(586); +const partial_1 = __webpack_require__(600); +class DeepFilter { + constructor(_settings, _micromatchOptions) { + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + } + getFilter(basePath, positive, negative) { + const matcher = this._getMatcher(positive); + const negativeRe = this._getNegativePatternsRe(negative); + return (entry) => this._filter(basePath, entry, matcher, negativeRe); + } + _getMatcher(patterns) { + return new partial_1.default(patterns, this._settings, this._micromatchOptions); + } + _getNegativePatternsRe(patterns) { + const affectDepthOfReadingPatterns = patterns.filter(utils.pattern.isAffectDepthOfReadingPattern); + return utils.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions); + } + _filter(basePath, entry, matcher, negativeRe) { + if (this._isSkippedByDeep(basePath, entry.path)) { + return false; + } + if (this._isSkippedSymbolicLink(entry)) { + return false; + } + const filepath = utils.path.removeLeadingDotSegment(entry.path); + if (this._isSkippedByPositivePatterns(filepath, matcher)) { + return false; + } + return this._isSkippedByNegativePatterns(filepath, negativeRe); + } + _isSkippedByDeep(basePath, entryPath) { + /** + * Avoid unnecessary depth calculations when it doesn't matter. + */ + if (this._settings.deep === Infinity) { + return false; + } + return this._getEntryLevel(basePath, entryPath) >= this._settings.deep; + } + _getEntryLevel(basePath, entryPath) { + const entryPathDepth = entryPath.split('/').length; + if (basePath === '') { + return entryPathDepth; + } + const basePathDepth = basePath.split('/').length; + return entryPathDepth - basePathDepth; + } + _isSkippedSymbolicLink(entry) { + return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink(); + } + _isSkippedByPositivePatterns(entryPath, matcher) { + return !this._settings.baseNameMatch && !matcher.match(entryPath); + } + _isSkippedByNegativePatterns(entryPath, patternsRe) { + return !utils.pattern.matchAny(entryPath, patternsRe); + } +} +exports.default = DeepFilter; -module.exports = function isGlob(str) { - if (typeof str !== 'string' || str === '') { - return false; - } - if (isExtglob(str)) return true; +/***/ }), +/* 600 */ +/***/ (function(module, exports, __webpack_require__) { - var regex = /(\\).|([*?]|\[.*\]|\{.*\}|\(.*\|.*\)|^!)/; - var match; +"use strict"; - while ((match = regex.exec(str))) { - if (match[2]) return true; - str = str.slice(match.index + match[0].length); - } - return false; -}; +Object.defineProperty(exports, "__esModule", { value: true }); +const matcher_1 = __webpack_require__(601); +class PartialMatcher extends matcher_1.default { + match(filepath) { + const parts = filepath.split('/'); + const levels = parts.length; + const patterns = this._storage.filter((info) => !info.complete || info.segments.length > levels); + for (const pattern of patterns) { + const section = pattern.sections[0]; + /** + * In this case, the pattern has a globstar and we must read all directories unconditionally, + * but only if the level has reached the end of the first group. + * + * fixtures/{a,b}/** + * ^ true/false ^ always true + */ + if (!pattern.complete && levels > section.length) { + return true; + } + const match = parts.every((part, index) => { + const segment = pattern.segments[index]; + if (segment.dynamic && segment.patternRe.test(part)) { + return true; + } + if (!segment.dynamic && segment.pattern === part) { + return true; + } + return false; + }); + if (match) { + return true; + } + } + return false; + } +} +exports.default = PartialMatcher; /***/ }), -/* 607 */ +/* 601 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; - -var path = __webpack_require__(4); -var inspect = __webpack_require__(234).inspect; - -function assertPath(path) { - if (typeof path !== 'string') { - throw new TypeError('Path must be a string. Received ' + inspect(path)); - } -} - -function posix(path) { - assertPath(path); - if (path.length === 0) - return '.'; - var code = path.charCodeAt(0); - var hasRoot = (code === 47/*/*/); - var end = -1; - var matchedSlash = true; - for (var i = path.length - 1; i >= 1; --i) { - code = path.charCodeAt(i); - if (code === 47/*/*/) { - if (!matchedSlash) { - end = i; - break; - } - } else { - // We saw the first non-path separator - matchedSlash = false; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils = __webpack_require__(586); +class Matcher { + constructor(_patterns, _settings, _micromatchOptions) { + this._patterns = _patterns; + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + this._storage = []; + this._fillStorage(); + } + _fillStorage() { + /** + * The original pattern may include `{,*,**,a/*}`, which will lead to problems with matching (unresolved level). + * So, before expand patterns with brace expansion into separated patterns. + */ + const patterns = utils.pattern.expandPatternsWithBraceExpansion(this._patterns); + for (const pattern of patterns) { + const segments = this._getPatternSegments(pattern); + const sections = this._splitSegmentsIntoSections(segments); + this._storage.push({ + complete: sections.length <= 1, + pattern, + segments, + sections + }); + } + } + _getPatternSegments(pattern) { + const parts = utils.pattern.getPatternParts(pattern, this._micromatchOptions); + return parts.map((part) => { + const dynamic = utils.pattern.isDynamicPattern(part, this._settings); + if (!dynamic) { + return { + dynamic: false, + pattern: part + }; + } + return { + dynamic: true, + pattern: part, + patternRe: utils.pattern.makeRe(part, this._micromatchOptions) + }; + }); + } + _splitSegmentsIntoSections(segments) { + return utils.array.splitWhen(segments, (segment) => segment.dynamic && utils.pattern.hasGlobStar(segment.pattern)); } - } - - if (end === -1) - return hasRoot ? '/' : '.'; - if (hasRoot && end === 1) - return '//'; - return path.slice(0, end); } +exports.default = Matcher; -function win32(path) { - assertPath(path); - var len = path.length; - if (len === 0) - return '.'; - var rootEnd = -1; - var end = -1; - var matchedSlash = true; - var offset = 0; - var code = path.charCodeAt(0); - // Try to match a root - if (len > 1) { - if (code === 47/*/*/ || code === 92/*\*/) { - // Possible UNC root +/***/ }), +/* 602 */ +/***/ (function(module, exports, __webpack_require__) { - rootEnd = offset = 1; +"use strict"; - code = path.charCodeAt(1); - if (code === 47/*/*/ || code === 92/*\*/) { - // Matched double path separator at beginning - var j = 2; - var last = j; - // Match 1 or more non-path separators - for (; j < len; ++j) { - code = path.charCodeAt(j); - if (code === 47/*/*/ || code === 92/*\*/) - break; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils = __webpack_require__(586); +class EntryFilter { + constructor(_settings, _micromatchOptions) { + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + this.index = new Map(); + } + getFilter(positive, negative) { + const positiveRe = utils.pattern.convertPatternsToRe(positive, this._micromatchOptions); + const negativeRe = utils.pattern.convertPatternsToRe(negative, this._micromatchOptions); + return (entry) => this._filter(entry, positiveRe, negativeRe); + } + _filter(entry, positiveRe, negativeRe) { + if (this._settings.unique && this._isDuplicateEntry(entry)) { + return false; } - if (j < len && j !== last) { - // Matched! - last = j; - // Match 1 or more path separators - for (; j < len; ++j) { - code = path.charCodeAt(j); - if (code !== 47/*/*/ && code !== 92/*\*/) - break; - } - if (j < len && j !== last) { - // Matched! - last = j; - // Match 1 or more non-path separators - for (; j < len; ++j) { - code = path.charCodeAt(j); - if (code === 47/*/*/ || code === 92/*\*/) - break; - } - if (j === len) { - // We matched a UNC root only - return path; - } - if (j !== last) { - // We matched a UNC root with leftovers - - // Offset by 1 to include the separator after the UNC root to - // treat it as a "normal root" on top of a (UNC) root - rootEnd = offset = j + 1; - } - } + if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) { + return false; } - } - } else if ((code >= 65/*A*/ && code <= 90/*Z*/) || - (code >= 97/*a*/ && code <= 122/*z*/)) { - // Possible device root - - code = path.charCodeAt(1); - if (path.charCodeAt(1) === 58/*:*/) { - rootEnd = offset = 2; - if (len > 2) { - code = path.charCodeAt(2); - if (code === 47/*/*/ || code === 92/*\*/) - rootEnd = offset = 3; + if (this._isSkippedByAbsoluteNegativePatterns(entry.path, negativeRe)) { + return false; + } + const filepath = this._settings.baseNameMatch ? entry.name : entry.path; + const isMatched = this._isMatchToPatterns(filepath, positiveRe) && !this._isMatchToPatterns(entry.path, negativeRe); + if (this._settings.unique && isMatched) { + this._createIndexRecord(entry); } - } + return isMatched; } - } else if (code === 47/*/*/ || code === 92/*\*/) { - return path[0]; - } - - for (var i = len - 1; i >= offset; --i) { - code = path.charCodeAt(i); - if (code === 47/*/*/ || code === 92/*\*/) { - if (!matchedSlash) { - end = i; - break; - } - } else { - // We saw the first non-path separator - matchedSlash = false; + _isDuplicateEntry(entry) { + return this.index.has(entry.path); + } + _createIndexRecord(entry) { + this.index.set(entry.path, undefined); + } + _onlyFileFilter(entry) { + return this._settings.onlyFiles && !entry.dirent.isFile(); + } + _onlyDirectoryFilter(entry) { + return this._settings.onlyDirectories && !entry.dirent.isDirectory(); + } + _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) { + if (!this._settings.absolute) { + return false; + } + const fullpath = utils.path.makeAbsolute(this._settings.cwd, entryPath); + return utils.pattern.matchAny(fullpath, patternsRe); + } + _isMatchToPatterns(entryPath, patternsRe) { + const filepath = utils.path.removeLeadingDotSegment(entryPath); + return utils.pattern.matchAny(filepath, patternsRe); } - } - - if (end === -1) { - if (rootEnd === -1) - return '.'; - else - end = rootEnd; - } - return path.slice(0, end); } - -module.exports = process.platform === 'win32' ? win32 : posix; -module.exports.posix = posix; -module.exports.win32 = win32; +exports.default = EntryFilter; /***/ }), -/* 608 */ +/* 603 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; - -/** - * Module dependencies - */ - -var util = __webpack_require__(234); -var braces = __webpack_require__(609); -var toRegex = __webpack_require__(610); -var extend = __webpack_require__(722); - -/** - * Local dependencies - */ - -var compilers = __webpack_require__(724); -var parsers = __webpack_require__(750); -var cache = __webpack_require__(751); -var utils = __webpack_require__(752); -var MAX_LENGTH = 1024 * 64; - -/** - * The main function takes a list of strings and one or more - * glob patterns to use for matching. - * - * ```js - * var mm = require('micromatch'); - * mm(list, patterns[, options]); - * - * console.log(mm(['a.js', 'a.txt'], ['*.js'])); - * //=> [ 'a.js' ] - * ``` - * @param {Array} `list` A list of strings to match - * @param {String|Array} `patterns` One or more glob patterns to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Array} Returns an array of matches - * @summary false - * @api public - */ - -function micromatch(list, patterns, options) { - patterns = utils.arrayify(patterns); - list = utils.arrayify(list); - - var len = patterns.length; - if (list.length === 0 || len === 0) { - return []; - } - - if (len === 1) { - return micromatch.match(list, patterns[0], options); - } - - var omit = []; - var keep = []; - var idx = -1; - - while (++idx < len) { - var pattern = patterns[idx]; - - if (typeof pattern === 'string' && pattern.charCodeAt(0) === 33 /* ! */) { - omit.push.apply(omit, micromatch.match(list, pattern.slice(1), options)); - } else { - keep.push.apply(keep, micromatch.match(list, pattern, options)); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils = __webpack_require__(586); +class ErrorFilter { + constructor(_settings) { + this._settings = _settings; + } + getFilter() { + return (error) => this._isNonFatalError(error); + } + _isNonFatalError(error) { + return utils.errno.isEnoentCodeError(error) || this._settings.suppressErrors; } - } - - var matches = utils.diff(keep, omit); - if (!options || options.nodupes !== false) { - return utils.unique(matches); - } - - return matches; } +exports.default = ErrorFilter; -/** - * Similar to the main function, but `pattern` must be a string. - * - * ```js - * var mm = require('micromatch'); - * mm.match(list, pattern[, options]); - * - * console.log(mm.match(['a.a', 'a.aa', 'a.b', 'a.c'], '*.a')); - * //=> ['a.a', 'a.aa'] - * ``` - * @param {Array} `list` Array of strings to match - * @param {String} `pattern` Glob pattern to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Array} Returns an array of matches - * @api public - */ - -micromatch.match = function(list, pattern, options) { - if (Array.isArray(pattern)) { - throw new TypeError('expected pattern to be a string'); - } - var unixify = utils.unixify(options); - var isMatch = memoize('match', pattern, options, micromatch.matcher); - var matches = []; +/***/ }), +/* 604 */ +/***/ (function(module, exports, __webpack_require__) { - list = utils.arrayify(list); - var len = list.length; - var idx = -1; +"use strict"; - while (++idx < len) { - var ele = list[idx]; - if (ele === pattern || isMatch(ele)) { - matches.push(utils.value(ele, unixify, options)); +Object.defineProperty(exports, "__esModule", { value: true }); +const utils = __webpack_require__(586); +class EntryTransformer { + constructor(_settings) { + this._settings = _settings; } - } - - // if no options were passed, uniquify results and return - if (typeof options === 'undefined') { - return utils.unique(matches); - } - - if (matches.length === 0) { - if (options.failglob === true) { - throw new Error('no matches found for "' + pattern + '"'); + getTransformer() { + return (entry) => this._transform(entry); } - if (options.nonull === true || options.nullglob === true) { - return [options.unescape ? utils.unescape(pattern) : pattern]; + _transform(entry) { + let filepath = entry.path; + if (this._settings.absolute) { + filepath = utils.path.makeAbsolute(this._settings.cwd, filepath); + filepath = utils.path.unixify(filepath); + } + if (this._settings.markDirectories && entry.dirent.isDirectory()) { + filepath += '/'; + } + if (!this._settings.objectMode) { + return filepath; + } + return Object.assign(Object.assign({}, entry), { path: filepath }); } - } - - // if `opts.ignore` was defined, diff ignored list - if (options.ignore) { - matches = micromatch.not(matches, options.ignore, options); - } - - return options.nodupes !== false ? utils.unique(matches) : matches; -}; - -/** - * Returns true if the specified `string` matches the given glob `pattern`. - * - * ```js - * var mm = require('micromatch'); - * mm.isMatch(string, pattern[, options]); - * - * console.log(mm.isMatch('a.a', '*.a')); - * //=> true - * console.log(mm.isMatch('a.b', '*.a')); - * //=> false - * ``` - * @param {String} `string` String to match - * @param {String} `pattern` Glob pattern to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Boolean} Returns true if the string matches the glob pattern. - * @api public - */ - -micromatch.isMatch = function(str, pattern, options) { - if (typeof str !== 'string') { - throw new TypeError('expected a string: "' + util.inspect(str) + '"'); - } - - if (isEmptyString(str) || isEmptyString(pattern)) { - return false; - } +} +exports.default = EntryTransformer; - var equals = utils.equalsPattern(options); - if (equals(str)) { - return true; - } - var isMatch = memoize('isMatch', pattern, options, micromatch.matcher); - return isMatch(str); -}; +/***/ }), +/* 605 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * Returns true if some of the strings in the given `list` match any of the - * given glob `patterns`. - * - * ```js - * var mm = require('micromatch'); - * mm.some(list, patterns[, options]); - * - * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); - * // true - * console.log(mm.some(['foo.js'], ['*.js', '!foo.js'])); - * // false - * ``` - * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found. - * @param {String|Array} `patterns` One or more glob patterns to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Boolean} Returns true if any patterns match `str` - * @api public - */ +"use strict"; -micromatch.some = function(list, patterns, options) { - if (typeof list === 'string') { - list = [list]; - } - for (var i = 0; i < list.length; i++) { - if (micromatch(list[i], patterns, options).length === 1) { - return true; +Object.defineProperty(exports, "__esModule", { value: true }); +const stream_1 = __webpack_require__(294); +const stream_2 = __webpack_require__(596); +const provider_1 = __webpack_require__(598); +class ProviderStream extends provider_1.default { + constructor() { + super(...arguments); + this._reader = new stream_2.default(this._settings); } - } - return false; -}; - -/** - * Returns true if every string in the given `list` matches - * any of the given glob `patterns`. - * - * ```js - * var mm = require('micromatch'); - * mm.every(list, patterns[, options]); - * - * console.log(mm.every('foo.js', ['foo.js'])); - * // true - * console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); - * // true - * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); - * // false - * console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); - * // false - * ``` - * @param {String|Array} `list` The string or array of strings to test. - * @param {String|Array} `patterns` One or more glob patterns to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Boolean} Returns true if any patterns match `str` - * @api public - */ - -micromatch.every = function(list, patterns, options) { - if (typeof list === 'string') { - list = [list]; - } - for (var i = 0; i < list.length; i++) { - if (micromatch(list[i], patterns, options).length !== 1) { - return false; + read(task) { + const root = this._getRootDirectory(task); + const options = this._getReaderOptions(task); + const source = this.api(root, task, options); + const destination = new stream_1.Readable({ objectMode: true, read: () => { } }); + source + .once('error', (error) => destination.emit('error', error)) + .on('data', (entry) => destination.emit('data', options.transform(entry))) + .once('end', () => destination.emit('end')); + destination + .once('close', () => source.destroy()); + return destination; } - } - return true; -}; - -/** - * Returns true if **any** of the given glob `patterns` - * match the specified `string`. - * - * ```js - * var mm = require('micromatch'); - * mm.any(string, patterns[, options]); - * - * console.log(mm.any('a.a', ['b.*', '*.a'])); - * //=> true - * console.log(mm.any('a.a', 'b.*')); - * //=> false - * ``` - * @param {String|Array} `str` The string to test. - * @param {String|Array} `patterns` One or more glob patterns to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Boolean} Returns true if any patterns match `str` - * @api public - */ + api(root, task, options) { + if (task.dynamic) { + return this._reader.dynamic(root, options); + } + return this._reader.static(task.patterns, options); + } +} +exports.default = ProviderStream; -micromatch.any = function(str, patterns, options) { - if (typeof str !== 'string') { - throw new TypeError('expected a string: "' + util.inspect(str) + '"'); - } - if (isEmptyString(str) || isEmptyString(patterns)) { - return false; - } +/***/ }), +/* 606 */ +/***/ (function(module, exports, __webpack_require__) { - if (typeof patterns === 'string') { - patterns = [patterns]; - } +"use strict"; - for (var i = 0; i < patterns.length; i++) { - if (micromatch.isMatch(str, patterns[i], options)) { - return true; +Object.defineProperty(exports, "__esModule", { value: true }); +const sync_1 = __webpack_require__(607); +const provider_1 = __webpack_require__(598); +class ProviderSync extends provider_1.default { + constructor() { + super(...arguments); + this._reader = new sync_1.default(this._settings); } - } - return false; -}; - -/** - * Returns true if **all** of the given `patterns` match - * the specified string. - * - * ```js - * var mm = require('micromatch'); - * mm.all(string, patterns[, options]); - * - * console.log(mm.all('foo.js', ['foo.js'])); - * // true - * - * console.log(mm.all('foo.js', ['*.js', '!foo.js'])); - * // false - * - * console.log(mm.all('foo.js', ['*.js', 'foo.js'])); - * // true - * - * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); - * // true - * ``` - * @param {String|Array} `str` The string to test. - * @param {String|Array} `patterns` One or more glob patterns to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Boolean} Returns true if any patterns match `str` - * @api public - */ - -micromatch.all = function(str, patterns, options) { - if (typeof str !== 'string') { - throw new TypeError('expected a string: "' + util.inspect(str) + '"'); - } - if (typeof patterns === 'string') { - patterns = [patterns]; - } - for (var i = 0; i < patterns.length; i++) { - if (!micromatch.isMatch(str, patterns[i], options)) { - return false; + read(task) { + const root = this._getRootDirectory(task); + const options = this._getReaderOptions(task); + const entries = this.api(root, task, options); + return entries.map(options.transform); } - } - return true; -}; - -/** - * Returns a list of strings that _**do not match any**_ of the given `patterns`. - * - * ```js - * var mm = require('micromatch'); - * mm.not(list, patterns[, options]); - * - * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); - * //=> ['b.b', 'c.c'] - * ``` - * @param {Array} `list` Array of strings to match. - * @param {String|Array} `patterns` One or more glob pattern to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Array} Returns an array of strings that **do not match** the given patterns. - * @api public - */ - -micromatch.not = function(list, patterns, options) { - var opts = extend({}, options); - var ignore = opts.ignore; - delete opts.ignore; - - var unixify = utils.unixify(opts); - list = utils.arrayify(list).map(unixify); - - var matches = utils.diff(list, micromatch(list, patterns, opts)); - if (ignore) { - matches = utils.diff(matches, micromatch(list, ignore)); - } + api(root, task, options) { + if (task.dynamic) { + return this._reader.dynamic(root, options); + } + return this._reader.static(task.patterns, options); + } +} +exports.default = ProviderSync; - return opts.nodupes !== false ? utils.unique(matches) : matches; -}; -/** - * Returns true if the given `string` contains the given pattern. Similar - * to [.isMatch](#isMatch) but the pattern can match any part of the string. - * - * ```js - * var mm = require('micromatch'); - * mm.contains(string, pattern[, options]); - * - * console.log(mm.contains('aa/bb/cc', '*b')); - * //=> true - * console.log(mm.contains('aa/bb/cc', '*d')); - * //=> false - * ``` - * @param {String} `str` The string to match. - * @param {String|Array} `patterns` Glob pattern to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Boolean} Returns true if the patter matches any part of `str`. - * @api public - */ +/***/ }), +/* 607 */ +/***/ (function(module, exports, __webpack_require__) { -micromatch.contains = function(str, patterns, options) { - if (typeof str !== 'string') { - throw new TypeError('expected a string: "' + util.inspect(str) + '"'); - } +"use strict"; - if (typeof patterns === 'string') { - if (isEmptyString(str) || isEmptyString(patterns)) { - return false; +Object.defineProperty(exports, "__esModule", { value: true }); +const fsStat = __webpack_require__(410); +const fsWalk = __webpack_require__(415); +const reader_1 = __webpack_require__(597); +class ReaderSync extends reader_1.default { + constructor() { + super(...arguments); + this._walkSync = fsWalk.walkSync; + this._statSync = fsStat.statSync; + } + dynamic(root, options) { + return this._walkSync(root, options); + } + static(patterns, options) { + const entries = []; + for (const pattern of patterns) { + const filepath = this._getFullEntryPath(pattern); + const entry = this._getEntry(filepath, pattern, options); + if (entry === null || !options.entryFilter(entry)) { + continue; + } + entries.push(entry); + } + return entries; } - - var equals = utils.equalsPattern(patterns, options); - if (equals(str)) { - return true; + _getEntry(filepath, pattern, options) { + try { + const stats = this._getStat(filepath); + return this._makeEntry(stats, pattern); + } + catch (error) { + if (options.errorFilter(error)) { + return null; + } + throw error; + } } - var contains = utils.containsPattern(patterns, options); - if (contains(str)) { - return true; + _getStat(filepath) { + return this._statSync(filepath, this._fsStatSettings); } - } +} +exports.default = ReaderSync; - var opts = extend({}, options, {contains: true}); - return micromatch.any(str, patterns, opts); -}; -/** - * Returns true if the given pattern and options should enable - * the `matchBase` option. - * @return {Boolean} - * @api private - */ +/***/ }), +/* 608 */ +/***/ (function(module, exports, __webpack_require__) { -micromatch.matchBase = function(pattern, options) { - if (pattern && pattern.indexOf('/') !== -1 || !options) return false; - return options.basename === true || options.matchBase === true; -}; +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0; +const fs = __webpack_require__(253); +const os = __webpack_require__(243); /** - * Filter the keys of the given object with the given `glob` pattern - * and `options`. Does not attempt to match nested keys. If you need this feature, - * use [glob-object][] instead. - * - * ```js - * var mm = require('micromatch'); - * mm.matchKeys(object, patterns[, options]); - * - * var obj = { aa: 'a', ab: 'b', ac: 'c' }; - * console.log(mm.matchKeys(obj, '*b')); - * //=> { ab: 'b' } - * ``` - * @param {Object} `object` The object with keys to filter. - * @param {String|Array} `patterns` One or more glob patterns to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Object} Returns an object with only keys that match the given patterns. - * @api public + * The `os.cpus` method can return zero. We expect the number of cores to be greater than zero. + * https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107 */ - -micromatch.matchKeys = function(obj, patterns, options) { - if (!utils.isObject(obj)) { - throw new TypeError('expected the first argument to be an object'); - } - var keys = micromatch(Object.keys(obj), patterns, options); - return utils.pick(obj, keys); +const CPU_COUNT = Math.max(os.cpus().length, 1); +exports.DEFAULT_FILE_SYSTEM_ADAPTER = { + lstat: fs.lstat, + lstatSync: fs.lstatSync, + stat: fs.stat, + statSync: fs.statSync, + readdir: fs.readdir, + readdirSync: fs.readdirSync }; +class Settings { + constructor(_options = {}) { + this._options = _options; + this.absolute = this._getValue(this._options.absolute, false); + this.baseNameMatch = this._getValue(this._options.baseNameMatch, false); + this.braceExpansion = this._getValue(this._options.braceExpansion, true); + this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true); + this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT); + this.cwd = this._getValue(this._options.cwd, process.cwd()); + this.deep = this._getValue(this._options.deep, Infinity); + this.dot = this._getValue(this._options.dot, false); + this.extglob = this._getValue(this._options.extglob, true); + this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true); + this.fs = this._getFileSystemMethods(this._options.fs); + this.globstar = this._getValue(this._options.globstar, true); + this.ignore = this._getValue(this._options.ignore, []); + this.markDirectories = this._getValue(this._options.markDirectories, false); + this.objectMode = this._getValue(this._options.objectMode, false); + this.onlyDirectories = this._getValue(this._options.onlyDirectories, false); + this.onlyFiles = this._getValue(this._options.onlyFiles, true); + this.stats = this._getValue(this._options.stats, false); + this.suppressErrors = this._getValue(this._options.suppressErrors, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false); + this.unique = this._getValue(this._options.unique, true); + if (this.onlyDirectories) { + this.onlyFiles = false; + } + if (this.stats) { + this.objectMode = true; + } + } + _getValue(option, value) { + return option === undefined ? value : option; + } + _getFileSystemMethods(methods = {}) { + return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods); + } +} +exports.default = Settings; -/** - * Returns a memoized matcher function from the given glob `pattern` and `options`. - * The returned function takes a string to match as its only argument and returns - * true if the string is a match. - * - * ```js - * var mm = require('micromatch'); - * mm.matcher(pattern[, options]); - * - * var isMatch = mm.matcher('*.!(*a)'); - * console.log(isMatch('a.a')); - * //=> false - * console.log(isMatch('a.b')); - * //=> true - * ``` - * @param {String} `pattern` Glob pattern - * @param {Object} `options` See available [options](#options) for changing how matches are performed. - * @return {Function} Returns a matcher function. - * @api public - */ - -micromatch.matcher = function matcher(pattern, options) { - if (Array.isArray(pattern)) { - return compose(pattern, options, matcher); - } - // if pattern is a regex - if (pattern instanceof RegExp) { - return test(pattern); - } +/***/ }), +/* 609 */ +/***/ (function(module, exports, __webpack_require__) { - // if pattern is invalid - if (!utils.isString(pattern)) { - throw new TypeError('expected pattern to be an array, string or regex'); - } +"use strict"; - // if pattern is a non-glob string - if (!utils.hasSpecialChars(pattern)) { - if (options && options.nocase === true) { - pattern = pattern.toLowerCase(); - } - return utils.matchPath(pattern, options); - } +const {promisify} = __webpack_require__(234); +const fs = __webpack_require__(253); +const path = __webpack_require__(4); +const fastGlob = __webpack_require__(584); +const gitIgnore = __webpack_require__(450); +const slash = __webpack_require__(451); - // if pattern is a glob string - var re = micromatch.makeRe(pattern, options); +const DEFAULT_IGNORE = [ + '**/node_modules/**', + '**/flow-typed/**', + '**/coverage/**', + '**/.git' +]; - // if `options.matchBase` or `options.basename` is defined - if (micromatch.matchBase(pattern, options)) { - return utils.matchBasename(re, options); - } +const readFileP = promisify(fs.readFile); - function test(regex) { - var equals = utils.equalsPattern(options); - var unixify = utils.unixify(options); +const mapGitIgnorePatternTo = base => ignore => { + if (ignore.startsWith('!')) { + return '!' + path.posix.join(base, ignore.slice(1)); + } - return function(str) { - if (equals(str)) { - return true; - } + return path.posix.join(base, ignore); +}; - if (regex.test(unixify(str))) { - return true; - } - return false; - }; - } +const parseGitIgnore = (content, options) => { + const base = slash(path.relative(options.cwd, path.dirname(options.fileName))); - var fn = test(re); - Object.defineProperty(fn, 'result', { - configurable: true, - enumerable: false, - value: re.result - }); - return fn; + return content + .split(/\r?\n/) + .filter(Boolean) + .filter(line => !line.startsWith('#')) + .map(mapGitIgnorePatternTo(base)); }; -/** - * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match. - * - * ```js - * var mm = require('micromatch'); - * mm.capture(pattern, string[, options]); - * - * console.log(mm.capture('test/*.js', 'test/foo.js')); - * //=> ['foo'] - * console.log(mm.capture('test/*.js', 'foo/bar.css')); - * //=> null - * ``` - * @param {String} `pattern` Glob pattern to use for matching. - * @param {String} `string` String to match - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Boolean} Returns an array of captures if the string matches the glob pattern, otherwise `null`. - * @api public - */ +const reduceIgnore = files => { + const ignores = gitIgnore(); + for (const file of files) { + ignores.add(parseGitIgnore(file.content, { + cwd: file.cwd, + fileName: file.filePath + })); + } -micromatch.capture = function(pattern, str, options) { - var re = micromatch.makeRe(pattern, extend({capture: true}, options)); - var unixify = utils.unixify(options); + return ignores; +}; - function match() { - return function(string) { - var match = re.exec(unixify(string)); - if (!match) { - return null; - } +const ensureAbsolutePathForCwd = (cwd, p) => { + cwd = slash(cwd); + if (path.isAbsolute(p)) { + if (slash(p).startsWith(cwd)) { + return p; + } - return match.slice(1); - }; - } + throw new Error(`Path ${p} is not in cwd ${cwd}`); + } - var capture = memoize('capture', pattern, options, match); - return capture(str); + return path.join(cwd, p); }; -/** - * Create a regular expression from the given glob `pattern`. - * - * ```js - * var mm = require('micromatch'); - * mm.makeRe(pattern[, options]); - * - * console.log(mm.makeRe('*.js')); - * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ - * ``` - * @param {String} `pattern` A glob pattern to convert to regex. - * @param {Object} `options` See available [options](#options) for changing how matches are performed. - * @return {RegExp} Returns a regex created from the given pattern. - * @api public - */ +const getIsIgnoredPredecate = (ignores, cwd) => { + return p => ignores.ignores(slash(path.relative(cwd, ensureAbsolutePathForCwd(cwd, p.path || p)))); +}; -micromatch.makeRe = function(pattern, options) { - if (typeof pattern !== 'string') { - throw new TypeError('expected pattern to be a string'); - } +const getFile = async (file, cwd) => { + const filePath = path.join(cwd, file); + const content = await readFileP(filePath, 'utf8'); - if (pattern.length > MAX_LENGTH) { - throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters'); - } + return { + cwd, + filePath, + content + }; +}; - function makeRe() { - var result = micromatch.create(pattern, options); - var ast_array = []; - var output = result.map(function(obj) { - obj.ast.state = obj.state; - ast_array.push(obj.ast); - return obj.output; - }); +const getFileSync = (file, cwd) => { + const filePath = path.join(cwd, file); + const content = fs.readFileSync(filePath, 'utf8'); - var regex = toRegex(output.join('|'), options); - Object.defineProperty(regex, 'result', { - configurable: true, - enumerable: false, - value: ast_array - }); - return regex; - } + return { + cwd, + filePath, + content + }; +}; - return memoize('makeRe', pattern, options, makeRe); +const normalizeOptions = ({ + ignore = [], + cwd = slash(process.cwd()) +} = {}) => { + return {ignore, cwd}; }; -/** - * Expand the given brace `pattern`. - * - * ```js - * var mm = require('micromatch'); - * console.log(mm.braces('foo/{a,b}/bar')); - * //=> ['foo/(a|b)/bar'] - * - * console.log(mm.braces('foo/{a,b}/bar', {expand: true})); - * //=> ['foo/(a|b)/bar'] - * ``` - * @param {String} `pattern` String with brace pattern to expand. - * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options. - * @return {Array} - * @api public - */ +module.exports = async options => { + options = normalizeOptions(options); -micromatch.braces = function(pattern, options) { - if (typeof pattern !== 'string' && !Array.isArray(pattern)) { - throw new TypeError('expected pattern to be an array or string'); - } + const paths = await fastGlob('**/.gitignore', { + ignore: DEFAULT_IGNORE.concat(options.ignore), + cwd: options.cwd + }); - function expand() { - if (options && options.nobrace === true || !/\{.*\}/.test(pattern)) { - return utils.arrayify(pattern); - } - return braces(pattern, options); - } + const files = await Promise.all(paths.map(file => getFile(file, options.cwd))); + const ignores = reduceIgnore(files); - return memoize('braces', pattern, options, expand); + return getIsIgnoredPredecate(ignores, options.cwd); }; -/** - * Proxy to the [micromatch.braces](#method), for parity with - * minimatch. - */ +module.exports.sync = options => { + options = normalizeOptions(options); -micromatch.braceExpand = function(pattern, options) { - var opts = extend({}, options, {expand: true}); - return micromatch.braces(pattern, opts); + const paths = fastGlob.sync('**/.gitignore', { + ignore: DEFAULT_IGNORE.concat(options.ignore), + cwd: options.cwd + }); + + const files = paths.map(file => getFileSync(file, options.cwd)); + const ignores = reduceIgnore(files); + + return getIsIgnoredPredecate(ignores, options.cwd); }; -/** - * Parses the given glob `pattern` and returns an array of abstract syntax - * trees (ASTs), with the compiled `output` and optional source `map` on - * each AST. - * - * ```js - * var mm = require('micromatch'); - * mm.create(pattern[, options]); - * - * console.log(mm.create('abc/*.js')); - * // [{ options: { source: 'string', sourcemap: true }, - * // state: {}, - * // compilers: - * // { ... }, - * // output: '(\\.[\\\\\\/])?abc\\/(?!\\.)(?=.)[^\\/]*?\\.js', - * // ast: - * // { type: 'root', - * // errors: [], - * // nodes: - * // [ ... ], - * // dot: false, - * // input: 'abc/*.js' }, - * // parsingErrors: [], - * // map: - * // { version: 3, - * // sources: [ 'string' ], - * // names: [], - * // mappings: 'AAAA,GAAG,EAAC,kBAAC,EAAC,EAAE', - * // sourcesContent: [ 'abc/*.js' ] }, - * // position: { line: 1, column: 28 }, - * // content: {}, - * // files: {}, - * // idx: 6 }] - * ``` - * @param {String} `pattern` Glob pattern to parse and compile. - * @param {Object} `options` Any [options](#options) to change how parsing and compiling is performed. - * @return {Object} Returns an object with the parsed AST, compiled string and optional source map. - * @api public - */ -micromatch.create = function(pattern, options) { - return memoize('create', pattern, options, function() { - function create(str, opts) { - return micromatch.compile(micromatch.parse(str, opts), opts); - } +/***/ }), +/* 610 */ +/***/ (function(module, exports, __webpack_require__) { - pattern = micromatch.braces(pattern, options); - var len = pattern.length; - var idx = -1; - var res = []; +"use strict"; - while (++idx < len) { - res.push(create(pattern[idx], options)); - } - return res; - }); -}; +const {Transform} = __webpack_require__(294); -/** - * Parse the given `str` with the given `options`. - * - * ```js - * var mm = require('micromatch'); - * mm.parse(pattern[, options]); - * - * var ast = mm.parse('a/{b,c}/d'); - * console.log(ast); - * // { type: 'root', - * // errors: [], - * // input: 'a/{b,c}/d', - * // nodes: - * // [ { type: 'bos', val: '' }, - * // { type: 'text', val: 'a/' }, - * // { type: 'brace', - * // nodes: - * // [ { type: 'brace.open', val: '{' }, - * // { type: 'text', val: 'b,c' }, - * // { type: 'brace.close', val: '}' } ] }, - * // { type: 'text', val: '/d' }, - * // { type: 'eos', val: '' } ] } - * ``` - * @param {String} `str` - * @param {Object} `options` - * @return {Object} Returns an AST - * @api public - */ +class ObjectTransform extends Transform { + constructor() { + super({ + objectMode: true + }); + } +} -micromatch.parse = function(pattern, options) { - if (typeof pattern !== 'string') { - throw new TypeError('expected a string'); - } +class FilterStream extends ObjectTransform { + constructor(filter) { + super(); + this._filter = filter; + } - function parse() { - var snapdragon = utils.instantiate(null, options); - parsers(snapdragon, options); + _transform(data, encoding, callback) { + if (this._filter(data)) { + this.push(data); + } + + callback(); + } +} + +class UniqueStream extends ObjectTransform { + constructor() { + super(); + this._pushed = new Set(); + } + + _transform(data, encoding, callback) { + if (!this._pushed.has(data)) { + this.push(data); + this._pushed.add(data); + } - var ast = snapdragon.parse(pattern, options); - utils.define(ast, 'snapdragon', snapdragon); - ast.input = pattern; - return ast; - } + callback(); + } +} - return memoize('parse', pattern, options, parse); +module.exports = { + FilterStream, + UniqueStream }; -/** - * Compile the given `ast` or string with the given `options`. - * - * ```js - * var mm = require('micromatch'); - * mm.compile(ast[, options]); + +/***/ }), +/* 611 */ +/***/ (function(module, exports) { + +/*! + * normalize-path * - * var ast = mm.parse('a/{b,c}/d'); - * console.log(mm.compile(ast)); - * // { options: { source: 'string' }, - * // state: {}, - * // compilers: - * // { eos: [Function], - * // noop: [Function], - * // bos: [Function], - * // brace: [Function], - * // 'brace.open': [Function], - * // text: [Function], - * // 'brace.close': [Function] }, - * // output: [ 'a/(b|c)/d' ], - * // ast: - * // { ... }, - * // parsingErrors: [] } - * ``` - * @param {Object|String} `ast` - * @param {Object} `options` - * @return {Object} Returns an object that has an `output` property with the compiled string. - * @api public + * Copyright (c) 2014-2018, Jon Schlinkert. + * Released under the MIT License. */ -micromatch.compile = function(ast, options) { - if (typeof ast === 'string') { - ast = micromatch.parse(ast, options); +module.exports = function(path, stripTrailing) { + if (typeof path !== 'string') { + throw new TypeError('expected path to be a string'); } - return memoize('compile', ast.input, options, function() { - var snapdragon = utils.instantiate(ast, options); - compilers(snapdragon, options); - return snapdragon.compile(ast, options); - }); -}; + if (path === '\\' || path === '/') return '/'; -/** - * Clear the regex cache. - * - * ```js - * mm.clearCache(); - * ``` - * @api public - */ + var len = path.length; + if (len <= 1) return path; -micromatch.clearCache = function() { - micromatch.cache.caches = {}; + // ensure that win32 namespaces has two leading slashes, so that the path is + // handled properly by the win32 version of path.parse() after being normalized + // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces + var prefix = ''; + if (len > 4 && path[3] === '\\') { + var ch = path[2]; + if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') { + path = path.slice(2); + prefix = '//'; + } + } + + var segs = path.split(/[/\\]+/); + if (stripTrailing !== false && segs[segs.length - 1] === '') { + segs.pop(); + } + return prefix + segs.join('/'); }; -/** - * Returns true if the given value is effectively an empty string - */ -function isEmptyString(val) { - return String(val) === '' || String(val) === './'; -} +/***/ }), +/* 612 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -/** - * Compose a matcher function with the given patterns. - * This allows matcher functions to be compiled once and - * called multiple times. +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "regeneratePackageJson", function() { return regeneratePackageJson; }); +/* harmony import */ var fs_promises__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(613); +/* harmony import */ var fs_promises__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs_promises__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _kbn_dev_utils_sort_package_json__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(614); +/* harmony import */ var _kbn_dev_utils_sort_package_json__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_kbn_dev_utils_sort_package_json__WEBPACK_IMPORTED_MODULE_2__); +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. */ -function compose(patterns, options, matcher) { - var matchers; - return memoize('compose', String(patterns), options, function() { - return function(file) { - // delay composition until it's invoked the first time, - // after that it won't be called again - if (!matchers) { - matchers = []; - for (var i = 0; i < patterns.length; i++) { - matchers.push(matcher(patterns[i], options)); - } - } - var len = matchers.length; - while (len--) { - if (matchers[len](file) === true) { - return true; - } - } - return false; - }; - }); +async function regeneratePackageJson(rootPath) { + const path = path__WEBPACK_IMPORTED_MODULE_1___default.a.resolve(rootPath, 'package.json'); + const json = await fs_promises__WEBPACK_IMPORTED_MODULE_0___default.a.readFile(path, 'utf8'); + await fs_promises__WEBPACK_IMPORTED_MODULE_0___default.a.writeFile(path, Object(_kbn_dev_utils_sort_package_json__WEBPACK_IMPORTED_MODULE_2__["sortPackageJson"])(json)); } -/** - * Memoize a generated regex or function. A unique key is generated - * from the `type` (usually method name), the `pattern`, and - * user-defined options. - */ - -function memoize(type, pattern, options, fn) { - var key = utils.createKey(type + '=' + pattern, options); +/***/ }), +/* 613 */ +/***/ (function(module, exports) { - if (options && options.cache === false) { - return fn(pattern, options); - } +module.exports = require("fs/promises"); - if (cache.has(type, key)) { - return cache.get(type, key); - } +/***/ }), +/* 614 */ +/***/ (function(module, exports, __webpack_require__) { - var val = fn(pattern, options); - cache.set(type, key, val); - return val; -} +"use strict"; -/** - * Expose compiler, parser and cache on `micromatch` - */ -micromatch.compilers = compilers; -micromatch.parsers = parsers; -micromatch.caches = cache.caches; +var _interopRequireDefault = __webpack_require__(7); -/** - * Expose `micromatch` - * @type {Function} - */ +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.sortPackageJson = sortPackageJson; -module.exports = micromatch; +var _sortPackageJson = _interopRequireDefault(__webpack_require__(615)); +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ +function sortPackageJson(json) { + return JSON.stringify((0, _sortPackageJson.default)(JSON.parse(json), { + // top level keys in the order they were written when this was implemented + sortOrder: ['name', 'description', 'keywords', 'private', 'version', 'branch', 'main', 'browser', 'types', 'tsdocMetadata', 'build', 'homepage', 'bugs', 'license', 'kibana', 'author', 'scripts', 'repository', 'engines', 'resolutions'] + }), null, 2) + '\n'; +} /***/ }), -/* 609 */ +/* 615 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +const sortObjectKeys = __webpack_require__(616) +const detectIndent = __webpack_require__(617) +const detectNewline = __webpack_require__(618).graceful +const gitHooks = __webpack_require__(619) +const isPlainObject = __webpack_require__(620) + +const hasOwnProperty = (object, property) => + Object.prototype.hasOwnProperty.call(object, property) +const pipe = (fns) => (x, ...args) => + fns.reduce((result, fn) => fn(result, ...args), x) +const onArray = (fn) => (x) => (Array.isArray(x) ? fn(x) : x) +const onStringArray = (fn) => (x) => + Array.isArray(x) && x.every((item) => typeof item === 'string') ? fn(x) : x +const uniq = onStringArray((xs) => xs.filter((x, i) => i === xs.indexOf(x))) +const sortArray = onStringArray((array) => [...array].sort()) +const uniqAndSortArray = pipe([uniq, sortArray]) +const onObject = (fn) => (x, ...args) => (isPlainObject(x) ? fn(x, ...args) : x) +const sortObjectBy = (comparator, deep) => { + const over = onObject((object) => { + object = sortObjectKeys(object, comparator) + if (deep) { + for (const [key, value] of Object.entries(object)) { + object[key] = over(value) + } + } + return object + }) + return over +} +const sortObject = sortObjectBy() +const sortURLObject = sortObjectBy(['type', 'url']) +const sortPeopleObject = sortObjectBy(['name', 'email', 'url']) +const sortDirectories = sortObjectBy([ + 'lib', + 'bin', + 'man', + 'doc', + 'example', + 'test', +]) +const overProperty = (property, over) => (object, ...args) => + hasOwnProperty(object, property) + ? Object.assign(object, { [property]: over(object[property], ...args) }) + : object +const sortGitHooks = sortObjectBy(gitHooks) -/** - * Module dependencies - */ +// https://github.com/eslint/eslint/blob/acc0e47572a9390292b4e313b4a4bf360d236358/conf/config-schema.js +const eslintBaseConfigProperties = [ + // `files` and `excludedFiles` are only on `overrides[]` + // for easier sort `overrides[]`, + // add them to here, so we don't need sort `overrides[]` twice + 'files', + 'excludedFiles', + // baseConfig + 'env', + 'parser', + 'parserOptions', + 'settings', + 'plugins', + 'extends', + 'rules', + 'overrides', + 'globals', + 'processor', + 'noInlineConfig', + 'reportUnusedDisableDirectives', +] +const sortEslintConfig = onObject( + pipe([ + sortObjectBy(eslintBaseConfigProperties), + overProperty('env', sortObject), + overProperty('globals', sortObject), + overProperty( + 'overrides', + onArray((overrides) => overrides.map(sortEslintConfig)), + ), + overProperty('parserOptions', sortObject), + overProperty( + 'rules', + sortObjectBy( + (rule1, rule2) => + rule1.split('/').length - rule2.split('/').length || + rule1.localeCompare(rule2), + ), + ), + overProperty('settings', sortObject), + ]), +) +const sortVSCodeBadgeObject = sortObjectBy(['description', 'url', 'href']) -var toRegex = __webpack_require__(610); -var unique = __webpack_require__(630); -var extend = __webpack_require__(631); +const sortPrettierConfig = onObject( + pipe([ + // sort keys alphabetically, but put `overrides` at bottom + (config) => + sortObjectKeys(config, [ + ...Object.keys(config) + .filter((key) => key !== 'overrides') + .sort(), + 'overrides', + ]), + // if `config.overrides` exists + overProperty( + 'overrides', + // and `config.overrides` is an array + onArray((overrides) => + overrides.map( + pipe([ + // sort `config.overrides[]` alphabetically + sortObject, + // sort `config.overrides[].options` alphabetically + overProperty('options', sortObject), + ]), + ), + ), + ), + ]), +) -/** - * Local dependencies - */ +// See https://docs.npmjs.com/misc/scripts +const defaultNpmScripts = new Set([ + 'install', + 'pack', + 'prepare', + 'publish', + 'restart', + 'shrinkwrap', + 'start', + 'stop', + 'test', + 'uninstall', + 'version', +]) -var compilers = __webpack_require__(633); -var parsers = __webpack_require__(648); -var Braces = __webpack_require__(653); -var utils = __webpack_require__(634); -var MAX_LENGTH = 1024 * 64; -var cache = {}; +const hasDevDependency = (dependency, packageJson) => { + return ( + 'devDependencies' in packageJson && + !!packageJson.devDependencies[dependency] + ) +} -/** - * Convert the given `braces` pattern into a regex-compatible string. By default, only one string is generated for every input string. Set `options.expand` to true to return an array of patterns (similar to Bash or minimatch. Before using `options.expand`, it's recommended that you read the [performance notes](#performance)). - * - * ```js - * var braces = require('braces'); - * console.log(braces('{a,b,c}')); - * //=> ['(a|b|c)'] - * - * console.log(braces('{a,b,c}', {expand: true})); - * //=> ['a', 'b', 'c'] - * ``` - * @param {String} `str` - * @param {Object} `options` - * @return {String} - * @api public - */ +const sortScripts = onObject((scripts, packageJson) => { + const names = Object.keys(scripts) + const prefixable = new Set() -function braces(pattern, options) { - var key = utils.createKey(String(pattern), options); - var arr = []; + const keys = names.map((name) => { + const omitted = name.replace(/^(?:pre|post)/, '') + if (defaultNpmScripts.has(omitted) || names.includes(omitted)) { + prefixable.add(omitted) + return omitted + } + return name + }) - var disabled = options && options.cache === false; - if (!disabled && cache.hasOwnProperty(key)) { - return cache[key]; + if (!hasDevDependency('npm-run-all', packageJson)) { + keys.sort() } - if (Array.isArray(pattern)) { - for (var i = 0; i < pattern.length; i++) { - arr.push.apply(arr, braces.create(pattern[i], options)); + const order = keys.reduce( + (order, key) => + order.concat( + prefixable.has(key) ? [`pre${key}`, key, `post${key}`] : [key], + ), + [], + ) + + return sortObjectKeys(scripts, order) +}) + +// fields marked `vscode` are for `Visual Studio Code extension manifest` only +// https://code.visualstudio.com/api/references/extension-manifest +// Supported fields: +// publisher, displayName, categories, galleryBanner, preview, contributes, +// activationEvents, badges, markdown, qna, extensionPack, +// extensionDependencies, icon + +// field.key{string}: field name +// field.over{function}: sort field subKey +const fields = [ + { key: '$schema' }, + { key: 'name' }, + /* vscode */ { key: 'displayName' }, + { key: 'version' }, + { key: 'private' }, + { key: 'description' }, + /* vscode */ { key: 'categories', over: uniq }, + { key: 'keywords', over: uniq }, + { key: 'homepage' }, + { key: 'bugs', over: sortObjectBy(['url', 'email']) }, + { key: 'repository', over: sortURLObject }, + { key: 'funding', over: sortURLObject }, + { key: 'license', over: sortURLObject }, + /* vscode */ { key: 'qna' }, + { key: 'author', over: sortPeopleObject }, + { + key: 'maintainers', + over: onArray((maintainers) => maintainers.map(sortPeopleObject)), + }, + { + key: 'contributors', + over: onArray((contributors) => contributors.map(sortPeopleObject)), + }, + /* vscode */ { key: 'publisher' }, + { key: 'sideEffects' }, + { key: 'type' }, + { key: 'imports' }, + { key: 'exports' }, + { key: 'main' }, + { key: 'umd:main' }, + { key: 'jsdelivr' }, + { key: 'unpkg' }, + { key: 'module' }, + { key: 'source' }, + { key: 'jsnext:main' }, + { key: 'browser' }, + { key: 'types' }, + { key: 'typesVersions' }, + { key: 'typings' }, + { key: 'style' }, + { key: 'example' }, + { key: 'examplestyle' }, + { key: 'assets' }, + { key: 'bin', over: sortObject }, + { key: 'man' }, + { key: 'directories', over: sortDirectories }, + { key: 'files', over: uniq }, + { key: 'workspaces' }, + // node-pre-gyp https://www.npmjs.com/package/node-pre-gyp#1-add-new-entries-to-your-packagejson + { + key: 'binary', + over: sortObjectBy([ + 'module_name', + 'module_path', + 'remote_path', + 'package_name', + 'host', + ]), + }, + { key: 'scripts', over: sortScripts }, + { key: 'betterScripts', over: sortScripts }, + /* vscode */ { key: 'contributes', over: sortObject }, + /* vscode */ { key: 'activationEvents', over: uniq }, + { key: 'husky', over: overProperty('hooks', sortGitHooks) }, + { key: 'simple-git-hooks', over: sortGitHooks }, + { key: 'pre-commit' }, + { key: 'commitlint', over: sortObject }, + { key: 'lint-staged' }, + { key: 'config', over: sortObject }, + { key: 'nodemonConfig', over: sortObject }, + { key: 'browserify', over: sortObject }, + { key: 'babel', over: sortObject }, + { key: 'browserslist' }, + { key: 'xo', over: sortObject }, + { key: 'prettier', over: sortPrettierConfig }, + { key: 'eslintConfig', over: sortEslintConfig }, + { key: 'eslintIgnore' }, + { key: 'npmpkgjsonlint', over: sortObject }, + { key: 'npmPackageJsonLintConfig', over: sortObject }, + { key: 'npmpackagejsonlint', over: sortObject }, + { key: 'release', over: sortObject }, + { key: 'remarkConfig', over: sortObject }, + { key: 'stylelint' }, + { key: 'ava', over: sortObject }, + { key: 'jest', over: sortObject }, + { key: 'mocha', over: sortObject }, + { key: 'nyc', over: sortObject }, + { key: 'c8', over: sortObject }, + { key: 'tap', over: sortObject }, + { key: 'resolutions', over: sortObject }, + { key: 'dependencies', over: sortObject }, + { key: 'devDependencies', over: sortObject }, + { key: 'dependenciesMeta', over: sortObjectBy(undefined, true) }, + { key: 'peerDependencies', over: sortObject }, + // TODO: only sort depth = 2 + { key: 'peerDependenciesMeta', over: sortObjectBy(undefined, true) }, + { key: 'optionalDependencies', over: sortObject }, + { key: 'bundledDependencies', over: uniqAndSortArray }, + { key: 'bundleDependencies', over: uniqAndSortArray }, + /* vscode */ { key: 'extensionPack', over: uniqAndSortArray }, + /* vscode */ { key: 'extensionDependencies', over: uniqAndSortArray }, + { key: 'flat' }, + { key: 'engines', over: sortObject }, + { key: 'engineStrict', over: sortObject }, + { key: 'languageName' }, + { key: 'os' }, + { key: 'cpu' }, + { key: 'preferGlobal', over: sortObject }, + { key: 'publishConfig', over: sortObject }, + /* vscode */ { key: 'icon' }, + /* vscode */ { + key: 'badges', + over: onArray((badge) => badge.map(sortVSCodeBadgeObject)), + }, + /* vscode */ { key: 'galleryBanner', over: sortObject }, + /* vscode */ { key: 'preview' }, + /* vscode */ { key: 'markdown' }, +] + +const defaultSortOrder = fields.map(({ key }) => key) +const overFields = pipe( + fields.reduce((fns, { key, over }) => { + if (over) { + fns.push(overProperty(key, over)) } - } else { - arr = braces.create(pattern, options); - } + return fns + }, []), +) - if (options && options.nodupes === true) { - arr = unique(arr); - } +function editStringJSON(json, over) { + if (typeof json === 'string') { + const { indent } = detectIndent(json) + const endCharacters = json.slice(-1) === '\n' ? '\n' : '' + const newline = detectNewline(json) + json = JSON.parse(json) - if (!disabled) { - cache[key] = arr; + let result = JSON.stringify(over(json), null, indent) + endCharacters + if (newline === '\r\n') { + result = result.replace(/\n/g, newline) + } + return result } - return arr; + + return over(json) } -/** - * Expands a brace pattern into an array. This method is called by the main [braces](#braces) function when `options.expand` is true. Before using this method it's recommended that you read the [performance notes](#performance)) and advantages of using [.optimize](#optimize) instead. - * - * ```js - * var braces = require('braces'); - * console.log(braces.expand('a/{b,c}/d')); - * //=> ['a/b/d', 'a/c/d']; - * ``` - * @param {String} `pattern` Brace pattern - * @param {Object} `options` - * @return {Array} Returns an array of expanded values. - * @api public - */ +const isPrivateKey = (key) => key[0] === '_' +const partition = (array, predicate) => + array.reduce( + (result, value) => { + result[predicate(value) ? 0 : 1].push(value) + return result + }, + [[], []], + ) +function sortPackageJson(jsonIsh, options = {}) { + return editStringJSON( + jsonIsh, + onObject((json) => { + let sortOrder = options.sortOrder ? options.sortOrder : defaultSortOrder -braces.expand = function(pattern, options) { - return braces.create(pattern, extend({}, options, {expand: true})); -}; + if (Array.isArray(sortOrder)) { + const keys = Object.keys(json) + const [privateKeys, publicKeys] = partition(keys, isPrivateKey) + sortOrder = [ + ...sortOrder, + ...defaultSortOrder, + ...publicKeys.sort(), + ...privateKeys.sort(), + ] + } -/** - * Expands a brace pattern into a regex-compatible, optimized string. This method is called by the main [braces](#braces) function by default. - * - * ```js - * var braces = require('braces'); - * console.log(braces.expand('a/{b,c}/d')); - * //=> ['a/(b|c)/d'] - * ``` - * @param {String} `pattern` Brace pattern - * @param {Object} `options` - * @return {Array} Returns an array of expanded values. - * @api public - */ + return overFields(sortObjectKeys(json, sortOrder), json) + }), + ) +} -braces.optimize = function(pattern, options) { - return braces.create(pattern, options); -}; +module.exports = sortPackageJson +module.exports.sortPackageJson = sortPackageJson +module.exports.sortOrder = defaultSortOrder +module.exports.default = sortPackageJson -/** - * Processes a brace pattern and returns either an expanded array (if `options.expand` is true), a highly optimized regex-compatible string. This method is called by the main [braces](#braces) function. - * - * ```js - * var braces = require('braces'); - * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}')) - * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)' - * ``` - * @param {String} `pattern` Brace pattern - * @param {Object} `options` - * @return {Array} Returns an array of expanded values. - * @api public - */ -braces.create = function(pattern, options) { - if (typeof pattern !== 'string') { - throw new TypeError('expected a string'); - } +/***/ }), +/* 616 */ +/***/ (function(module, exports) { - var maxLength = (options && options.maxLength) || MAX_LENGTH; - if (pattern.length >= maxLength) { - throw new Error('expected pattern to be less than ' + maxLength + ' characters'); +module.exports = function sortObjectByKeyNameList(object, sortWith) { + var keys; + var sortFn; + + if (typeof sortWith === 'function') { + sortFn = sortWith; + } else { + keys = sortWith; } - function create() { - if (pattern === '' || pattern.length < 3) { - return [pattern]; + var objectKeys = Object.keys(object); + return (keys || []).concat(objectKeys.sort(sortFn)).reduce(function(total, key) { + if (objectKeys.indexOf(key) !== -1) { + total[key] = object[key]; } + return total; + }, Object.create(null)); +} - if (utils.isEmptySets(pattern)) { - return []; - } - if (utils.isQuotedString(pattern)) { - return [pattern.slice(1, -1)]; - } +/***/ }), +/* 617 */ +/***/ (function(module, exports, __webpack_require__) { - var proto = new Braces(options); - var result = !options || options.expand !== true - ? proto.optimize(pattern, options) - : proto.expand(pattern, options); +"use strict"; - // get the generated pattern(s) - var arr = result.output; - // filter out empty strings if specified - if (options && options.noempty === true) { - arr = arr.filter(Boolean); - } +// Detect either spaces or tabs but not both to properly handle tabs for indentation and spaces for alignment +const INDENT_REGEX = /^(?:( )+|\t+)/; - // filter out duplicates if specified - if (options && options.nodupes === true) { - arr = unique(arr); - } +const INDENT_TYPE_SPACE = 'space'; +const INDENT_TYPE_TAB = 'tab'; - Object.defineProperty(arr, 'result', { - enumerable: false, - value: result - }); +// Make a Map that counts how many indents/unindents have occurred for a given size and how many lines follow a given indentation. +// The key is a concatenation of the indentation type (s = space and t = tab) and the size of the indents/unindents. +// +// indents = { +// t3: [1, 0], +// t4: [1, 5], +// s5: [1, 0], +// s12: [1, 0], +// } +function makeIndentsMap(string, ignoreSingleSpaces) { + const indents = new Map(); - return arr; - } + // Remember the size of previous line's indentation + let previousSize = 0; + let previousIndentType; - return memoize('create', pattern, options, create); -}; + // Indents key (ident type + size of the indents/unindents) + let key; -/** - * Create a regular expression from the given string `pattern`. - * - * ```js - * var braces = require('braces'); - * - * console.log(braces.makeRe('id-{200..300}')); - * //=> /^(?:id-(20[0-9]|2[1-9][0-9]|300))$/ - * ``` - * @param {String} `pattern` The pattern to convert to regex. - * @param {Object} `options` - * @return {RegExp} - * @api public - */ + for (const line of string.split(/\n/g)) { + if (!line) { + // Ignore empty lines + continue; + } -braces.makeRe = function(pattern, options) { - if (typeof pattern !== 'string') { - throw new TypeError('expected a string'); - } + let indent; + let indentType; + let weight; + let entry; + const matches = line.match(INDENT_REGEX); - var maxLength = (options && options.maxLength) || MAX_LENGTH; - if (pattern.length >= maxLength) { - throw new Error('expected pattern to be less than ' + maxLength + ' characters'); - } + if (matches === null) { + previousSize = 0; + previousIndentType = ''; + } else { + indent = matches[0].length; - function makeRe() { - var arr = braces(pattern, options); - var opts = extend({strictErrors: false}, options); - return toRegex(arr, opts); - } + if (matches[1]) { + indentType = INDENT_TYPE_SPACE; + } else { + indentType = INDENT_TYPE_TAB; + } - return memoize('makeRe', pattern, options, makeRe); -}; + // Ignore single space unless it's the only indent detected to prevent common false positives + if (ignoreSingleSpaces && indentType === INDENT_TYPE_SPACE && indent === 1) { + continue; + } -/** - * Parse the given `str` with the given `options`. - * - * ```js - * var braces = require('braces'); - * var ast = braces.parse('a/{b,c}/d'); - * console.log(ast); - * // { type: 'root', - * // errors: [], - * // input: 'a/{b,c}/d', - * // nodes: - * // [ { type: 'bos', val: '' }, - * // { type: 'text', val: 'a/' }, - * // { type: 'brace', - * // nodes: - * // [ { type: 'brace.open', val: '{' }, - * // { type: 'text', val: 'b,c' }, - * // { type: 'brace.close', val: '}' } ] }, - * // { type: 'text', val: '/d' }, - * // { type: 'eos', val: '' } ] } - * ``` - * @param {String} `pattern` Brace pattern to parse - * @param {Object} `options` - * @return {Object} Returns an AST - * @api public - */ + if (indentType !== previousIndentType) { + previousSize = 0; + } -braces.parse = function(pattern, options) { - var proto = new Braces(options); - return proto.parse(pattern, options); -}; + previousIndentType = indentType; -/** - * Compile the given `ast` or string with the given `options`. - * - * ```js - * var braces = require('braces'); - * var ast = braces.parse('a/{b,c}/d'); - * console.log(braces.compile(ast)); - * // { options: { source: 'string' }, - * // state: {}, - * // compilers: - * // { eos: [Function], - * // noop: [Function], - * // bos: [Function], - * // brace: [Function], - * // 'brace.open': [Function], - * // text: [Function], - * // 'brace.close': [Function] }, - * // output: [ 'a/(b|c)/d' ], - * // ast: - * // { ... }, - * // parsingErrors: [] } - * ``` - * @param {Object|String} `ast` AST from [.parse](#parse). If a string is passed it will be parsed first. - * @param {Object} `options` - * @return {Object} Returns an object that has an `output` property with the compiled string. - * @api public - */ + weight = 0; -braces.compile = function(ast, options) { - var proto = new Braces(options); - return proto.compile(ast, options); -}; + const indentDifference = indent - previousSize; + previousSize = indent; -/** - * Clear the regex cache. - * - * ```js - * braces.clearCache(); - * ``` - * @api public - */ + // Previous line have same indent? + if (indentDifference === 0) { + weight++; + // We use the key from previous loop + } else { + const absoluteIndentDifference = indentDifference > 0 ? indentDifference : -indentDifference; + key = encodeIndentsKey(indentType, absoluteIndentDifference); + } -braces.clearCache = function() { - cache = braces.cache = {}; -}; + // Update the stats + entry = indents.get(key); -/** - * Memoize a generated regex or function. A unique key is generated - * from the method name, pattern, and user-defined options. Set - * options.memoize to false to disable. - */ + if (entry === undefined) { + entry = [1, 0]; // Init + } else { + entry = [++entry[0], entry[1] + weight]; + } -function memoize(type, pattern, options, fn) { - var key = utils.createKey(type + ':' + pattern, options); - var disabled = options && options.cache === false; - if (disabled) { - braces.clearCache(); - return fn(pattern, options); - } + indents.set(key, entry); + } + } - if (cache.hasOwnProperty(key)) { - return cache[key]; - } + return indents; +} - var res = fn(pattern, options); - cache[key] = res; - return res; +// Encode the indent type and amount as a string (e.g. 's4') for use as a compound key in the indents Map. +function encodeIndentsKey(indentType, indentAmount) { + const typeCharacter = indentType === INDENT_TYPE_SPACE ? 's' : 't'; + return typeCharacter + String(indentAmount); } -/** - * Expose `Braces` constructor and methods - * @type {Function} - */ +// Extract the indent type and amount from a key of the indents Map. +function decodeIndentsKey(indentsKey) { + const keyHasTypeSpace = indentsKey[0] === 's'; + const type = keyHasTypeSpace ? INDENT_TYPE_SPACE : INDENT_TYPE_TAB; -braces.Braces = Braces; -braces.compilers = compilers; -braces.parsers = parsers; -braces.cache = cache; + const amount = Number(indentsKey.slice(1)); -/** - * Expose `braces` - * @type {Function} - */ + return {type, amount}; +} -module.exports = braces; +// Return the key (e.g. 's4') from the indents Map that represents the most common indent, +// or return undefined if there are no indents. +function getMostUsedKey(indents) { + let result; + let maxUsed = 0; + let maxWeight = 0; + for (const [key, [usedCount, weight]] of indents) { + if (usedCount > maxUsed || (usedCount === maxUsed && weight > maxWeight)) { + maxUsed = usedCount; + maxWeight = weight; + result = key; + } + } -/***/ }), -/* 610 */ -/***/ (function(module, exports, __webpack_require__) { + return result; +} -"use strict"; +function makeIndentString(type, amount) { + const indentCharacter = type === INDENT_TYPE_SPACE ? ' ' : '\t'; + return indentCharacter.repeat(amount); +} +module.exports = string => { + if (typeof string !== 'string') { + throw new TypeError('Expected a string'); + } -var safe = __webpack_require__(611); -var define = __webpack_require__(617); -var extend = __webpack_require__(623); -var not = __webpack_require__(627); -var MAX_LENGTH = 1024 * 64; + // Identify indents while skipping single space indents to avoid common edge cases (e.g. code comments) + // If no indents are identified, run again and include all indents for comprehensive detection + let indents = makeIndentsMap(string, true); + if (indents.size === 0) { + indents = makeIndentsMap(string, false); + } -/** - * Session cache - */ + const keyOfMostUsedIndent = getMostUsedKey(indents); -var cache = {}; + let type; + let amount = 0; + let indent = ''; -/** - * Create a regular expression from the given `pattern` string. - * - * @param {String|RegExp} `pattern` Pattern can be a string or regular expression. - * @param {Object} `options` - * @return {RegExp} - * @api public - */ + if (keyOfMostUsedIndent !== undefined) { + ({type, amount} = decodeIndentsKey(keyOfMostUsedIndent)); + indent = makeIndentString(type, amount); + } -module.exports = function(patterns, options) { - if (!Array.isArray(patterns)) { - return makeRe(patterns, options); - } - return makeRe(patterns.join('|'), options); + return { + amount, + type, + indent + }; }; -/** - * Create a regular expression from the given `pattern` string. - * - * @param {String|RegExp} `pattern` Pattern can be a string or regular expression. - * @param {Object} `options` - * @return {RegExp} - * @api public - */ -function makeRe(pattern, options) { - if (pattern instanceof RegExp) { - return pattern; - } +/***/ }), +/* 618 */ +/***/ (function(module, exports, __webpack_require__) { - if (typeof pattern !== 'string') { - throw new TypeError('expected a string'); - } +"use strict"; - if (pattern.length > MAX_LENGTH) { - throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters'); - } - var key = pattern; - // do this before shallow cloning options, it's a lot faster - if (!options || (options && options.cache !== false)) { - key = createKey(pattern, options); +const detectNewline = string => { + if (typeof string !== 'string') { + throw new TypeError('Expected a string'); + } - if (cache.hasOwnProperty(key)) { - return cache[key]; - } - } + const newlines = string.match(/(?:\r?\n)/g) || []; - var opts = extend({}, options); - if (opts.contains === true) { - if (opts.negate === true) { - opts.strictNegate = false; - } else { - opts.strict = false; - } - } + if (newlines.length === 0) { + return; + } - if (opts.strict === false) { - opts.strictOpen = false; - opts.strictClose = false; - } + const crlf = newlines.filter(newline => newline === '\r\n').length; + const lf = newlines.length - crlf; - var open = opts.strictOpen !== false ? '^' : ''; - var close = opts.strictClose !== false ? '$' : ''; - var flags = opts.flags || ''; - var regex; + return crlf > lf ? '\r\n' : '\n'; +}; - if (opts.nocase === true && !/i/.test(flags)) { - flags += 'i'; - } +module.exports = detectNewline; +module.exports.graceful = string => (typeof string === 'string' && detectNewline(string)) || '\n'; - try { - if (opts.negate || typeof opts.strictNegate === 'boolean') { - pattern = not.create(pattern, opts); - } - var str = open + '(?:' + pattern + ')' + close; - regex = new RegExp(str, flags); +/***/ }), +/* 619 */ +/***/ (function(module) { - if (opts.safe === true && safe(regex) === false) { - throw new Error('potentially unsafe regular expression: ' + regex.source); - } +module.exports = JSON.parse("[\"applypatch-msg\",\"pre-applypatch\",\"post-applypatch\",\"pre-commit\",\"pre-merge-commit\",\"prepare-commit-msg\",\"commit-msg\",\"post-commit\",\"pre-rebase\",\"post-checkout\",\"post-merge\",\"pre-push\",\"pre-receive\",\"update\",\"post-receive\",\"post-update\",\"push-to-checkout\",\"pre-auto-gc\",\"post-rewrite\",\"sendemail-validate\",\"fsmonitor-watchman\",\"p4-pre-submit\",\"post-index-change\"]"); - } catch (err) { - if (opts.strictErrors === true || opts.safe === true) { - err.key = key; - err.pattern = pattern; - err.originalOptions = options; - err.createdOptions = opts; - throw err; - } +/***/ }), +/* 620 */ +/***/ (function(module, exports, __webpack_require__) { - try { - regex = new RegExp('^' + pattern.replace(/(\W)/g, '\\$1') + '$'); - } catch (err) { - regex = /.^/; //<= match nothing - } - } +"use strict"; - if (opts.cache !== false) { - memoize(regex, key, pattern, opts); - } - return regex; -} -/** - * Memoize generated regex. This can result in dramatic speed improvements - * and simplify debugging by adding options and pattern to the regex. It can be - * disabled by passing setting `options.cache` to false. - */ +module.exports = value => { + if (Object.prototype.toString.call(value) !== '[object Object]') { + return false; + } -function memoize(regex, key, pattern, options) { - define(regex, 'cached', true); - define(regex, 'pattern', pattern); - define(regex, 'options', options); - define(regex, 'key', key); - cache[key] = regex; -} + const prototype = Object.getPrototypeOf(value); + return prototype === null || prototype === Object.prototype; +}; -/** - * Create the key to use for memoization. The key is generated - * by iterating over the options and concatenating key-value pairs - * to the pattern string. - */ -function createKey(pattern, options) { - if (!options) return pattern; - var key = pattern; - for (var prop in options) { - if (options.hasOwnProperty(prop)) { - key += ';' + prop + '=' + String(options[prop]); - } - } - return key; -} +/***/ }), +/* 621 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -/** - * Expose `makeRe` +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "regenerateSyntheticPackageMap", function() { return regenerateSyntheticPackageMap; }); +/* harmony import */ var fs_promises__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(613); +/* harmony import */ var fs_promises__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs_promises__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var normalize_path__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(611); +/* harmony import */ var normalize_path__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(normalize_path__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var _convert_plugin_id_to_package_id__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(622); +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. */ -module.exports.makeRe = makeRe; -/***/ }), -/* 611 */ -/***/ (function(module, exports, __webpack_require__) { -var parse = __webpack_require__(612); -var types = parse.types; +async function regenerateSyntheticPackageMap(plugins, repoRoot) { + const entries = [['@kbn/core', 'src/core']]; -module.exports = function (re, opts) { - if (!opts) opts = {}; - var replimit = opts.limit === undefined ? 25 : opts.limit; - - if (isRegExp(re)) re = re.source; - else if (typeof re !== 'string') re = String(re); - - try { re = parse(re) } - catch (err) { return false } - - var reps = 0; - return (function walk (node, starHeight) { - if (node.type === types.REPETITION) { - starHeight ++; - reps ++; - if (starHeight > 1) return false; - if (reps > replimit) return false; - } - - if (node.options) { - for (var i = 0, len = node.options.length; i < len; i++) { - var ok = walk({ stack: node.options[i] }, starHeight); - if (!ok) return false; - } - } - var stack = node.stack || (node.value && node.value.stack); - if (!stack) return true; - - for (var i = 0; i < stack.length; i++) { - var ok = walk(stack[i], starHeight); - if (!ok) return false; - } - - return true; - })(re, 0); -}; + for (const plugin of plugins) { + entries.push([Object(_convert_plugin_id_to_package_id__WEBPACK_IMPORTED_MODULE_3__["convertPluginIdToPackageId"])(plugin.manifest.id), normalize_path__WEBPACK_IMPORTED_MODULE_2___default()(path__WEBPACK_IMPORTED_MODULE_1___default.a.relative(repoRoot, plugin.directory))]); + } -function isRegExp (x) { - return {}.toString.call(x) === '[object RegExp]'; + await fs_promises__WEBPACK_IMPORTED_MODULE_0___default.a.writeFile(path__WEBPACK_IMPORTED_MODULE_1___default.a.resolve(repoRoot, 'packages/kbn-synthetic-package-map/synthetic-packages.json'), JSON.stringify(entries, null, 2)); } +/***/ }), +/* 622 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "convertPluginIdToPackageId", function() { return convertPluginIdToPackageId; }); +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ +function convertPluginIdToPackageId(pluginId) { + if (pluginId === 'core') { + // core is the only non-plugin + return `@kbn/core`; + } + + return `@kbn/${pluginId.split('').flatMap(c => c.toUpperCase() === c ? `-${c.toLowerCase()}` : c).join('')}-plugin`.replace(/-\w(-\w)+-/g, match => `-${match.split('-').join('')}-`).replace(/-plugin-plugin$/, '-plugin'); +} /***/ }), -/* 612 */ -/***/ (function(module, exports, __webpack_require__) { +/* 623 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -var util = __webpack_require__(613); -var types = __webpack_require__(614); -var sets = __webpack_require__(615); -var positions = __webpack_require__(616); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "regenerateBaseTsconfig", function() { return regenerateBaseTsconfig; }); +/* harmony import */ var fs_promises__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(613); +/* harmony import */ var fs_promises__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs_promises__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _convert_plugin_id_to_package_id__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(622); +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ -module.exports = function(regexpStr) { - var i = 0, l, c, - start = { type: types.ROOT, stack: []}, - // Keep track of last clause/group and stack. - lastGroup = start, - last = start.stack, - groupStack = []; +async function regenerateBaseTsconfig(plugins, repoRoot) { + const tsconfigPath = path__WEBPACK_IMPORTED_MODULE_1___default.a.resolve(repoRoot, 'tsconfig.base.json'); + const lines = (await fs_promises__WEBPACK_IMPORTED_MODULE_0___default.a.readFile(tsconfigPath, 'utf-8')).split('\n'); + const packageMap = plugins.slice().sort((a, b) => a.manifestPath.localeCompare(b.manifestPath)).flatMap(p => { + const id = Object(_convert_plugin_id_to_package_id__WEBPACK_IMPORTED_MODULE_2__["convertPluginIdToPackageId"])(p.manifest.id); + const path = path__WEBPACK_IMPORTED_MODULE_1___default.a.relative(repoRoot, p.directory); + return [` "${id}": ["${path}"],`, ` "${id}/*": ["${path}/*"],`]; + }); + const start = lines.findIndex(l => l.trim() === '// START AUTOMATED PACKAGE LISTING'); + const end = lines.findIndex(l => l.trim() === '// END AUTOMATED PACKAGE LISTING'); + await fs_promises__WEBPACK_IMPORTED_MODULE_0___default.a.writeFile(tsconfigPath, [...lines.slice(0, start + 1), ...packageMap, ...lines.slice(end)].join('\n')); +} +/***/ }), +/* 624 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - var repeatErr = function(i) { - util.error(regexpStr, 'Nothing to repeat at column ' + (i - 1)); - }; +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Kibana", function() { return Kibana; }); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(253); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var multimatch__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(625); +/* harmony import */ var multimatch__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(multimatch__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var is_path_inside__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(454); +/* harmony import */ var is_path_inside__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(is_path_inside__WEBPACK_IMPORTED_MODULE_3__); +/* harmony import */ var _yarn_lock__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(530); +/* harmony import */ var _projects__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(461); +/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(628); +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } - // Decode a few escaped characters. - var str = util.strToChars(regexpStr); - l = str.length; +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } - // Iterate through each character in string. - while (i < l) { - c = str[i++]; +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - switch (c) { - // Handle escaped characters, inclues a few sets. - case '\\': - c = str[i++]; +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ - switch (c) { - case 'b': - last.push(positions.wordBoundary()); - break; - case 'B': - last.push(positions.nonWordBoundary()); - break; - case 'w': - last.push(sets.words()); - break; - case 'W': - last.push(sets.notWords()); - break; - case 'd': - last.push(sets.ints()); - break; - case 'D': - last.push(sets.notInts()); - break; - case 's': - last.push(sets.whitespace()); - break; +/** + * Helper class for dealing with a set of projects as children of + * the Kibana project. The kbn/pm is currently implemented to be + * more generic, where everything is an operation of generic projects, + * but that leads to exceptions where we need the kibana project and + * do things like `project.get('kibana')!`. + * + * Using this helper we can restructre the generic list of projects + * as a Kibana object which encapulates all the projects in the + * workspace and knows about the root Kibana project. + */ - case 'S': - last.push(sets.notWhitespace()); - break; +class Kibana { + static async loadFrom(rootPath) { + return new Kibana(await Object(_projects__WEBPACK_IMPORTED_MODULE_5__["getProjects"])(rootPath, Object(_config__WEBPACK_IMPORTED_MODULE_6__["getProjectPaths"])({ + rootPath + }))); + } - default: - // Check if c is integer. - // In which case it's a reference. - if (/\d/.test(c)) { - last.push({ type: types.REFERENCE, value: parseInt(c, 10) }); + constructor(allWorkspaceProjects) { + this.allWorkspaceProjects = allWorkspaceProjects; - // Escaped character. - } else { - last.push({ type: types.CHAR, value: c.charCodeAt(0) }); - } - } + _defineProperty(this, "kibanaProject", void 0); - break; + const kibanaProject = allWorkspaceProjects.get('kibana'); + if (!kibanaProject) { + throw new TypeError('Unable to create Kibana object without all projects, including the Kibana project.'); + } - // Positionals. - case '^': - last.push(positions.begin()); - break; + this.kibanaProject = kibanaProject; + } + /** make an absolute path by resolving subPath relative to the kibana repo */ - case '$': - last.push(positions.end()); - break; + getAbsolute(...subPath) { + return path__WEBPACK_IMPORTED_MODULE_0___default.a.resolve(this.kibanaProject.path, ...subPath); + } + /** convert an absolute path to a relative path, relative to the kibana repo */ - // Handle custom sets. - case '[': - // Check if this class is 'anti' i.e. [^abc]. - var not; - if (str[i] === '^') { - not = true; - i++; - } else { - not = false; - } - // Get all the characters in class. - var classTokens = util.tokenizeClass(str.slice(i), regexpStr); + getRelative(absolute) { + return path__WEBPACK_IMPORTED_MODULE_0___default.a.relative(this.kibanaProject.path, absolute); + } + /** get a copy of the map of all projects in the kibana workspace */ - // Increase index by length of class. - i += classTokens[1]; - last.push({ - type: types.SET, - set: classTokens[0], - not: not, - }); - break; + getAllProjects() { + return new Map(this.allWorkspaceProjects); + } + /** determine if a project with the given name exists */ - // Class of any character except \n. - case '.': - last.push(sets.anyChar()); - break; + hasProject(name) { + return this.allWorkspaceProjects.has(name); + } + /** get a specific project, throws if the name is not known (use hasProject() first) */ - // Push group onto stack. - case '(': - // Create group. - var group = { - type: types.GROUP, - stack: [], - remember: true, - }; + getProject(name) { + const project = this.allWorkspaceProjects.get(name); - c = str[i]; + if (!project) { + throw new Error(`No package with name "${name}" in the workspace`); + } - // If if this is a special kind of group. - if (c === '?') { - c = str[i + 1]; - i += 2; + return project; + } + /** get a project and all of the projects it depends on in a ProjectMap */ - // Match if followed by. - if (c === '=') { - group.followedBy = true; - // Match if not followed by. - } else if (c === '!') { - group.notFollowedBy = true; + getProjectAndDeps(name) { + const project = this.getProject(name); + return Object(_projects__WEBPACK_IMPORTED_MODULE_5__["includeTransitiveProjects"])([project], this.allWorkspaceProjects); + } + /** filter the projects to just those matching certain paths/include/exclude tags */ - } else if (c !== ':') { - util.error(regexpStr, - 'Invalid group, character \'' + c + - '\' after \'?\' at column ' + (i - 1)); - } - group.remember = false; - } + getFilteredProjects(options) { + const allProjects = this.getAllProjects(); + const filteredProjects = new Map(); + const pkgJsonPaths = Array.from(allProjects.values()).map(p => p.packageJsonLocation); + const filteredPkgJsonGlobs = Object(_config__WEBPACK_IMPORTED_MODULE_6__["getProjectPaths"])(_objectSpread(_objectSpread({}, options), {}, { + rootPath: this.kibanaProject.path + })).map(g => path__WEBPACK_IMPORTED_MODULE_0___default.a.resolve(g, 'package.json')); + const matchingPkgJsonPaths = multimatch__WEBPACK_IMPORTED_MODULE_2___default()(pkgJsonPaths, filteredPkgJsonGlobs); - // Insert subgroup into current group stack. - last.push(group); + for (const project of allProjects.values()) { + const pathMatches = matchingPkgJsonPaths.includes(project.packageJsonLocation); + const notExcluded = !options.exclude.includes(project.name); + const isIncluded = !options.include.length || options.include.includes(project.name); - // Remember the current group for when the group closes. - groupStack.push(lastGroup); + if (pathMatches && notExcluded && isIncluded) { + filteredProjects.set(project.name, project); + } + } - // Make this new group the current group. - lastGroup = group; - last = group.stack; - break; + return filteredProjects; + } + isPartOfRepo(project) { + return project.path === this.kibanaProject.path || is_path_inside__WEBPACK_IMPORTED_MODULE_3___default()(project.path, this.kibanaProject.path); + } - // Pop group out of stack. - case ')': - if (groupStack.length === 0) { - util.error(regexpStr, 'Unmatched ) at column ' + (i - 1)); - } - lastGroup = groupStack.pop(); + isOutsideRepo(project) { + return !this.isPartOfRepo(project); + } - // Check if this group has a PIPE. - // To get back the correct last stack. - last = lastGroup.options ? - lastGroup.options[lastGroup.options.length - 1] : lastGroup.stack; - break; + resolveAllProductionDependencies(yarnLock, log) { + const kibanaDeps = Object(_yarn_lock__WEBPACK_IMPORTED_MODULE_4__["resolveDepsForProject"])({ + project: this.kibanaProject, + yarnLock, + kbn: this, + includeDependentProject: true, + productionDepsOnly: true, + log + }); + const xpackDeps = Object(_yarn_lock__WEBPACK_IMPORTED_MODULE_4__["resolveDepsForProject"])({ + project: this.getProject('x-pack'), + yarnLock, + kbn: this, + includeDependentProject: true, + productionDepsOnly: true, + log + }); + return new Map([...kibanaDeps.entries(), ...xpackDeps.entries()]); + } + getUuid() { + try { + return fs__WEBPACK_IMPORTED_MODULE_1___default.a.readFileSync(this.getAbsolute('data/uuid'), 'utf-8').trim(); + } catch (error) { + if (error.code === 'ENOENT') { + return undefined; + } - // Use pipe character to give more choices. - case '|': - // Create array where options are if this is the first PIPE - // in this clause. - if (!lastGroup.options) { - lastGroup.options = [lastGroup.stack]; - delete lastGroup.stack; - } + throw error; + } + } - // Create a new stack and add to options for rest of clause. - var stack = []; - lastGroup.options.push(stack); - last = stack; - break; +} +/***/ }), +/* 625 */ +/***/ (function(module, exports, __webpack_require__) { - // Repetition. - // For every repetition, remove last element from last stack - // then insert back a RANGE object. - // This design is chosen because there could be more than - // one repetition symbols in a regex i.e. `a?+{2,3}`. - case '{': - var rs = /^(\d+)(,(\d+)?)?\}/.exec(str.slice(i)), min, max; - if (rs !== null) { - if (last.length === 0) { - repeatErr(i); - } - min = parseInt(rs[1], 10); - max = rs[2] ? rs[3] ? parseInt(rs[3], 10) : Infinity : min; - i += rs[0].length; +"use strict"; - last.push({ - type: types.REPETITION, - min: min, - max: max, - value: last.pop(), - }); - } else { - last.push({ - type: types.CHAR, - value: 123, - }); - } - break; +const minimatch = __webpack_require__(368); +const arrayUnion = __webpack_require__(363); +const arrayDiffer = __webpack_require__(626); +const arrify = __webpack_require__(627); - case '?': - if (last.length === 0) { - repeatErr(i); - } - last.push({ - type: types.REPETITION, - min: 0, - max: 1, - value: last.pop(), - }); - break; +module.exports = (list, patterns, options = {}) => { + list = arrify(list); + patterns = arrify(patterns); - case '+': - if (last.length === 0) { - repeatErr(i); - } - last.push({ - type: types.REPETITION, - min: 1, - max: Infinity, - value: last.pop(), - }); - break; + if (list.length === 0 || patterns.length === 0) { + return []; + } - case '*': - if (last.length === 0) { - repeatErr(i); - } - last.push({ - type: types.REPETITION, - min: 0, - max: Infinity, - value: last.pop(), - }); - break; + return patterns.reduce((result, pattern) => { + let process = arrayUnion; + + if (pattern[0] === '!') { + pattern = pattern.slice(1); + process = arrayDiffer; + } + return process(result, minimatch.match(list, pattern, options)); + }, []); +}; - // Default is a character that is not `\[](){}?+*^$`. - default: - last.push({ - type: types.CHAR, - value: c.charCodeAt(0), - }); - } - } +/***/ }), +/* 626 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; - // Check if any groups have not been closed. - if (groupStack.length !== 0) { - util.error(regexpStr, 'Unterminated group'); - } - return start; +const arrayDiffer = (array, ...values) => { + const rest = new Set([].concat(...values)); + return array.filter(element => !rest.has(element)); }; -module.exports.types = types; +module.exports = arrayDiffer; /***/ }), -/* 613 */ +/* 627 */ /***/ (function(module, exports, __webpack_require__) { -var types = __webpack_require__(614); -var sets = __webpack_require__(615); +"use strict"; -// All of these are private and only used by randexp. -// It's assumed that they will always be called with the correct input. +const arrify = value => { + if (value === null || value === undefined) { + return []; + } + + if (Array.isArray(value)) { + return value; + } + + if (typeof value === 'string') { + return [value]; + } + + if (typeof value[Symbol.iterator] === 'function') { + return [...value]; + } + + return [value]; +}; + +module.exports = arrify; + + +/***/ }), +/* 628 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getProjectPaths", function() { return getProjectPaths; }); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_0__); +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ -var CTRL = '@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ ?'; -var SLSH = { '0': 0, 't': 9, 'n': 10, 'v': 11, 'f': 12, 'r': 13 }; /** - * Finds character representations in str and convert all to - * their respective characters - * - * @param {String} str - * @return {String} + * Returns all the paths where plugins are located */ -exports.strToChars = function(str) { - /* jshint maxlen: false */ - var chars_regex = /(\[\\b\])|(\\)?\\(?:u([A-F0-9]{4})|x([A-F0-9]{2})|(0?[0-7]{2})|c([@A-Z\[\\\]\^?])|([0tnvfr]))/g; - str = str.replace(chars_regex, function(s, b, lbs, a16, b16, c8, dctrl, eslsh) { - if (lbs) { - return s; - } +function getProjectPaths({ + rootPath, + ossOnly, + skipKibanaPlugins +}) { + const projectPaths = [rootPath, Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(rootPath, 'packages/*')]; // This is needed in order to install the dependencies for the declared + // plugin functional used in the selenium functional tests. + // As we are now using the webpack dll for the client vendors dependencies + // when we run the plugin functional tests against the distributable + // dependencies used by such plugins like @eui, react and react-dom can't + // be loaded from the dll as the context is different from the one declared + // into the webpack dll reference plugin. + // In anyway, have a plugin declaring their own dependencies is the + // correct and the expect behavior. - var code = b ? 8 : - a16 ? parseInt(a16, 16) : - b16 ? parseInt(b16, 16) : - c8 ? parseInt(c8, 8) : - dctrl ? CTRL.indexOf(dctrl) : - SLSH[eslsh]; + projectPaths.push(Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(rootPath, 'test/plugin_functional/plugins/*')); + projectPaths.push(Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(rootPath, 'test/interpreter_functional/plugins/*')); + projectPaths.push(Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(rootPath, 'test/server_integration/__fixtures__/plugins/*')); + projectPaths.push(Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(rootPath, 'examples/*')); - var c = String.fromCharCode(code); + if (!ossOnly) { + projectPaths.push(Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(rootPath, 'x-pack')); + projectPaths.push(Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(rootPath, 'x-pack/plugins/*')); + projectPaths.push(Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(rootPath, 'x-pack/legacy/plugins/*')); + projectPaths.push(Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(rootPath, 'x-pack/test/functional_with_es_ssl/fixtures/plugins/*')); + } - // Escape special regex characters. - if (/[\[\]{}\^$.|?*+()]/.test(c)) { - c = '\\' + c; - } + if (!skipKibanaPlugins) { + projectPaths.push(Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(rootPath, '../kibana-extra/*')); + projectPaths.push(Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(rootPath, '../kibana-extra/*/packages/*')); + projectPaths.push(Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(rootPath, '../kibana-extra/*/plugins/*')); + projectPaths.push(Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(rootPath, 'plugins/*')); + projectPaths.push(Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(rootPath, 'plugins/*/packages/*')); + projectPaths.push(Object(path__WEBPACK_IMPORTED_MODULE_0__["resolve"])(rootPath, 'plugins/*/plugins/*')); + } - return c; - }); + return projectPaths; +} - return str; -}; +/***/ }), +/* 629 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _build_bazel_production_projects__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(630); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "buildBazelProductionProjects", function() { return _build_bazel_production_projects__WEBPACK_IMPORTED_MODULE_0__["buildBazelProductionProjects"]; }); +/* harmony import */ var _build_non_bazel_production_projects__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(843); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "buildNonBazelProductionProjects", function() { return _build_non_bazel_production_projects__WEBPACK_IMPORTED_MODULE_1__["buildNonBazelProductionProjects"]; }); -/** - * turns class into tokens - * reads str until it encounters a ] not preceeded by a \ - * - * @param {String} str - * @param {String} regexpStr - * @return {Array., Number>} +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. */ -exports.tokenizeClass = function(str, regexpStr) { - /* jshint maxlen: false */ - var tokens = []; - var regexp = /\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(?:\\)?([^\]]))|(\])|(?:\\)?(.)/g; - var rs, c; - while ((rs = regexp.exec(str)) != null) { - if (rs[1]) { - tokens.push(sets.words()); - } else if (rs[2]) { - tokens.push(sets.ints()); +/***/ }), +/* 630 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "buildBazelProductionProjects", function() { return buildBazelProductionProjects; }); +/* harmony import */ var cpy__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(631); +/* harmony import */ var cpy__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(cpy__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var globby__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(583); +/* harmony import */ var globby__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(globby__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var _build_non_bazel_production_projects__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(843); +/* harmony import */ var _utils_bazel__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(535); +/* harmony import */ var _utils_fs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(352); +/* harmony import */ var _utils_log__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(341); +/* harmony import */ var _utils_package_json__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(464); +/* harmony import */ var _utils_projects__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(461); +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ - } else if (rs[3]) { - tokens.push(sets.whitespace()); - } else if (rs[4]) { - tokens.push(sets.notWords()); - } else if (rs[5]) { - tokens.push(sets.notInts()); - } else if (rs[6]) { - tokens.push(sets.notWhitespace()); - } else if (rs[7]) { - tokens.push({ - type: types.RANGE, - from: (rs[8] || rs[9]).charCodeAt(0), - to: rs[10].charCodeAt(0), - }); - } else if (c = rs[12]) { - tokens.push({ - type: types.CHAR, - value: c.charCodeAt(0), - }); - } else { - return [tokens, regexp.lastIndex]; - } - } - exports.error(regexpStr, 'Unterminated character class'); -}; +async function buildBazelProductionProjects({ + kibanaRoot, + buildRoot, + onlyOSS +}) { + const projects = await Object(_utils_projects__WEBPACK_IMPORTED_MODULE_8__["getBazelProjectsOnly"])(await Object(_build_non_bazel_production_projects__WEBPACK_IMPORTED_MODULE_3__["getProductionProjects"])(kibanaRoot, onlyOSS)); + const projectNames = [...projects.values()].map(project => project.name); + _utils_log__WEBPACK_IMPORTED_MODULE_6__["log"].info(`Preparing Bazel projects production build for [${projectNames.join(', ')}]`); + await Object(_utils_bazel__WEBPACK_IMPORTED_MODULE_4__["runBazel"])(['build', '//packages:build']); + _utils_log__WEBPACK_IMPORTED_MODULE_6__["log"].info(`All Bazel projects production builds for [${projectNames.join(', ')}] are complete`); + for (const project of projects.values()) { + await copyToBuild(project, kibanaRoot, buildRoot); + await applyCorrectPermissions(project, kibanaRoot, buildRoot); + } +} /** - * Shortcut to throw errors. + * Copy all the project's files from its Bazel dist directory into the + * project build folder. * - * @param {String} regexp - * @param {String} msg + * When copying all the files into the build, we exclude `node_modules` because + * we want the Kibana build to be responsible for actually installing all + * dependencies. The primary reason for allowing the Kibana build process to + * manage dependencies is that it will "dedupe" them, so we don't include + * unnecessary copies of dependencies. We also exclude every related Bazel build + * files in order to get the most cleaner package module we can in the final distributable. */ -exports.error = function(regexp, msg) { - throw new SyntaxError('Invalid regular expression: /' + regexp + '/: ' + msg); -}; - - -/***/ }), -/* 614 */ -/***/ (function(module, exports) { -module.exports = { - ROOT : 0, - GROUP : 1, - POSITION : 2, - SET : 3, - RANGE : 4, - REPETITION : 5, - REFERENCE : 6, - CHAR : 7, -}; +async function copyToBuild(project, kibanaRoot, buildRoot) { + // We want the package to have the same relative location within the build + const relativeProjectPath = Object(path__WEBPACK_IMPORTED_MODULE_2__["relative"])(kibanaRoot, project.path); + const buildProjectPath = Object(path__WEBPACK_IMPORTED_MODULE_2__["resolve"])(buildRoot, relativeProjectPath); + await cpy__WEBPACK_IMPORTED_MODULE_0___default()(['**/*'], buildProjectPath, { + cwd: Object(path__WEBPACK_IMPORTED_MODULE_2__["join"])(kibanaRoot, 'bazel-bin', 'packages', Object(path__WEBPACK_IMPORTED_MODULE_2__["basename"])(buildProjectPath), 'npm_module'), + dot: true, + onlyFiles: true, + parents: true + }); // If a project is using an intermediate build directory, we special-case our + // handling of `package.json`, as the project build process might have copied + // (a potentially modified) `package.json` into the intermediate build + // directory already. If so, we want to use that `package.json` as the basis + // for creating the production-ready `package.json`. If it's not present in + // the intermediate build, we fall back to using the project's already defined + // `package.json`. + const packageJson = (await Object(_utils_fs__WEBPACK_IMPORTED_MODULE_5__["isFile"])(Object(path__WEBPACK_IMPORTED_MODULE_2__["join"])(buildProjectPath, 'package.json'))) ? await Object(_utils_package_json__WEBPACK_IMPORTED_MODULE_7__["readPackageJson"])(buildProjectPath) : project.json; + const preparedPackageJson = Object(_utils_package_json__WEBPACK_IMPORTED_MODULE_7__["createProductionPackageJson"])(packageJson); + await Object(_utils_package_json__WEBPACK_IMPORTED_MODULE_7__["writePackageJson"])(buildProjectPath, preparedPackageJson); +} -/***/ }), -/* 615 */ -/***/ (function(module, exports, __webpack_require__) { +async function applyCorrectPermissions(project, kibanaRoot, buildRoot) { + const relativeProjectPath = Object(path__WEBPACK_IMPORTED_MODULE_2__["relative"])(kibanaRoot, project.path); + const buildProjectPath = Object(path__WEBPACK_IMPORTED_MODULE_2__["resolve"])(buildRoot, relativeProjectPath); + const allPluginPaths = await globby__WEBPACK_IMPORTED_MODULE_1___default()([`**/*`], { + onlyFiles: false, + cwd: buildProjectPath, + dot: true + }); -var types = __webpack_require__(614); + for (const pluginPath of allPluginPaths) { + const resolvedPluginPath = Object(path__WEBPACK_IMPORTED_MODULE_2__["resolve"])(buildProjectPath, pluginPath); -var INTS = function() { - return [{ type: types.RANGE , from: 48, to: 57 }]; -}; + if (await Object(_utils_fs__WEBPACK_IMPORTED_MODULE_5__["isFile"])(resolvedPluginPath)) { + await Object(_utils_fs__WEBPACK_IMPORTED_MODULE_5__["chmod"])(resolvedPluginPath, 0o644); + } -var WORDS = function() { - return [ - { type: types.CHAR, value: 95 }, - { type: types.RANGE, from: 97, to: 122 }, - { type: types.RANGE, from: 65, to: 90 } - ].concat(INTS()); -}; + if (await Object(_utils_fs__WEBPACK_IMPORTED_MODULE_5__["isDirectory"])(resolvedPluginPath)) { + await Object(_utils_fs__WEBPACK_IMPORTED_MODULE_5__["chmod"])(resolvedPluginPath, 0o755); + } + } +} -var WHITESPACE = function() { - return [ - { type: types.CHAR, value: 9 }, - { type: types.CHAR, value: 10 }, - { type: types.CHAR, value: 11 }, - { type: types.CHAR, value: 12 }, - { type: types.CHAR, value: 13 }, - { type: types.CHAR, value: 32 }, - { type: types.CHAR, value: 160 }, - { type: types.CHAR, value: 5760 }, - { type: types.CHAR, value: 6158 }, - { type: types.CHAR, value: 8192 }, - { type: types.CHAR, value: 8193 }, - { type: types.CHAR, value: 8194 }, - { type: types.CHAR, value: 8195 }, - { type: types.CHAR, value: 8196 }, - { type: types.CHAR, value: 8197 }, - { type: types.CHAR, value: 8198 }, - { type: types.CHAR, value: 8199 }, - { type: types.CHAR, value: 8200 }, - { type: types.CHAR, value: 8201 }, - { type: types.CHAR, value: 8202 }, - { type: types.CHAR, value: 8232 }, - { type: types.CHAR, value: 8233 }, - { type: types.CHAR, value: 8239 }, - { type: types.CHAR, value: 8287 }, - { type: types.CHAR, value: 12288 }, - { type: types.CHAR, value: 65279 } - ]; -}; +/***/ }), +/* 631 */ +/***/ (function(module, exports, __webpack_require__) { -var NOTANYCHAR = function() { - return [ - { type: types.CHAR, value: 10 }, - { type: types.CHAR, value: 13 }, - { type: types.CHAR, value: 8232 }, - { type: types.CHAR, value: 8233 }, - ]; -}; +"use strict"; -// Predefined class objects. -exports.words = function() { - return { type: types.SET, set: WORDS(), not: false }; -}; +const EventEmitter = __webpack_require__(285); +const path = __webpack_require__(4); +const os = __webpack_require__(243); +const pMap = __webpack_require__(632); +const arrify = __webpack_require__(627); +const globby = __webpack_require__(635); +const hasGlob = __webpack_require__(827); +const cpFile = __webpack_require__(829); +const junk = __webpack_require__(839); +const pFilter = __webpack_require__(840); +const CpyError = __webpack_require__(842); -exports.notWords = function() { - return { type: types.SET, set: WORDS(), not: true }; +const defaultOptions = { + ignoreJunk: true }; -exports.ints = function() { - return { type: types.SET, set: INTS(), not: false }; -}; +class SourceFile { + constructor(relativePath, path) { + this.path = path; + this.relativePath = relativePath; + Object.freeze(this); + } -exports.notInts = function() { - return { type: types.SET, set: INTS(), not: true }; -}; + get name() { + return path.basename(this.relativePath); + } -exports.whitespace = function() { - return { type: types.SET, set: WHITESPACE(), not: false }; -}; + get nameWithoutExtension() { + return path.basename(this.relativePath, path.extname(this.relativePath)); + } -exports.notWhitespace = function() { - return { type: types.SET, set: WHITESPACE(), not: true }; -}; + get extension() { + return path.extname(this.relativePath).slice(1); + } +} -exports.anyChar = function() { - return { type: types.SET, set: NOTANYCHAR(), not: true }; -}; +const preprocessSourcePath = (source, options) => path.resolve(options.cwd ? options.cwd : process.cwd(), source); +const preprocessDestinationPath = (source, destination, options) => { + let basename = path.basename(source); -/***/ }), -/* 616 */ -/***/ (function(module, exports, __webpack_require__) { + if (typeof options.rename === 'string') { + basename = options.rename; + } else if (typeof options.rename === 'function') { + basename = options.rename(basename); + } -var types = __webpack_require__(614); + if (options.cwd) { + destination = path.resolve(options.cwd, destination); + } -exports.wordBoundary = function() { - return { type: types.POSITION, value: 'b' }; -}; + if (options.parents) { + const dirname = path.dirname(source); + const parsedDirectory = path.parse(dirname); + return path.join(destination, dirname.replace(parsedDirectory.root, path.sep), basename); + } -exports.nonWordBoundary = function() { - return { type: types.POSITION, value: 'B' }; + return path.join(destination, basename); }; -exports.begin = function() { - return { type: types.POSITION, value: '^' }; -}; +module.exports = (source, destination, { + concurrency = (os.cpus().length || 1) * 2, + ...options +} = {}) => { + const progressEmitter = new EventEmitter(); -exports.end = function() { - return { type: types.POSITION, value: '$' }; -}; + options = { + ...defaultOptions, + ...options + }; + const promise = (async () => { + source = arrify(source); -/***/ }), -/* 617 */ -/***/ (function(module, exports, __webpack_require__) { + if (source.length === 0 || !destination) { + throw new CpyError('`source` and `destination` required'); + } -"use strict"; -/*! - * define-property - * - * Copyright (c) 2015-2018, Jon Schlinkert. - * Released under the MIT License. - */ + const copyStatus = new Map(); + let completedFiles = 0; + let completedSize = 0; + let files; + try { + files = await globby(source, options); + if (options.ignoreJunk) { + files = files.filter(file => junk.not(path.basename(file))); + } + } catch (error) { + throw new CpyError(`Cannot glob \`${source}\`: ${error.message}`, error); + } -var isobject = __webpack_require__(618); -var isDescriptor = __webpack_require__(619); -var define = (typeof Reflect !== 'undefined' && Reflect.defineProperty) - ? Reflect.defineProperty - : Object.defineProperty; + if (files.length === 0 && !hasGlob(source)) { + throw new CpyError(`Cannot copy \`${source}\`: the file doesn't exist`); + } -module.exports = function defineProperty(obj, key, val) { - if (!isobject(obj) && typeof obj !== 'function' && !Array.isArray(obj)) { - throw new TypeError('expected an object, function, or array'); - } + let sources = files.map(sourcePath => new SourceFile(sourcePath, preprocessSourcePath(sourcePath, options))); - if (typeof key !== 'string') { - throw new TypeError('expected "key" to be a string'); - } + if (options.filter !== undefined) { + const filteredSources = await pFilter(sources, options.filter, {concurrency: 1024}); + sources = filteredSources; + } - if (isDescriptor(val)) { - define(obj, key, val); - return obj; - } + if (sources.length === 0) { + progressEmitter.emit('progress', { + totalFiles: 0, + percent: 1, + completedFiles: 0, + completedSize: 0 + }); + } - define(obj, key, { - configurable: true, - enumerable: false, - writable: true, - value: val - }); + const fileProgressHandler = event => { + const fileStatus = copyStatus.get(event.src) || {written: 0, percent: 0}; - return obj; -}; + if (fileStatus.written !== event.written || fileStatus.percent !== event.percent) { + completedSize -= fileStatus.written; + completedSize += event.written; + if (event.percent === 1 && fileStatus.percent !== 1) { + completedFiles++; + } -/***/ }), -/* 618 */ -/***/ (function(module, exports, __webpack_require__) { + copyStatus.set(event.src, { + written: event.written, + percent: event.percent + }); -"use strict"; -/*! - * isobject - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. - */ + progressEmitter.emit('progress', { + totalFiles: files.length, + percent: completedFiles / files.length, + completedFiles, + completedSize + }); + } + }; + + return pMap(sources, async source => { + const to = preprocessDestinationPath(source.relativePath, destination, options); + try { + await cpFile(source.path, to, options).on('progress', fileProgressHandler); + } catch (error) { + throw new CpyError(`Cannot copy from \`${source.relativePath}\` to \`${to}\`: ${error.message}`, error); + } + return to; + }, {concurrency}); + })(); -module.exports = function isObject(val) { - return val != null && typeof val === 'object' && Array.isArray(val) === false; + promise.on = (...arguments_) => { + progressEmitter.on(...arguments_); + return promise; + }; + + return promise; }; /***/ }), -/* 619 */ +/* 632 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/*! - * is-descriptor - * - * Copyright (c) 2015-2017, Jon Schlinkert. - * Released under the MIT License. - */ +const AggregateError = __webpack_require__(633); +module.exports = async ( + iterable, + mapper, + { + concurrency = Infinity, + stopOnError = true + } = {} +) => { + return new Promise((resolve, reject) => { + if (typeof mapper !== 'function') { + throw new TypeError('Mapper function is required'); + } -var typeOf = __webpack_require__(620); -var isAccessor = __webpack_require__(621); -var isData = __webpack_require__(622); + if (!(typeof concurrency === 'number' && concurrency >= 1)) { + throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${concurrency}\` (${typeof concurrency})`); + } -module.exports = function isDescriptor(obj, key) { - if (typeOf(obj) !== 'object') { - return false; - } - if ('get' in obj) { - return isAccessor(obj, key); - } - return isData(obj, key); -}; + const ret = []; + const errors = []; + const iterator = iterable[Symbol.iterator](); + let isRejected = false; + let isIterableDone = false; + let resolvingCount = 0; + let currentIndex = 0; + const next = () => { + if (isRejected) { + return; + } -/***/ }), -/* 620 */ -/***/ (function(module, exports) { + const nextItem = iterator.next(); + const i = currentIndex; + currentIndex++; -var toString = Object.prototype.toString; + if (nextItem.done) { + isIterableDone = true; -module.exports = function kindOf(val) { - if (val === void 0) return 'undefined'; - if (val === null) return 'null'; + if (resolvingCount === 0) { + if (!stopOnError && errors.length !== 0) { + reject(new AggregateError(errors)); + } else { + resolve(ret); + } + } - var type = typeof val; - if (type === 'boolean') return 'boolean'; - if (type === 'string') return 'string'; - if (type === 'number') return 'number'; - if (type === 'symbol') return 'symbol'; - if (type === 'function') { - return isGeneratorFn(val) ? 'generatorfunction' : 'function'; - } + return; + } - if (isArray(val)) return 'array'; - if (isBuffer(val)) return 'buffer'; - if (isArguments(val)) return 'arguments'; - if (isDate(val)) return 'date'; - if (isError(val)) return 'error'; - if (isRegexp(val)) return 'regexp'; + resolvingCount++; - switch (ctorName(val)) { - case 'Symbol': return 'symbol'; - case 'Promise': return 'promise'; + (async () => { + try { + const element = await nextItem.value; + ret[i] = await mapper(element, i); + resolvingCount--; + next(); + } catch (error) { + if (stopOnError) { + isRejected = true; + reject(error); + } else { + errors.push(error); + resolvingCount--; + next(); + } + } + })(); + }; - // Set, Map, WeakSet, WeakMap - case 'WeakMap': return 'weakmap'; - case 'WeakSet': return 'weakset'; - case 'Map': return 'map'; - case 'Set': return 'set'; + for (let i = 0; i < concurrency; i++) { + next(); - // 8-bit typed arrays - case 'Int8Array': return 'int8array'; - case 'Uint8Array': return 'uint8array'; - case 'Uint8ClampedArray': return 'uint8clampedarray'; + if (isIterableDone) { + break; + } + } + }); +}; - // 16-bit typed arrays - case 'Int16Array': return 'int16array'; - case 'Uint16Array': return 'uint16array'; - // 32-bit typed arrays - case 'Int32Array': return 'int32array'; - case 'Uint32Array': return 'uint32array'; - case 'Float32Array': return 'float32array'; - case 'Float64Array': return 'float64array'; - } +/***/ }), +/* 633 */ +/***/ (function(module, exports, __webpack_require__) { - if (isGeneratorObj(val)) { - return 'generator'; - } +"use strict"; - // Non-plain objects - type = toString.call(val); - switch (type) { - case '[object Object]': return 'object'; - // iterators - case '[object Map Iterator]': return 'mapiterator'; - case '[object Set Iterator]': return 'setiterator'; - case '[object String Iterator]': return 'stringiterator'; - case '[object Array Iterator]': return 'arrayiterator'; - } +const indentString = __webpack_require__(634); +const cleanStack = __webpack_require__(459); - // other - return type.slice(8, -1).toLowerCase().replace(/\s/g, ''); -}; +const cleanInternalStack = stack => stack.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g, ''); -function ctorName(val) { - return typeof val.constructor === 'function' ? val.constructor.name : null; -} +class AggregateError extends Error { + constructor(errors) { + if (!Array.isArray(errors)) { + throw new TypeError(`Expected input to be an Array, got ${typeof errors}`); + } -function isArray(val) { - if (Array.isArray) return Array.isArray(val); - return val instanceof Array; -} + errors = [...errors].map(error => { + if (error instanceof Error) { + return error; + } -function isError(val) { - return val instanceof Error || (typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number'); -} + if (error !== null && typeof error === 'object') { + // Handle plain error objects with message property and/or possibly other metadata + return Object.assign(new Error(error.message), error); + } -function isDate(val) { - if (val instanceof Date) return true; - return typeof val.toDateString === 'function' - && typeof val.getDate === 'function' - && typeof val.setDate === 'function'; -} + return new Error(error); + }); -function isRegexp(val) { - if (val instanceof RegExp) return true; - return typeof val.flags === 'string' - && typeof val.ignoreCase === 'boolean' - && typeof val.multiline === 'boolean' - && typeof val.global === 'boolean'; -} + let message = errors + .map(error => { + // The `stack` property is not standardized, so we can't assume it exists + return typeof error.stack === 'string' ? cleanInternalStack(cleanStack(error.stack)) : String(error); + }) + .join('\n'); + message = '\n' + indentString(message, 4); + super(message); -function isGeneratorFn(name, val) { - return ctorName(name) === 'GeneratorFunction'; -} + this.name = 'AggregateError'; -function isGeneratorObj(val) { - return typeof val.throw === 'function' - && typeof val.return === 'function' - && typeof val.next === 'function'; -} + Object.defineProperty(this, '_errors', {value: errors}); + } -function isArguments(val) { - try { - if (typeof val.length === 'number' && typeof val.callee === 'function') { - return true; - } - } catch (err) { - if (err.message.indexOf('callee') !== -1) { - return true; - } - } - return false; + * [Symbol.iterator]() { + for (const error of this._errors) { + yield error; + } + } } -/** - * If you need to support Safari 5-7 (8-10 yr-old browser), - * take a look at https://github.com/feross/is-buffer - */ - -function isBuffer(val) { - if (val.constructor && typeof val.constructor.isBuffer === 'function') { - return val.constructor.isBuffer(val); - } - return false; -} +module.exports = AggregateError; /***/ }), -/* 621 */ +/* 634 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/*! - * is-accessor-descriptor - * - * Copyright (c) 2015-2017, Jon Schlinkert. - * Released under the MIT License. - */ +module.exports = (string, count = 1, options) => { + options = { + indent: ' ', + includeEmptyLines: false, + ...options + }; -var typeOf = __webpack_require__(620); + if (typeof string !== 'string') { + throw new TypeError( + `Expected \`input\` to be a \`string\`, got \`${typeof string}\`` + ); + } -// accessor descriptor properties -var accessor = { - get: 'function', - set: 'function', - configurable: 'boolean', - enumerable: 'boolean' -}; + if (typeof count !== 'number') { + throw new TypeError( + `Expected \`count\` to be a \`number\`, got \`${typeof count}\`` + ); + } -function isAccessorDescriptor(obj, prop) { - if (typeof prop === 'string') { - var val = Object.getOwnPropertyDescriptor(obj, prop); - return typeof val !== 'undefined'; - } + if (typeof options.indent !== 'string') { + throw new TypeError( + `Expected \`options.indent\` to be a \`string\`, got \`${typeof options.indent}\`` + ); + } - if (typeOf(obj) !== 'object') { - return false; - } + if (count === 0) { + return string; + } - if (has(obj, 'value') || has(obj, 'writable')) { - return false; - } + const regex = options.includeEmptyLines ? /^/gm : /^(?!\s*$)/gm; - if (!has(obj, 'get') || typeof obj.get !== 'function') { - return false; - } + return string.replace(regex, options.indent.repeat(count)); +}; - // tldr: it's valid to have "set" be undefined - // "set" might be undefined if `Object.getOwnPropertyDescriptor` - // was used to get the value, and only `get` was defined by the user - if (has(obj, 'set') && typeof obj[key] !== 'function' && typeof obj[key] !== 'undefined') { - return false; - } - for (var key in obj) { - if (!accessor.hasOwnProperty(key)) { - continue; - } +/***/ }), +/* 635 */ +/***/ (function(module, exports, __webpack_require__) { - if (typeOf(obj[key]) === accessor[key]) { - continue; - } +"use strict"; - if (typeof obj[key] !== 'undefined') { - return false; - } - } - return true; -} +const fs = __webpack_require__(253); +const arrayUnion = __webpack_require__(636); +const glob = __webpack_require__(365); +const fastGlob = __webpack_require__(638); +const dirGlob = __webpack_require__(821); +const gitignore = __webpack_require__(824); -function has(obj, key) { - return {}.hasOwnProperty.call(obj, key); -} +const DEFAULT_FILTER = () => false; -/** - * Expose `isAccessorDescriptor` - */ +const isNegative = pattern => pattern[0] === '!'; -module.exports = isAccessorDescriptor; +const assertPatternsInput = patterns => { + if (!patterns.every(x => typeof x === 'string')) { + throw new TypeError('Patterns must be a string or an array of strings'); + } +}; +const checkCwdOption = options => { + if (options && options.cwd && !fs.statSync(options.cwd).isDirectory()) { + throw new Error('The `cwd` option must be a path to a directory'); + } +}; -/***/ }), -/* 622 */ -/***/ (function(module, exports, __webpack_require__) { +const generateGlobTasks = (patterns, taskOptions) => { + patterns = arrayUnion([].concat(patterns)); + assertPatternsInput(patterns); + checkCwdOption(taskOptions); -"use strict"; -/*! - * is-data-descriptor - * - * Copyright (c) 2015-2017, Jon Schlinkert. - * Released under the MIT License. - */ + const globTasks = []; + taskOptions = Object.assign({ + ignore: [], + expandDirectories: true + }, taskOptions); + patterns.forEach((pattern, i) => { + if (isNegative(pattern)) { + return; + } -var typeOf = __webpack_require__(620); + const ignore = patterns + .slice(i) + .filter(isNegative) + .map(pattern => pattern.slice(1)); -module.exports = function isDataDescriptor(obj, prop) { - // data descriptor properties - var data = { - configurable: 'boolean', - enumerable: 'boolean', - writable: 'boolean' - }; + const options = Object.assign({}, taskOptions, { + ignore: taskOptions.ignore.concat(ignore) + }); - if (typeOf(obj) !== 'object') { - return false; - } + globTasks.push({pattern, options}); + }); - if (typeof prop === 'string') { - var val = Object.getOwnPropertyDescriptor(obj, prop); - return typeof val !== 'undefined'; - } + return globTasks; +}; - if (!('value' in obj) && !('writable' in obj)) { - return false; - } +const globDirs = (task, fn) => { + let options = {}; + if (task.options.cwd) { + options.cwd = task.options.cwd; + } - for (var key in obj) { - if (key === 'value') continue; + if (Array.isArray(task.options.expandDirectories)) { + options = Object.assign(options, {files: task.options.expandDirectories}); + } else if (typeof task.options.expandDirectories === 'object') { + options = Object.assign(options, task.options.expandDirectories); + } - if (!data.hasOwnProperty(key)) { - continue; - } + return fn(task.pattern, options); +}; - if (typeOf(obj[key]) === data[key]) { - continue; - } +const getPattern = (task, fn) => task.options.expandDirectories ? globDirs(task, fn) : [task.pattern]; - if (typeof obj[key] !== 'undefined') { - return false; - } - } - return true; -}; +const globToTask = task => glob => { + const {options} = task; + if (options.ignore && Array.isArray(options.ignore) && options.expandDirectories) { + options.ignore = dirGlob.sync(options.ignore); + } + return { + pattern: glob, + options + }; +}; -/***/ }), -/* 623 */ -/***/ (function(module, exports, __webpack_require__) { +const globby = (patterns, options) => { + let globTasks; -"use strict"; + try { + globTasks = generateGlobTasks(patterns, options); + } catch (error) { + return Promise.reject(error); + } + const getTasks = Promise.all(globTasks.map(task => Promise.resolve(getPattern(task, dirGlob)) + .then(globs => Promise.all(globs.map(globToTask(task)))) + )) + .then(tasks => arrayUnion(...tasks)); -var isExtendable = __webpack_require__(624); -var assignSymbols = __webpack_require__(626); + const getFilter = () => { + return Promise.resolve( + options && options.gitignore ? + gitignore({cwd: options.cwd, ignore: options.ignore}) : + DEFAULT_FILTER + ); + }; -module.exports = Object.assign || function(obj/*, objects*/) { - if (obj === null || typeof obj === 'undefined') { - throw new TypeError('Cannot convert undefined or null to object'); - } - if (!isObject(obj)) { - obj = {}; - } - for (var i = 1; i < arguments.length; i++) { - var val = arguments[i]; - if (isString(val)) { - val = toObject(val); - } - if (isObject(val)) { - assign(obj, val); - assignSymbols(obj, val); - } - } - return obj; + return getFilter() + .then(filter => { + return getTasks + .then(tasks => Promise.all(tasks.map(task => fastGlob(task.pattern, task.options)))) + .then(paths => arrayUnion(...paths)) + .then(paths => paths.filter(p => !filter(p))); + }); }; -function assign(a, b) { - for (var key in b) { - if (hasOwn(b, key)) { - a[key] = b[key]; - } - } -} +module.exports = globby; +// TODO: Remove this for the next major release +module.exports.default = globby; -function isString(val) { - return (val && typeof val === 'string'); -} +module.exports.sync = (patterns, options) => { + const globTasks = generateGlobTasks(patterns, options); -function toObject(str) { - var obj = {}; - for (var i in str) { - obj[i] = str[i]; - } - return obj; -} + const getFilter = () => { + return options && options.gitignore ? + gitignore.sync({cwd: options.cwd, ignore: options.ignore}) : + DEFAULT_FILTER; + }; -function isObject(val) { - return (val && typeof val === 'object') || isExtendable(val); -} + const tasks = globTasks.reduce((tasks, task) => { + const newTask = getPattern(task, dirGlob.sync).map(globToTask(task)); + return tasks.concat(newTask); + }, []); -/** - * Returns true if the given `key` is an own property of `obj`. - */ + const filter = getFilter(); + return tasks.reduce( + (matches, task) => arrayUnion(matches, fastGlob.sync(task.pattern, task.options)), + [] + ).filter(p => !filter(p)); +}; -function hasOwn(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -} +module.exports.generateGlobTasks = generateGlobTasks; -function isEnum(obj, key) { - return Object.prototype.propertyIsEnumerable.call(obj, key); -} +module.exports.hasMagic = (patterns, options) => [] + .concat(patterns) + .some(pattern => glob.hasMagic(pattern, options)); + +module.exports.gitignore = gitignore; /***/ }), -/* 624 */ +/* 636 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/*! - * is-extendable - * - * Copyright (c) 2015-2017, Jon Schlinkert. - * Released under the MIT License. - */ +var arrayUniq = __webpack_require__(637); - -var isPlainObject = __webpack_require__(625); - -module.exports = function isExtendable(val) { - return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); +module.exports = function () { + return arrayUniq([].concat.apply([], arguments)); }; /***/ }), -/* 625 */ +/* 637 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/*! - * is-plain-object - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. - */ - - -var isObject = __webpack_require__(618); -function isObjectObject(o) { - return isObject(o) === true - && Object.prototype.toString.call(o) === '[object Object]'; -} +// there's 3 implementations written in increasing order of efficiency -module.exports = function isPlainObject(o) { - var ctor,prot; +// 1 - no Set type is defined +function uniqNoSet(arr) { + var ret = []; - if (isObjectObject(o) === false) return false; + for (var i = 0; i < arr.length; i++) { + if (ret.indexOf(arr[i]) === -1) { + ret.push(arr[i]); + } + } - // If has modified constructor - ctor = o.constructor; - if (typeof ctor !== 'function') return false; + return ret; +} - // If has modified prototype - prot = ctor.prototype; - if (isObjectObject(prot) === false) return false; +// 2 - a simple Set type is defined +function uniqSet(arr) { + var seen = new Set(); + return arr.filter(function (el) { + if (!seen.has(el)) { + seen.add(el); + return true; + } - // If constructor does not have an Object-specific method - if (prot.hasOwnProperty('isPrototypeOf') === false) { - return false; - } + return false; + }); +} - // Most likely a plain Object - return true; -}; +// 3 - a standard Set type is defined and it has a forEach method +function uniqSetWithForEach(arr) { + var ret = []; + (new Set(arr)).forEach(function (el) { + ret.push(el); + }); -/***/ }), -/* 626 */ -/***/ (function(module, exports, __webpack_require__) { + return ret; +} -"use strict"; -/*! - * assign-symbols - * - * Copyright (c) 2015, Jon Schlinkert. - * Licensed under the MIT License. - */ +// V8 currently has a broken implementation +// https://github.com/joyent/node/issues/8449 +function doesForEachActuallyWork() { + var ret = false; + (new Set([true])).forEach(function (el) { + ret = el; + }); + return ret === true; +} -module.exports = function(receiver, objects) { - if (receiver === null || typeof receiver === 'undefined') { - throw new TypeError('expected first argument to be an object.'); - } +if ('Set' in global) { + if (typeof Set.prototype.forEach === 'function' && doesForEachActuallyWork()) { + module.exports = uniqSetWithForEach; + } else { + module.exports = uniqSet; + } +} else { + module.exports = uniqNoSet; +} - if (typeof objects === 'undefined' || typeof Symbol === 'undefined') { - return receiver; - } - if (typeof Object.getOwnPropertySymbols !== 'function') { - return receiver; - } +/***/ }), +/* 638 */ +/***/ (function(module, exports, __webpack_require__) { - var isEnumerable = Object.prototype.propertyIsEnumerable; - var target = Object(receiver); - var len = arguments.length, i = 0; +const pkg = __webpack_require__(639); - while (++i < len) { - var provider = Object(arguments[i]); - var names = Object.getOwnPropertySymbols(provider); +module.exports = pkg.async; +module.exports.default = pkg.async; - for (var j = 0; j < names.length; j++) { - var key = names[j]; +module.exports.async = pkg.async; +module.exports.sync = pkg.sync; +module.exports.stream = pkg.stream; - if (isEnumerable.call(provider, key)) { - target[key] = provider[key]; - } - } - } - return target; -}; +module.exports.generateTasks = pkg.generateTasks; /***/ }), -/* 627 */ +/* 639 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var optionsManager = __webpack_require__(640); +var taskManager = __webpack_require__(641); +var reader_async_1 = __webpack_require__(792); +var reader_stream_1 = __webpack_require__(816); +var reader_sync_1 = __webpack_require__(817); +var arrayUtils = __webpack_require__(819); +var streamUtils = __webpack_require__(820); +/** + * Synchronous API. + */ +function sync(source, opts) { + assertPatternsInput(source); + var works = getWorks(source, reader_sync_1.default, opts); + return arrayUtils.flatten(works); +} +exports.sync = sync; +/** + * Asynchronous API. + */ +function async(source, opts) { + try { + assertPatternsInput(source); + } + catch (error) { + return Promise.reject(error); + } + var works = getWorks(source, reader_async_1.default, opts); + return Promise.all(works).then(arrayUtils.flatten); +} +exports.async = async; +/** + * Stream API. + */ +function stream(source, opts) { + assertPatternsInput(source); + var works = getWorks(source, reader_stream_1.default, opts); + return streamUtils.merge(works); +} +exports.stream = stream; +/** + * Return a set of tasks based on provided patterns. + */ +function generateTasks(source, opts) { + assertPatternsInput(source); + var patterns = [].concat(source); + var options = optionsManager.prepare(opts); + return taskManager.generate(patterns, options); +} +exports.generateTasks = generateTasks; +/** + * Returns a set of works based on provided tasks and class of the reader. + */ +function getWorks(source, _Reader, opts) { + var patterns = [].concat(source); + var options = optionsManager.prepare(opts); + var tasks = taskManager.generate(patterns, options); + var reader = new _Reader(options); + return tasks.map(reader.read, reader); +} +function assertPatternsInput(source) { + if ([].concat(source).every(isString)) { + return; + } + throw new TypeError('Patterns must be a string or an array of strings'); +} +function isString(source) { + /* tslint:disable-next-line strict-type-predicates */ + return typeof source === 'string'; +} -var extend = __webpack_require__(628); -var safe = __webpack_require__(611); - -/** - * The main export is a function that takes a `pattern` string and an `options` object. - * - * ```js - & var not = require('regex-not'); - & console.log(not('foo')); - & //=> /^(?:(?!^(?:foo)$).)*$/ - * ``` - * - * @param {String} `pattern` - * @param {Object} `options` - * @return {RegExp} Converts the given `pattern` to a regex using the specified `options`. - * @api public - */ - -function toRegex(pattern, options) { - return new RegExp(toRegex.create(pattern, options)); -} - -/** - * Create a regex-compatible string from the given `pattern` and `options`. - * - * ```js - & var not = require('regex-not'); - & console.log(not.create('foo')); - & //=> '^(?:(?!^(?:foo)$).)*$' - * ``` - * @param {String} `pattern` - * @param {Object} `options` - * @return {String} - * @api public - */ - -toRegex.create = function(pattern, options) { - if (typeof pattern !== 'string') { - throw new TypeError('expected a string'); - } +/***/ }), +/* 640 */ +/***/ (function(module, exports, __webpack_require__) { - var opts = extend({}, options); - if (opts.contains === true) { - opts.strictNegate = false; - } +"use strict"; + +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +function prepare(options) { + var opts = __assign({ cwd: process.cwd(), deep: true, ignore: [], dot: false, stats: false, onlyFiles: true, onlyDirectories: false, followSymlinkedDirectories: true, unique: true, markDirectories: false, absolute: false, nobrace: false, brace: true, noglobstar: false, globstar: true, noext: false, extension: true, nocase: false, case: true, matchBase: false, transform: null }, options); + if (opts.onlyDirectories) { + opts.onlyFiles = false; + } + opts.brace = !opts.nobrace; + opts.globstar = !opts.noglobstar; + opts.extension = !opts.noext; + opts.case = !opts.nocase; + if (options) { + opts.brace = ('brace' in options ? options.brace : opts.brace); + opts.globstar = ('globstar' in options ? options.globstar : opts.globstar); + opts.extension = ('extension' in options ? options.extension : opts.extension); + opts.case = ('case' in options ? options.case : opts.case); + } + return opts; +} +exports.prepare = prepare; - var open = opts.strictOpen !== false ? '^' : ''; - var close = opts.strictClose !== false ? '$' : ''; - var endChar = opts.endChar ? opts.endChar : '+'; - var str = pattern; - if (opts.strictNegate === false) { - str = '(?:(?!(?:' + pattern + ')).)' + endChar; - } else { - str = '(?:(?!^(?:' + pattern + ')$).)' + endChar; - } +/***/ }), +/* 641 */ +/***/ (function(module, exports, __webpack_require__) { - var res = open + str + close; - if (opts.safe === true && safe(res) === false) { - throw new Error('potentially unsafe regular expression: ' + res); - } +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var patternUtils = __webpack_require__(642); +/** + * Generate tasks based on parent directory of each pattern. + */ +function generate(patterns, options) { + var unixPatterns = patterns.map(patternUtils.unixifyPattern); + var unixIgnore = options.ignore.map(patternUtils.unixifyPattern); + var positivePatterns = getPositivePatterns(unixPatterns); + var negativePatterns = getNegativePatternsAsPositive(unixPatterns, unixIgnore); + /** + * When the `case` option is disabled, all patterns must be marked as dynamic, because we cannot check filepath + * directly (without read directory). + */ + var staticPatterns = !options.case ? [] : positivePatterns.filter(patternUtils.isStaticPattern); + var dynamicPatterns = !options.case ? positivePatterns : positivePatterns.filter(patternUtils.isDynamicPattern); + var staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false); + var dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, /* dynamic */ true); + return staticTasks.concat(dynamicTasks); +} +exports.generate = generate; +/** + * Convert patterns to tasks based on parent directory of each pattern. + */ +function convertPatternsToTasks(positive, negative, dynamic) { + var positivePatternsGroup = groupPatternsByBaseDirectory(positive); + // When we have a global group – there is no reason to divide the patterns into independent tasks. + // In this case, the global task covers the rest. + if ('.' in positivePatternsGroup) { + var task = convertPatternGroupToTask('.', positive, negative, dynamic); + return [task]; + } + return convertPatternGroupsToTasks(positivePatternsGroup, negative, dynamic); +} +exports.convertPatternsToTasks = convertPatternsToTasks; +/** + * Return only positive patterns. + */ +function getPositivePatterns(patterns) { + return patternUtils.getPositivePatterns(patterns); +} +exports.getPositivePatterns = getPositivePatterns; +/** + * Return only negative patterns. + */ +function getNegativePatternsAsPositive(patterns, ignore) { + var negative = patternUtils.getNegativePatterns(patterns).concat(ignore); + var positive = negative.map(patternUtils.convertToPositivePattern); + return positive; +} +exports.getNegativePatternsAsPositive = getNegativePatternsAsPositive; +/** + * Group patterns by base directory of each pattern. + */ +function groupPatternsByBaseDirectory(patterns) { + return patterns.reduce(function (collection, pattern) { + var base = patternUtils.getBaseDirectory(pattern); + if (base in collection) { + collection[base].push(pattern); + } + else { + collection[base] = [pattern]; + } + return collection; + }, {}); +} +exports.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory; +/** + * Convert group of patterns to tasks. + */ +function convertPatternGroupsToTasks(positive, negative, dynamic) { + return Object.keys(positive).map(function (base) { + return convertPatternGroupToTask(base, positive[base], negative, dynamic); + }); +} +exports.convertPatternGroupsToTasks = convertPatternGroupsToTasks; +/** + * Create a task for positive and negative patterns. + */ +function convertPatternGroupToTask(base, positive, negative, dynamic) { + return { + base: base, + dynamic: dynamic, + positive: positive, + negative: negative, + patterns: [].concat(positive, negative.map(patternUtils.convertToNegativePattern)) + }; +} +exports.convertPatternGroupToTask = convertPatternGroupToTask; - return res; -}; -/** - * Expose `toRegex` - */ +/***/ }), +/* 642 */ +/***/ (function(module, exports, __webpack_require__) { -module.exports = toRegex; +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var path = __webpack_require__(4); +var globParent = __webpack_require__(643); +var isGlob = __webpack_require__(387); +var micromatch = __webpack_require__(646); +var GLOBSTAR = '**'; +/** + * Return true for static pattern. + */ +function isStaticPattern(pattern) { + return !isDynamicPattern(pattern); +} +exports.isStaticPattern = isStaticPattern; +/** + * Return true for pattern that looks like glob. + */ +function isDynamicPattern(pattern) { + return isGlob(pattern, { strict: false }); +} +exports.isDynamicPattern = isDynamicPattern; +/** + * Convert a windows «path» to a unix-style «path». + */ +function unixifyPattern(pattern) { + return pattern.replace(/\\/g, '/'); +} +exports.unixifyPattern = unixifyPattern; +/** + * Returns negative pattern as positive pattern. + */ +function convertToPositivePattern(pattern) { + return isNegativePattern(pattern) ? pattern.slice(1) : pattern; +} +exports.convertToPositivePattern = convertToPositivePattern; +/** + * Returns positive pattern as negative pattern. + */ +function convertToNegativePattern(pattern) { + return '!' + pattern; +} +exports.convertToNegativePattern = convertToNegativePattern; +/** + * Return true if provided pattern is negative pattern. + */ +function isNegativePattern(pattern) { + return pattern.startsWith('!') && pattern[1] !== '('; +} +exports.isNegativePattern = isNegativePattern; +/** + * Return true if provided pattern is positive pattern. + */ +function isPositivePattern(pattern) { + return !isNegativePattern(pattern); +} +exports.isPositivePattern = isPositivePattern; +/** + * Extracts negative patterns from array of patterns. + */ +function getNegativePatterns(patterns) { + return patterns.filter(isNegativePattern); +} +exports.getNegativePatterns = getNegativePatterns; +/** + * Extracts positive patterns from array of patterns. + */ +function getPositivePatterns(patterns) { + return patterns.filter(isPositivePattern); +} +exports.getPositivePatterns = getPositivePatterns; +/** + * Extract base directory from provided pattern. + */ +function getBaseDirectory(pattern) { + return globParent(pattern); +} +exports.getBaseDirectory = getBaseDirectory; +/** + * Return true if provided pattern has globstar. + */ +function hasGlobStar(pattern) { + return pattern.indexOf(GLOBSTAR) !== -1; +} +exports.hasGlobStar = hasGlobStar; +/** + * Return true if provided pattern ends with slash and globstar. + */ +function endsWithSlashGlobStar(pattern) { + return pattern.endsWith('/' + GLOBSTAR); +} +exports.endsWithSlashGlobStar = endsWithSlashGlobStar; +/** + * Returns «true» when pattern ends with a slash and globstar or the last partial of the pattern is static pattern. + */ +function isAffectDepthOfReadingPattern(pattern) { + var basename = path.basename(pattern); + return endsWithSlashGlobStar(pattern) || isStaticPattern(basename); +} +exports.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern; +/** + * Return naive depth of provided pattern without depth of the base directory. + */ +function getNaiveDepth(pattern) { + var base = getBaseDirectory(pattern); + var patternDepth = pattern.split('/').length; + var patternBaseDepth = base.split('/').length; + /** + * This is a hack for pattern that has no base directory. + * + * This is related to the `*\something\*` pattern. + */ + if (base === '.') { + return patternDepth - patternBaseDepth; + } + return patternDepth - patternBaseDepth - 1; +} +exports.getNaiveDepth = getNaiveDepth; +/** + * Return max naive depth of provided patterns without depth of the base directory. + */ +function getMaxNaivePatternsDepth(patterns) { + return patterns.reduce(function (max, pattern) { + var depth = getNaiveDepth(pattern); + return depth > max ? depth : max; + }, 0); +} +exports.getMaxNaivePatternsDepth = getMaxNaivePatternsDepth; +/** + * Make RegExp for provided pattern. + */ +function makeRe(pattern, options) { + return micromatch.makeRe(pattern, options); +} +exports.makeRe = makeRe; +/** + * Convert patterns to regexps. + */ +function convertPatternsToRe(patterns, options) { + return patterns.map(function (pattern) { return makeRe(pattern, options); }); +} +exports.convertPatternsToRe = convertPatternsToRe; +/** + * Returns true if the entry match any of the given RegExp's. + */ +function matchAny(entry, patternsRe) { + return patternsRe.some(function (patternRe) { return patternRe.test(entry); }); +} +exports.matchAny = matchAny; /***/ }), -/* 628 */ +/* 643 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var isExtendable = __webpack_require__(629); -var assignSymbols = __webpack_require__(626); - -module.exports = Object.assign || function(obj/*, objects*/) { - if (obj === null || typeof obj === 'undefined') { - throw new TypeError('Cannot convert undefined or null to object'); - } - if (!isObject(obj)) { - obj = {}; - } - for (var i = 1; i < arguments.length; i++) { - var val = arguments[i]; - if (isString(val)) { - val = toObject(val); - } - if (isObject(val)) { - assign(obj, val); - assignSymbols(obj, val); - } - } - return obj; -}; - -function assign(a, b) { - for (var key in b) { - if (hasOwn(b, key)) { - a[key] = b[key]; - } - } -} - -function isString(val) { - return (val && typeof val === 'string'); -} - -function toObject(str) { - var obj = {}; - for (var i in str) { - obj[i] = str[i]; - } - return obj; -} - -function isObject(val) { - return (val && typeof val === 'object') || isExtendable(val); -} - -/** - * Returns true if the given `key` is an own property of `obj`. - */ - -function hasOwn(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -} - -function isEnum(obj, key) { - return Object.prototype.propertyIsEnumerable.call(obj, key); -} - - -/***/ }), -/* 629 */ -/***/ (function(module, exports, __webpack_require__) { +var path = __webpack_require__(4); +var isglob = __webpack_require__(644); +var pathDirname = __webpack_require__(645); +var isWin32 = __webpack_require__(243).platform() === 'win32'; -"use strict"; -/*! - * is-extendable - * - * Copyright (c) 2015-2017, Jon Schlinkert. - * Released under the MIT License. - */ +module.exports = function globParent(str) { + // flip windows path separators + if (isWin32 && str.indexOf('/') < 0) str = str.split('\\').join('/'); + // special case for strings ending in enclosure containing path separator + if (/[\{\[].*[\/]*.*[\}\]]$/.test(str)) str += '/'; + // preserves full path in case of trailing path separator + str += 'a'; -var isPlainObject = __webpack_require__(625); + // remove path parts that are globby + do {str = pathDirname.posix(str)} + while (isglob(str) || /(^|[^\\])([\{\[]|\([^\)]+$)/.test(str)); -module.exports = function isExtendable(val) { - return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); + // remove escape chars and return result + return str.replace(/\\([\*\?\|\[\]\(\)\{\}])/g, '$1'); }; /***/ }), -/* 630 */ +/* 644 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; /*! - * array-unique + * is-glob * - * Copyright (c) 2014-2015, Jon Schlinkert. + * Copyright (c) 2014-2016, Jon Schlinkert. * Licensed under the MIT License. */ +var isExtglob = __webpack_require__(388); - -module.exports = function unique(arr) { - if (!Array.isArray(arr)) { - throw new TypeError('array-unique expects an array.'); - } - - var len = arr.length; - var i = -1; - - while (i++ < len) { - var j = i + 1; - - for (; j < arr.length; ++j) { - if (arr[i] === arr[j]) { - arr.splice(j--, 1); - } - } +module.exports = function isGlob(str) { + if (typeof str !== 'string' || str === '') { + return false; } - return arr; -}; -module.exports.immutable = function uniqueImmutable(arr) { - if (!Array.isArray(arr)) { - throw new TypeError('array-unique expects an array.'); - } + if (isExtglob(str)) return true; - var arrLen = arr.length; - var newArr = new Array(arrLen); + var regex = /(\\).|([*?]|\[.*\]|\{.*\}|\(.*\|.*\)|^!)/; + var match; - for (var i = 0; i < arrLen; i++) { - newArr[i] = arr[i]; + while ((match = regex.exec(str))) { + if (match[2]) return true; + str = str.slice(match.index + match[0].length); } - - return module.exports(newArr); + return false; }; /***/ }), -/* 631 */ +/* 645 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var isObject = __webpack_require__(632); - -module.exports = function extend(o/*, objects*/) { - if (!isObject(o)) { o = {}; } - - var len = arguments.length; - for (var i = 1; i < len; i++) { - var obj = arguments[i]; - - if (isObject(obj)) { - assign(o, obj); - } - } - return o; -}; +var path = __webpack_require__(4); +var inspect = __webpack_require__(234).inspect; -function assign(a, b) { - for (var key in b) { - if (hasOwn(b, key)) { - a[key] = b[key]; - } +function assertPath(path) { + if (typeof path !== 'string') { + throw new TypeError('Path must be a string. Received ' + inspect(path)); } } -/** - * Returns true if the given `key` is an own property of `obj`. - */ - -function hasOwn(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -} - - -/***/ }), -/* 632 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/*! - * is-extendable - * - * Copyright (c) 2015, Jon Schlinkert. - * Licensed under the MIT License. - */ - - - -module.exports = function isExtendable(val) { - return typeof val !== 'undefined' && val !== null - && (typeof val === 'object' || typeof val === 'function'); -}; - - -/***/ }), -/* 633 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var utils = __webpack_require__(634); - -module.exports = function(braces, options) { - braces.compiler - - /** - * bos - */ - - .set('bos', function() { - if (this.output) return; - this.ast.queue = isEscaped(this.ast) ? [this.ast.val] : []; - this.ast.count = 1; - }) - - /** - * Square brackets - */ - - .set('bracket', function(node) { - var close = node.close; - var open = !node.escaped ? '[' : '\\['; - var negated = node.negated; - var inner = node.inner; - - inner = inner.replace(/\\(?=[\\\w]|$)/g, '\\\\'); - if (inner === ']-') { - inner = '\\]\\-'; - } - - if (negated && inner.indexOf('.') === -1) { - inner += '.'; - } - if (negated && inner.indexOf('/') === -1) { - inner += '/'; - } - - var val = open + negated + inner + close; - var queue = node.parent.queue; - var last = utils.arrayify(queue.pop()); - - queue.push(utils.join(last, val)); - queue.push.apply(queue, []); - }) - - /** - * Brace - */ - - .set('brace', function(node) { - node.queue = isEscaped(node) ? [node.val] : []; - node.count = 1; - return this.mapVisit(node.nodes); - }) - - /** - * Open - */ - - .set('brace.open', function(node) { - node.parent.open = node.val; - }) - - /** - * Inner - */ - - .set('text', function(node) { - var queue = node.parent.queue; - var escaped = node.escaped; - var segs = [node.val]; - - if (node.optimize === false) { - options = utils.extend({}, options, {optimize: false}); - } - - if (node.multiplier > 1) { - node.parent.count *= node.multiplier; - } - - if (options.quantifiers === true && utils.isQuantifier(node.val)) { - escaped = true; - - } else if (node.val.length > 1) { - if (isType(node.parent, 'brace') && !isEscaped(node)) { - var expanded = utils.expand(node.val, options); - segs = expanded.segs; - - if (expanded.isOptimized) { - node.parent.isOptimized = true; - } - - // if nothing was expanded, we probably have a literal brace - if (!segs.length) { - var val = (expanded.val || node.val); - if (options.unescape !== false) { - // unescape unexpanded brace sequence/set separators - val = val.replace(/\\([,.])/g, '$1'); - // strip quotes - val = val.replace(/["'`]/g, ''); - } - - segs = [val]; - escaped = true; - } - } - - } else if (node.val === ',') { - if (options.expand) { - node.parent.queue.push(['']); - segs = ['']; - } else { - segs = ['|']; - } - } else { - escaped = true; - } - - if (escaped && isType(node.parent, 'brace')) { - if (node.parent.nodes.length <= 4 && node.parent.count === 1) { - node.parent.escaped = true; - } else if (node.parent.length <= 3) { - node.parent.escaped = true; - } - } - - if (!hasQueue(node.parent)) { - node.parent.queue = segs; - return; - } - - var last = utils.arrayify(queue.pop()); - if (node.parent.count > 1 && options.expand) { - last = multiply(last, node.parent.count); - node.parent.count = 1; - } - - queue.push(utils.join(utils.flatten(last), segs.shift())); - queue.push.apply(queue, segs); - }) - - /** - * Close - */ - - .set('brace.close', function(node) { - var queue = node.parent.queue; - var prev = node.parent.parent; - var last = prev.queue.pop(); - var open = node.parent.open; - var close = node.val; - - if (open && close && isOptimized(node, options)) { - open = '('; - close = ')'; - } - - // if a close brace exists, and the previous segment is one character - // don't wrap the result in braces or parens - var ele = utils.last(queue); - if (node.parent.count > 1 && options.expand) { - ele = multiply(queue.pop(), node.parent.count); - node.parent.count = 1; - queue.push(ele); - } - - if (close && typeof ele === 'string' && ele.length === 1) { - open = ''; - close = ''; - } - - if ((isLiteralBrace(node, options) || noInner(node)) && !node.parent.hasEmpty) { - queue.push(utils.join(open, queue.pop() || '')); - queue = utils.flatten(utils.join(queue, close)); - } - - if (typeof last === 'undefined') { - prev.queue = [queue]; - } else { - prev.queue.push(utils.flatten(utils.join(last, queue))); - } - }) - - /** - * eos - */ - - .set('eos', function(node) { - if (this.input) return; - - if (options.optimize !== false) { - this.output = utils.last(utils.flatten(this.ast.queue)); - } else if (Array.isArray(utils.last(this.ast.queue))) { - this.output = utils.flatten(this.ast.queue.pop()); - } else { - this.output = utils.flatten(this.ast.queue); - } - - if (node.parent.count > 1 && options.expand) { - this.output = multiply(this.output, node.parent.count); +function posix(path) { + assertPath(path); + if (path.length === 0) + return '.'; + var code = path.charCodeAt(0); + var hasRoot = (code === 47/*/*/); + var end = -1; + var matchedSlash = true; + for (var i = path.length - 1; i >= 1; --i) { + code = path.charCodeAt(i); + if (code === 47/*/*/) { + if (!matchedSlash) { + end = i; + break; } + } else { + // We saw the first non-path separator + matchedSlash = false; + } + } - this.output = utils.arrayify(this.output); - this.ast.queue = []; - }); - -}; - -/** - * Multiply the segments in the current brace level - */ - -function multiply(queue, n, options) { - return utils.flatten(utils.repeat(utils.arrayify(queue), n)); -} - -/** - * Return true if `node` is escaped - */ - -function isEscaped(node) { - return node.escaped === true; + if (end === -1) + return hasRoot ? '/' : '.'; + if (hasRoot && end === 1) + return '//'; + return path.slice(0, end); } -/** - * Returns true if regex parens should be used for sets. If the parent `type` - * is not `brace`, then we're on a root node, which means we should never - * expand segments and open/close braces should be `{}` (since this indicates - * a brace is missing from the set) - */ +function win32(path) { + assertPath(path); + var len = path.length; + if (len === 0) + return '.'; + var rootEnd = -1; + var end = -1; + var matchedSlash = true; + var offset = 0; + var code = path.charCodeAt(0); -function isOptimized(node, options) { - if (node.parent.isOptimized) return true; - return isType(node.parent, 'brace') - && !isEscaped(node.parent) - && options.expand !== true; -} + // Try to match a root + if (len > 1) { + if (code === 47/*/*/ || code === 92/*\*/) { + // Possible UNC root -/** - * Returns true if the value in `node` should be wrapped in a literal brace. - * @return {Boolean} - */ + rootEnd = offset = 1; -function isLiteralBrace(node, options) { - return isEscaped(node.parent) || options.optimize !== false; -} + code = path.charCodeAt(1); + if (code === 47/*/*/ || code === 92/*\*/) { + // Matched double path separator at beginning + var j = 2; + var last = j; + // Match 1 or more non-path separators + for (; j < len; ++j) { + code = path.charCodeAt(j); + if (code === 47/*/*/ || code === 92/*\*/) + break; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more path separators + for (; j < len; ++j) { + code = path.charCodeAt(j); + if (code !== 47/*/*/ && code !== 92/*\*/) + break; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more non-path separators + for (; j < len; ++j) { + code = path.charCodeAt(j); + if (code === 47/*/*/ || code === 92/*\*/) + break; + } + if (j === len) { + // We matched a UNC root only + return path; + } + if (j !== last) { + // We matched a UNC root with leftovers -/** - * Returns true if the given `node` does not have an inner value. - * @return {Boolean} - */ + // Offset by 1 to include the separator after the UNC root to + // treat it as a "normal root" on top of a (UNC) root + rootEnd = offset = j + 1; + } + } + } + } + } else if ((code >= 65/*A*/ && code <= 90/*Z*/) || + (code >= 97/*a*/ && code <= 122/*z*/)) { + // Possible device root -function noInner(node, type) { - if (node.parent.queue.length === 1) { - return true; + code = path.charCodeAt(1); + if (path.charCodeAt(1) === 58/*:*/) { + rootEnd = offset = 2; + if (len > 2) { + code = path.charCodeAt(2); + if (code === 47/*/*/ || code === 92/*\*/) + rootEnd = offset = 3; + } + } + } + } else if (code === 47/*/*/ || code === 92/*\*/) { + return path[0]; } - var nodes = node.parent.nodes; - return nodes.length === 3 - && isType(nodes[0], 'brace.open') - && !isType(nodes[1], 'text') - && isType(nodes[2], 'brace.close'); -} -/** - * Returns true if the given `node` is the given `type` - * @return {Boolean} - */ + for (var i = len - 1; i >= offset; --i) { + code = path.charCodeAt(i); + if (code === 47/*/*/ || code === 92/*\*/) { + if (!matchedSlash) { + end = i; + break; + } + } else { + // We saw the first non-path separator + matchedSlash = false; + } + } -function isType(node, type) { - return typeof node !== 'undefined' && node.type === type; + if (end === -1) { + if (rootEnd === -1) + return '.'; + else + end = rootEnd; + } + return path.slice(0, end); } -/** - * Returns true if the given `node` has a non-empty queue. - * @return {Boolean} - */ - -function hasQueue(node) { - return Array.isArray(node.queue) && node.queue.length; -} +module.exports = process.platform === 'win32' ? win32 : posix; +module.exports.posix = posix; +module.exports.win32 = win32; /***/ }), -/* 634 */ +/* 646 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var splitString = __webpack_require__(635); -var utils = module.exports; - /** * Module dependencies */ -utils.extend = __webpack_require__(631); -utils.flatten = __webpack_require__(638); -utils.isObject = __webpack_require__(618); -utils.fillRange = __webpack_require__(639); -utils.repeat = __webpack_require__(647); -utils.unique = __webpack_require__(630); - -utils.define = function(obj, key, val) { - Object.defineProperty(obj, key, { - writable: true, - configurable: true, - enumerable: false, - value: val - }); -}; +var util = __webpack_require__(234); +var braces = __webpack_require__(647); +var toRegex = __webpack_require__(648); +var extend = __webpack_require__(760); /** - * Returns true if the given string contains only empty brace sets. + * Local dependencies */ -utils.isEmptySets = function(str) { - return /^(?:\{,\})+$/.test(str); -}; +var compilers = __webpack_require__(762); +var parsers = __webpack_require__(788); +var cache = __webpack_require__(789); +var utils = __webpack_require__(790); +var MAX_LENGTH = 1024 * 64; /** - * Returns true if the given string contains only empty brace sets. + * The main function takes a list of strings and one or more + * glob patterns to use for matching. + * + * ```js + * var mm = require('micromatch'); + * mm(list, patterns[, options]); + * + * console.log(mm(['a.js', 'a.txt'], ['*.js'])); + * //=> [ 'a.js' ] + * ``` + * @param {Array} `list` A list of strings to match + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array} Returns an array of matches + * @summary false + * @api public */ -utils.isQuotedString = function(str) { - var open = str.charAt(0); - if (open === '\'' || open === '"' || open === '`') { - return str.slice(-1) === open; - } - return false; -}; - -/** - * Create the key to use for memoization. The unique key is generated - * by iterating over the options and concatenating key-value pairs - * to the pattern string. - */ +function micromatch(list, patterns, options) { + patterns = utils.arrayify(patterns); + list = utils.arrayify(list); -utils.createKey = function(pattern, options) { - var id = pattern; - if (typeof options === 'undefined') { - return id; + var len = patterns.length; + if (list.length === 0 || len === 0) { + return []; } - var keys = Object.keys(options); - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - id += ';' + key + '=' + String(options[key]); + + if (len === 1) { + return micromatch.match(list, patterns[0], options); } - return id; -}; -/** - * Normalize options - */ + var omit = []; + var keep = []; + var idx = -1; -utils.createOptions = function(options) { - var opts = utils.extend.apply(null, arguments); - if (typeof opts.expand === 'boolean') { - opts.optimize = !opts.expand; - } - if (typeof opts.optimize === 'boolean') { - opts.expand = !opts.optimize; + while (++idx < len) { + var pattern = patterns[idx]; + + if (typeof pattern === 'string' && pattern.charCodeAt(0) === 33 /* ! */) { + omit.push.apply(omit, micromatch.match(list, pattern.slice(1), options)); + } else { + keep.push.apply(keep, micromatch.match(list, pattern, options)); + } } - if (opts.optimize === true) { - opts.makeRe = true; + + var matches = utils.diff(keep, omit); + if (!options || options.nodupes !== false) { + return utils.unique(matches); } - return opts; -}; + + return matches; +} /** - * Join patterns in `a` to patterns in `b` + * Similar to the main function, but `pattern` must be a string. + * + * ```js + * var mm = require('micromatch'); + * mm.match(list, pattern[, options]); + * + * console.log(mm.match(['a.a', 'a.aa', 'a.b', 'a.c'], '*.a')); + * //=> ['a.a', 'a.aa'] + * ``` + * @param {Array} `list` Array of strings to match + * @param {String} `pattern` Glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array} Returns an array of matches + * @api public */ -utils.join = function(a, b, options) { - options = options || {}; - a = utils.arrayify(a); - b = utils.arrayify(b); +micromatch.match = function(list, pattern, options) { + if (Array.isArray(pattern)) { + throw new TypeError('expected pattern to be a string'); + } - if (!a.length) return b; - if (!b.length) return a; + var unixify = utils.unixify(options); + var isMatch = memoize('match', pattern, options, micromatch.matcher); + var matches = []; - var len = a.length; + list = utils.arrayify(list); + var len = list.length; var idx = -1; - var arr = []; while (++idx < len) { - var val = a[idx]; - if (Array.isArray(val)) { - for (var i = 0; i < val.length; i++) { - val[i] = utils.join(val[i], b, options); - } - arr.push(val); - continue; + var ele = list[idx]; + if (ele === pattern || isMatch(ele)) { + matches.push(utils.value(ele, unixify, options)); } + } - for (var j = 0; j < b.length; j++) { - var bval = b[j]; + // if no options were passed, uniquify results and return + if (typeof options === 'undefined') { + return utils.unique(matches); + } - if (Array.isArray(bval)) { - arr.push(utils.join(val, bval, options)); - } else { - arr.push(val + bval); - } + if (matches.length === 0) { + if (options.failglob === true) { + throw new Error('no matches found for "' + pattern + '"'); + } + if (options.nonull === true || options.nullglob === true) { + return [options.unescape ? utils.unescape(pattern) : pattern]; } } - return arr; -}; - -/** - * Split the given string on `,` if not escaped. - */ -utils.split = function(str, options) { - var opts = utils.extend({sep: ','}, options); - if (typeof opts.keepQuotes !== 'boolean') { - opts.keepQuotes = true; - } - if (opts.unescape === false) { - opts.keepEscaping = true; + // if `opts.ignore` was defined, diff ignored list + if (options.ignore) { + matches = micromatch.not(matches, options.ignore, options); } - return splitString(str, opts, utils.escapeBrackets(opts)); + + return options.nodupes !== false ? utils.unique(matches) : matches; }; /** - * Expand ranges or sets in the given `pattern`. + * Returns true if the specified `string` matches the given glob `pattern`. * - * @param {String} `str` - * @param {Object} `options` - * @return {Object} + * ```js + * var mm = require('micromatch'); + * mm.isMatch(string, pattern[, options]); + * + * console.log(mm.isMatch('a.a', '*.a')); + * //=> true + * console.log(mm.isMatch('a.b', '*.a')); + * //=> false + * ``` + * @param {String} `string` String to match + * @param {String} `pattern` Glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if the string matches the glob pattern. + * @api public */ -utils.expand = function(str, options) { - var opts = utils.extend({rangeLimit: 10000}, options); - var segs = utils.split(str, opts); - var tok = { segs: segs }; - - if (utils.isQuotedString(str)) { - return tok; +micromatch.isMatch = function(str, pattern, options) { + if (typeof str !== 'string') { + throw new TypeError('expected a string: "' + util.inspect(str) + '"'); } - if (opts.rangeLimit === true) { - opts.rangeLimit = 10000; + if (isEmptyString(str) || isEmptyString(pattern)) { + return false; } - if (segs.length > 1) { - if (opts.optimize === false) { - tok.val = segs[0]; - return tok; - } - - tok.segs = utils.stringifyArray(tok.segs); - } else if (segs.length === 1) { - var arr = str.split('..'); - - if (arr.length === 1) { - tok.val = tok.segs[tok.segs.length - 1] || tok.val || str; - tok.segs = []; - return tok; - } - - if (arr.length === 2 && arr[0] === arr[1]) { - tok.escaped = true; - tok.val = arr[0]; - tok.segs = []; - return tok; - } - - if (arr.length > 1) { - if (opts.optimize !== false) { - opts.optimize = true; - delete opts.expand; - } - - if (opts.optimize !== true) { - var min = Math.min(arr[0], arr[1]); - var max = Math.max(arr[0], arr[1]); - var step = arr[2] || 1; - - if (opts.rangeLimit !== false && ((max - min) / step >= opts.rangeLimit)) { - throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.'); - } - } - - arr.push(opts); - tok.segs = utils.fillRange.apply(null, arr); + var equals = utils.equalsPattern(options); + if (equals(str)) { + return true; + } - if (!tok.segs.length) { - tok.escaped = true; - tok.val = str; - return tok; - } + var isMatch = memoize('isMatch', pattern, options, micromatch.matcher); + return isMatch(str); +}; - if (opts.optimize === true) { - tok.segs = utils.stringifyArray(tok.segs); - } +/** + * Returns true if some of the strings in the given `list` match any of the + * given glob `patterns`. + * + * ```js + * var mm = require('micromatch'); + * mm.some(list, patterns[, options]); + * + * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * // true + * console.log(mm.some(['foo.js'], ['*.js', '!foo.js'])); + * // false + * ``` + * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ - if (tok.segs === '') { - tok.val = str; - } else { - tok.val = tok.segs[0]; - } - return tok; +micromatch.some = function(list, patterns, options) { + if (typeof list === 'string') { + list = [list]; + } + for (var i = 0; i < list.length; i++) { + if (micromatch(list[i], patterns, options).length === 1) { + return true; } - } else { - tok.val = str; } - return tok; + return false; }; /** - * Ensure commas inside brackets and parens are not split. - * @param {Object} `tok` Token from the `split-string` module - * @return {undefined} + * Returns true if every string in the given `list` matches + * any of the given glob `patterns`. + * + * ```js + * var mm = require('micromatch'); + * mm.every(list, patterns[, options]); + * + * console.log(mm.every('foo.js', ['foo.js'])); + * // true + * console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); + * // true + * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * // false + * console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); + * // false + * ``` + * @param {String|Array} `list` The string or array of strings to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public */ -utils.escapeBrackets = function(options) { - return function(tok) { - if (tok.escaped && tok.val === 'b') { - tok.val = '\\b'; - return; +micromatch.every = function(list, patterns, options) { + if (typeof list === 'string') { + list = [list]; + } + for (var i = 0; i < list.length; i++) { + if (micromatch(list[i], patterns, options).length !== 1) { + return false; } + } + return true; +}; - if (tok.val !== '(' && tok.val !== '[') return; - var opts = utils.extend({}, options); - var brackets = []; - var parens = []; - var stack = []; - var val = tok.val; - var str = tok.str; - var i = tok.idx - 1; - - while (++i < str.length) { - var ch = str[i]; - - if (ch === '\\') { - val += (opts.keepEscaping === false ? '' : ch) + str[++i]; - continue; - } +/** + * Returns true if **any** of the given glob `patterns` + * match the specified `string`. + * + * ```js + * var mm = require('micromatch'); + * mm.any(string, patterns[, options]); + * + * console.log(mm.any('a.a', ['b.*', '*.a'])); + * //=> true + * console.log(mm.any('a.a', 'b.*')); + * //=> false + * ``` + * @param {String|Array} `str` The string to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ - if (ch === '(') { - parens.push(ch); - stack.push(ch); - } +micromatch.any = function(str, patterns, options) { + if (typeof str !== 'string') { + throw new TypeError('expected a string: "' + util.inspect(str) + '"'); + } - if (ch === '[') { - brackets.push(ch); - stack.push(ch); - } + if (isEmptyString(str) || isEmptyString(patterns)) { + return false; + } - if (ch === ')') { - parens.pop(); - stack.pop(); - if (!stack.length) { - val += ch; - break; - } - } + if (typeof patterns === 'string') { + patterns = [patterns]; + } - if (ch === ']') { - brackets.pop(); - stack.pop(); - if (!stack.length) { - val += ch; - break; - } - } - val += ch; + for (var i = 0; i < patterns.length; i++) { + if (micromatch.isMatch(str, patterns[i], options)) { + return true; } - - tok.split = false; - tok.val = val.slice(1); - tok.idx = i; - }; + } + return false; }; /** - * Returns true if the given string looks like a regex quantifier - * @return {Boolean} + * Returns true if **all** of the given `patterns` match + * the specified string. + * + * ```js + * var mm = require('micromatch'); + * mm.all(string, patterns[, options]); + * + * console.log(mm.all('foo.js', ['foo.js'])); + * // true + * + * console.log(mm.all('foo.js', ['*.js', '!foo.js'])); + * // false + * + * console.log(mm.all('foo.js', ['*.js', 'foo.js'])); + * // true + * + * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); + * // true + * ``` + * @param {String|Array} `str` The string to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public */ -utils.isQuantifier = function(str) { - return /^(?:[0-9]?,[0-9]|[0-9],)$/.test(str); +micromatch.all = function(str, patterns, options) { + if (typeof str !== 'string') { + throw new TypeError('expected a string: "' + util.inspect(str) + '"'); + } + if (typeof patterns === 'string') { + patterns = [patterns]; + } + for (var i = 0; i < patterns.length; i++) { + if (!micromatch.isMatch(str, patterns[i], options)) { + return false; + } + } + return true; }; /** - * Cast `val` to an array. - * @param {*} `val` + * Returns a list of strings that _**do not match any**_ of the given `patterns`. + * + * ```js + * var mm = require('micromatch'); + * mm.not(list, patterns[, options]); + * + * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); + * //=> ['b.b', 'c.c'] + * ``` + * @param {Array} `list` Array of strings to match. + * @param {String|Array} `patterns` One or more glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array} Returns an array of strings that **do not match** the given patterns. + * @api public */ -utils.stringifyArray = function(arr) { - return [utils.arrayify(arr).join('|')]; +micromatch.not = function(list, patterns, options) { + var opts = extend({}, options); + var ignore = opts.ignore; + delete opts.ignore; + + var unixify = utils.unixify(opts); + list = utils.arrayify(list).map(unixify); + + var matches = utils.diff(list, micromatch(list, patterns, opts)); + if (ignore) { + matches = utils.diff(matches, micromatch(list, ignore)); + } + + return opts.nodupes !== false ? utils.unique(matches) : matches; }; /** - * Cast `val` to an array. - * @param {*} `val` + * Returns true if the given `string` contains the given pattern. Similar + * to [.isMatch](#isMatch) but the pattern can match any part of the string. + * + * ```js + * var mm = require('micromatch'); + * mm.contains(string, pattern[, options]); + * + * console.log(mm.contains('aa/bb/cc', '*b')); + * //=> true + * console.log(mm.contains('aa/bb/cc', '*d')); + * //=> false + * ``` + * @param {String} `str` The string to match. + * @param {String|Array} `patterns` Glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if the patter matches any part of `str`. + * @api public */ -utils.arrayify = function(arr) { - if (typeof arr === 'undefined') { - return []; +micromatch.contains = function(str, patterns, options) { + if (typeof str !== 'string') { + throw new TypeError('expected a string: "' + util.inspect(str) + '"'); } - if (typeof arr === 'string') { - return [arr]; + + if (typeof patterns === 'string') { + if (isEmptyString(str) || isEmptyString(patterns)) { + return false; + } + + var equals = utils.equalsPattern(patterns, options); + if (equals(str)) { + return true; + } + var contains = utils.containsPattern(patterns, options); + if (contains(str)) { + return true; + } } - return arr; + + var opts = extend({}, options, {contains: true}); + return micromatch.any(str, patterns, opts); }; /** - * Returns true if the given `str` is a non-empty string + * Returns true if the given pattern and options should enable + * the `matchBase` option. * @return {Boolean} + * @api private */ -utils.isString = function(str) { - return str != null && typeof str === 'string'; +micromatch.matchBase = function(pattern, options) { + if (pattern && pattern.indexOf('/') !== -1 || !options) return false; + return options.basename === true || options.matchBase === true; }; /** - * Get the last element from `array` - * @param {Array} `array` - * @return {*} + * Filter the keys of the given object with the given `glob` pattern + * and `options`. Does not attempt to match nested keys. If you need this feature, + * use [glob-object][] instead. + * + * ```js + * var mm = require('micromatch'); + * mm.matchKeys(object, patterns[, options]); + * + * var obj = { aa: 'a', ab: 'b', ac: 'c' }; + * console.log(mm.matchKeys(obj, '*b')); + * //=> { ab: 'b' } + * ``` + * @param {Object} `object` The object with keys to filter. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Object} Returns an object with only keys that match the given patterns. + * @api public */ -utils.last = function(arr, n) { - return arr[arr.length - (n || 1)]; -}; - -utils.escapeRegex = function(str) { - return str.replace(/\\?([!^*?()[\]{}+?/])/g, '\\$1'); +micromatch.matchKeys = function(obj, patterns, options) { + if (!utils.isObject(obj)) { + throw new TypeError('expected the first argument to be an object'); + } + var keys = micromatch(Object.keys(obj), patterns, options); + return utils.pick(obj, keys); }; - -/***/ }), -/* 635 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/*! - * split-string +/** + * Returns a memoized matcher function from the given glob `pattern` and `options`. + * The returned function takes a string to match as its only argument and returns + * true if the string is a match. * - * Copyright (c) 2015-2017, Jon Schlinkert. - * Released under the MIT License. + * ```js + * var mm = require('micromatch'); + * mm.matcher(pattern[, options]); + * + * var isMatch = mm.matcher('*.!(*a)'); + * console.log(isMatch('a.a')); + * //=> false + * console.log(isMatch('a.b')); + * //=> true + * ``` + * @param {String} `pattern` Glob pattern + * @param {Object} `options` See available [options](#options) for changing how matches are performed. + * @return {Function} Returns a matcher function. + * @api public */ - - -var extend = __webpack_require__(636); - -module.exports = function(str, options, fn) { - if (typeof str !== 'string') { - throw new TypeError('expected a string'); +micromatch.matcher = function matcher(pattern, options) { + if (Array.isArray(pattern)) { + return compose(pattern, options, matcher); } - if (typeof options === 'function') { - fn = options; - options = null; + // if pattern is a regex + if (pattern instanceof RegExp) { + return test(pattern); } - // allow separator to be defined as a string - if (typeof options === 'string') { - options = { sep: options }; + // if pattern is invalid + if (!utils.isString(pattern)) { + throw new TypeError('expected pattern to be an array, string or regex'); } - var opts = extend({sep: '.'}, options); - var quotes = opts.quotes || ['"', "'", '`']; - var brackets; - - if (opts.brackets === true) { - brackets = { - '<': '>', - '(': ')', - '[': ']', - '{': '}' - }; - } else if (opts.brackets) { - brackets = opts.brackets; + // if pattern is a non-glob string + if (!utils.hasSpecialChars(pattern)) { + if (options && options.nocase === true) { + pattern = pattern.toLowerCase(); + } + return utils.matchPath(pattern, options); } - var tokens = []; - var stack = []; - var arr = ['']; - var sep = opts.sep; - var len = str.length; - var idx = -1; - var closeIdx; + // if pattern is a glob string + var re = micromatch.makeRe(pattern, options); - function expected() { - if (brackets && stack.length) { - return brackets[stack[stack.length - 1]]; - } + // if `options.matchBase` or `options.basename` is defined + if (micromatch.matchBase(pattern, options)) { + return utils.matchBasename(re, options); } - while (++idx < len) { - var ch = str[idx]; - var next = str[idx + 1]; - var tok = { val: ch, idx: idx, arr: arr, str: str }; - tokens.push(tok); + function test(regex) { + var equals = utils.equalsPattern(options); + var unixify = utils.unixify(options); - if (ch === '\\') { - tok.val = keepEscaping(opts, str, idx) === true ? (ch + next) : next; - tok.escaped = true; - if (typeof fn === 'function') { - fn(tok); + return function(str) { + if (equals(str)) { + return true; } - arr[arr.length - 1] += tok.val; - idx++; - continue; - } - - if (brackets && brackets[ch]) { - stack.push(ch); - var e = expected(); - var i = idx + 1; - - if (str.indexOf(e, i + 1) !== -1) { - while (stack.length && i < len) { - var s = str[++i]; - if (s === '\\') { - s++; - continue; - } - - if (quotes.indexOf(s) !== -1) { - i = getClosingQuote(str, s, i + 1); - continue; - } - e = expected(); - if (stack.length && str.indexOf(e, i + 1) === -1) { - break; - } - - if (brackets[s]) { - stack.push(s); - continue; - } - - if (e === s) { - stack.pop(); - } - } + if (regex.test(unixify(str))) { + return true; } + return false; + }; + } - closeIdx = i; - if (closeIdx === -1) { - arr[arr.length - 1] += ch; - continue; - } + var fn = test(re); + Object.defineProperty(fn, 'result', { + configurable: true, + enumerable: false, + value: re.result + }); + return fn; +}; - ch = str.slice(idx, closeIdx + 1); - tok.val = ch; - tok.idx = idx = closeIdx; - } +/** + * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match. + * + * ```js + * var mm = require('micromatch'); + * mm.capture(pattern, string[, options]); + * + * console.log(mm.capture('test/*.js', 'test/foo.js')); + * //=> ['foo'] + * console.log(mm.capture('test/*.js', 'foo/bar.css')); + * //=> null + * ``` + * @param {String} `pattern` Glob pattern to use for matching. + * @param {String} `string` String to match + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns an array of captures if the string matches the glob pattern, otherwise `null`. + * @api public + */ - if (quotes.indexOf(ch) !== -1) { - closeIdx = getClosingQuote(str, ch, idx + 1); - if (closeIdx === -1) { - arr[arr.length - 1] += ch; - continue; - } +micromatch.capture = function(pattern, str, options) { + var re = micromatch.makeRe(pattern, extend({capture: true}, options)); + var unixify = utils.unixify(options); - if (keepQuotes(ch, opts) === true) { - ch = str.slice(idx, closeIdx + 1); - } else { - ch = str.slice(idx + 1, closeIdx); + function match() { + return function(string) { + var match = re.exec(unixify(string)); + if (!match) { + return null; } - tok.val = ch; - tok.idx = idx = closeIdx; - } - - if (typeof fn === 'function') { - fn(tok, tokens); - ch = tok.val; - idx = tok.idx; - } - - if (tok.val === sep && tok.split !== false) { - arr.push(''); - continue; - } - - arr[arr.length - 1] += tok.val; + return match.slice(1); + }; } - return arr; + var capture = memoize('capture', pattern, options, match); + return capture(str); }; -function getClosingQuote(str, ch, i, brackets) { - var idx = str.indexOf(ch, i); - if (str.charAt(idx - 1) === '\\') { - return getClosingQuote(str, ch, idx + 1); - } - return idx; -} - -function keepQuotes(ch, opts) { - if (opts.keepDoubleQuotes === true && ch === '"') return true; - if (opts.keepSingleQuotes === true && ch === "'") return true; - return opts.keepQuotes; -} +/** + * Create a regular expression from the given glob `pattern`. + * + * ```js + * var mm = require('micromatch'); + * mm.makeRe(pattern[, options]); + * + * console.log(mm.makeRe('*.js')); + * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ + * ``` + * @param {String} `pattern` A glob pattern to convert to regex. + * @param {Object} `options` See available [options](#options) for changing how matches are performed. + * @return {RegExp} Returns a regex created from the given pattern. + * @api public + */ -function keepEscaping(opts, str, idx) { - if (typeof opts.keepEscaping === 'function') { - return opts.keepEscaping(str, idx); +micromatch.makeRe = function(pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected pattern to be a string'); } - return opts.keepEscaping === true || str[idx + 1] === '\\'; -} + if (pattern.length > MAX_LENGTH) { + throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters'); + } -/***/ }), -/* 636 */ -/***/ (function(module, exports, __webpack_require__) { + function makeRe() { + var result = micromatch.create(pattern, options); + var ast_array = []; + var output = result.map(function(obj) { + obj.ast.state = obj.state; + ast_array.push(obj.ast); + return obj.output; + }); -"use strict"; + var regex = toRegex(output.join('|'), options); + Object.defineProperty(regex, 'result', { + configurable: true, + enumerable: false, + value: ast_array + }); + return regex; + } + return memoize('makeRe', pattern, options, makeRe); +}; -var isExtendable = __webpack_require__(637); -var assignSymbols = __webpack_require__(626); +/** + * Expand the given brace `pattern`. + * + * ```js + * var mm = require('micromatch'); + * console.log(mm.braces('foo/{a,b}/bar')); + * //=> ['foo/(a|b)/bar'] + * + * console.log(mm.braces('foo/{a,b}/bar', {expand: true})); + * //=> ['foo/(a|b)/bar'] + * ``` + * @param {String} `pattern` String with brace pattern to expand. + * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options. + * @return {Array} + * @api public + */ -module.exports = Object.assign || function(obj/*, objects*/) { - if (obj === null || typeof obj === 'undefined') { - throw new TypeError('Cannot convert undefined or null to object'); - } - if (!isObject(obj)) { - obj = {}; - } - for (var i = 1; i < arguments.length; i++) { - var val = arguments[i]; - if (isString(val)) { - val = toObject(val); - } - if (isObject(val)) { - assign(obj, val); - assignSymbols(obj, val); - } - } - return obj; -}; +micromatch.braces = function(pattern, options) { + if (typeof pattern !== 'string' && !Array.isArray(pattern)) { + throw new TypeError('expected pattern to be an array or string'); + } -function assign(a, b) { - for (var key in b) { - if (hasOwn(b, key)) { - a[key] = b[key]; + function expand() { + if (options && options.nobrace === true || !/\{.*\}/.test(pattern)) { + return utils.arrayify(pattern); } + return braces(pattern, options); } -} -function isString(val) { - return (val && typeof val === 'string'); -} + return memoize('braces', pattern, options, expand); +}; -function toObject(str) { - var obj = {}; - for (var i in str) { - obj[i] = str[i]; - } - return obj; -} +/** + * Proxy to the [micromatch.braces](#method), for parity with + * minimatch. + */ -function isObject(val) { - return (val && typeof val === 'object') || isExtendable(val); -} +micromatch.braceExpand = function(pattern, options) { + var opts = extend({}, options, {expand: true}); + return micromatch.braces(pattern, opts); +}; /** - * Returns true if the given `key` is an own property of `obj`. + * Parses the given glob `pattern` and returns an array of abstract syntax + * trees (ASTs), with the compiled `output` and optional source `map` on + * each AST. + * + * ```js + * var mm = require('micromatch'); + * mm.create(pattern[, options]); + * + * console.log(mm.create('abc/*.js')); + * // [{ options: { source: 'string', sourcemap: true }, + * // state: {}, + * // compilers: + * // { ... }, + * // output: '(\\.[\\\\\\/])?abc\\/(?!\\.)(?=.)[^\\/]*?\\.js', + * // ast: + * // { type: 'root', + * // errors: [], + * // nodes: + * // [ ... ], + * // dot: false, + * // input: 'abc/*.js' }, + * // parsingErrors: [], + * // map: + * // { version: 3, + * // sources: [ 'string' ], + * // names: [], + * // mappings: 'AAAA,GAAG,EAAC,kBAAC,EAAC,EAAE', + * // sourcesContent: [ 'abc/*.js' ] }, + * // position: { line: 1, column: 28 }, + * // content: {}, + * // files: {}, + * // idx: 6 }] + * ``` + * @param {String} `pattern` Glob pattern to parse and compile. + * @param {Object} `options` Any [options](#options) to change how parsing and compiling is performed. + * @return {Object} Returns an object with the parsed AST, compiled string and optional source map. + * @api public */ -function hasOwn(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -} - -function isEnum(obj, key) { - return Object.prototype.propertyIsEnumerable.call(obj, key); -} +micromatch.create = function(pattern, options) { + return memoize('create', pattern, options, function() { + function create(str, opts) { + return micromatch.compile(micromatch.parse(str, opts), opts); + } + pattern = micromatch.braces(pattern, options); + var len = pattern.length; + var idx = -1; + var res = []; -/***/ }), -/* 637 */ -/***/ (function(module, exports, __webpack_require__) { + while (++idx < len) { + res.push(create(pattern[idx], options)); + } + return res; + }); +}; -"use strict"; -/*! - * is-extendable +/** + * Parse the given `str` with the given `options`. * - * Copyright (c) 2015-2017, Jon Schlinkert. - * Released under the MIT License. + * ```js + * var mm = require('micromatch'); + * mm.parse(pattern[, options]); + * + * var ast = mm.parse('a/{b,c}/d'); + * console.log(ast); + * // { type: 'root', + * // errors: [], + * // input: 'a/{b,c}/d', + * // nodes: + * // [ { type: 'bos', val: '' }, + * // { type: 'text', val: 'a/' }, + * // { type: 'brace', + * // nodes: + * // [ { type: 'brace.open', val: '{' }, + * // { type: 'text', val: 'b,c' }, + * // { type: 'brace.close', val: '}' } ] }, + * // { type: 'text', val: '/d' }, + * // { type: 'eos', val: '' } ] } + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {Object} Returns an AST + * @api public */ +micromatch.parse = function(pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected a string'); + } + function parse() { + var snapdragon = utils.instantiate(null, options); + parsers(snapdragon, options); -var isPlainObject = __webpack_require__(625); + var ast = snapdragon.parse(pattern, options); + utils.define(ast, 'snapdragon', snapdragon); + ast.input = pattern; + return ast; + } -module.exports = function isExtendable(val) { - return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); + return memoize('parse', pattern, options, parse); }; - -/***/ }), -/* 638 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/*! - * arr-flatten +/** + * Compile the given `ast` or string with the given `options`. * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. + * ```js + * var mm = require('micromatch'); + * mm.compile(ast[, options]); + * + * var ast = mm.parse('a/{b,c}/d'); + * console.log(mm.compile(ast)); + * // { options: { source: 'string' }, + * // state: {}, + * // compilers: + * // { eos: [Function], + * // noop: [Function], + * // bos: [Function], + * // brace: [Function], + * // 'brace.open': [Function], + * // text: [Function], + * // 'brace.close': [Function] }, + * // output: [ 'a/(b|c)/d' ], + * // ast: + * // { ... }, + * // parsingErrors: [] } + * ``` + * @param {Object|String} `ast` + * @param {Object} `options` + * @return {Object} Returns an object that has an `output` property with the compiled string. + * @api public */ +micromatch.compile = function(ast, options) { + if (typeof ast === 'string') { + ast = micromatch.parse(ast, options); + } - -module.exports = function (arr) { - return flat(arr, []); + return memoize('compile', ast.input, options, function() { + var snapdragon = utils.instantiate(ast, options); + compilers(snapdragon, options); + return snapdragon.compile(ast, options); + }); }; -function flat(arr, res) { - var i = 0, cur; - var len = arr.length; - for (; i < len; i++) { - cur = arr[i]; - Array.isArray(cur) ? flat(cur, res) : res.push(cur); - } - return res; -} +/** + * Clear the regex cache. + * + * ```js + * mm.clearCache(); + * ``` + * @api public + */ +micromatch.clearCache = function() { + micromatch.cache.caches = {}; +}; -/***/ }), -/* 639 */ -/***/ (function(module, exports, __webpack_require__) { +/** + * Returns true if the given value is effectively an empty string + */ -"use strict"; -/*! - * fill-range - * - * Copyright (c) 2014-2015, 2017, Jon Schlinkert. - * Released under the MIT License. +function isEmptyString(val) { + return String(val) === '' || String(val) === './'; +} + +/** + * Compose a matcher function with the given patterns. + * This allows matcher functions to be compiled once and + * called multiple times. */ +function compose(patterns, options, matcher) { + var matchers; + return memoize('compose', String(patterns), options, function() { + return function(file) { + // delay composition until it's invoked the first time, + // after that it won't be called again + if (!matchers) { + matchers = []; + for (var i = 0; i < patterns.length; i++) { + matchers.push(matcher(patterns[i], options)); + } + } -var util = __webpack_require__(234); -var isNumber = __webpack_require__(640); -var extend = __webpack_require__(643); -var repeat = __webpack_require__(645); -var toRegex = __webpack_require__(646); + var len = matchers.length; + while (len--) { + if (matchers[len](file) === true) { + return true; + } + } + return false; + }; + }); +} /** - * Return a range of numbers or letters. - * - * @param {String} `start` Start of the range - * @param {String} `stop` End of the range - * @param {String} `step` Increment or decrement to use. - * @param {Function} `fn` Custom function to modify each element in the range. - * @return {Array} + * Memoize a generated regex or function. A unique key is generated + * from the `type` (usually method name), the `pattern`, and + * user-defined options. */ -function fillRange(start, stop, step, options) { - if (typeof start === 'undefined') { - return []; - } +function memoize(type, pattern, options, fn) { + var key = utils.createKey(type + '=' + pattern, options); - if (typeof stop === 'undefined' || start === stop) { - // special case, for handling negative zero - var isString = typeof start === 'string'; - if (isNumber(start) && !toNumber(start)) { - return [isString ? '0' : 0]; - } - return [start]; + if (options && options.cache === false) { + return fn(pattern, options); } - if (typeof step !== 'number' && typeof step !== 'string') { - options = step; - step = undefined; + if (cache.has(type, key)) { + return cache.get(type, key); } - if (typeof options === 'function') { - options = { transform: options }; - } + var val = fn(pattern, options); + cache.set(type, key, val); + return val; +} - var opts = extend({step: step}, options); - if (opts.step && !isValidNumber(opts.step)) { - if (opts.strictRanges === true) { - throw new TypeError('expected options.step to be a number'); - } - return []; - } +/** + * Expose compiler, parser and cache on `micromatch` + */ - opts.isNumber = isValidNumber(start) && isValidNumber(stop); - if (!opts.isNumber && !isValid(start, stop)) { - if (opts.strictRanges === true) { - throw new RangeError('invalid range arguments: ' + util.inspect([start, stop])); - } - return []; - } +micromatch.compilers = compilers; +micromatch.parsers = parsers; +micromatch.caches = cache.caches; - opts.isPadded = isPadded(start) || isPadded(stop); - opts.toString = opts.stringify - || typeof opts.step === 'string' - || typeof start === 'string' - || typeof stop === 'string' - || !opts.isNumber; +/** + * Expose `micromatch` + * @type {Function} + */ - if (opts.isPadded) { - opts.maxLength = Math.max(String(start).length, String(stop).length); - } +module.exports = micromatch; - // support legacy minimatch/fill-range options - if (typeof opts.optimize === 'boolean') opts.toRegex = opts.optimize; - if (typeof opts.makeRe === 'boolean') opts.toRegex = opts.makeRe; - return expand(start, stop, opts); -} -function expand(start, stop, options) { - var a = options.isNumber ? toNumber(start) : start.charCodeAt(0); - var b = options.isNumber ? toNumber(stop) : stop.charCodeAt(0); +/***/ }), +/* 647 */ +/***/ (function(module, exports, __webpack_require__) { - var step = Math.abs(toNumber(options.step)) || 1; - if (options.toRegex && step === 1) { - return toRange(a, b, start, stop, options); - } +"use strict"; - var zero = {greater: [], lesser: []}; - var asc = a < b; - var arr = new Array(Math.round((asc ? b - a : a - b) / step)); - var idx = 0; - while (asc ? a <= b : a >= b) { - var val = options.isNumber ? a : String.fromCharCode(a); - if (options.toRegex && (val >= 0 || !options.isNumber)) { - zero.greater.push(val); - } else { - zero.lesser.push(Math.abs(val)); - } +/** + * Module dependencies + */ - if (options.isPadded) { - val = zeros(val, options); - } +var toRegex = __webpack_require__(648); +var unique = __webpack_require__(668); +var extend = __webpack_require__(669); - if (options.toString) { - val = String(val); - } +/** + * Local dependencies + */ - if (typeof options.transform === 'function') { - arr[idx++] = options.transform(val, a, b, step, idx, arr, options); - } else { - arr[idx++] = val; - } +var compilers = __webpack_require__(671); +var parsers = __webpack_require__(686); +var Braces = __webpack_require__(691); +var utils = __webpack_require__(672); +var MAX_LENGTH = 1024 * 64; +var cache = {}; - if (asc) { - a += step; - } else { - a -= step; - } - } +/** + * Convert the given `braces` pattern into a regex-compatible string. By default, only one string is generated for every input string. Set `options.expand` to true to return an array of patterns (similar to Bash or minimatch. Before using `options.expand`, it's recommended that you read the [performance notes](#performance)). + * + * ```js + * var braces = require('braces'); + * console.log(braces('{a,b,c}')); + * //=> ['(a|b|c)'] + * + * console.log(braces('{a,b,c}', {expand: true})); + * //=> ['a', 'b', 'c'] + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {String} + * @api public + */ - if (options.toRegex === true) { - return toSequence(arr, zero, options); - } - return arr; -} +function braces(pattern, options) { + var key = utils.createKey(String(pattern), options); + var arr = []; -function toRange(a, b, start, stop, options) { - if (options.isPadded) { - return toRegex(start, stop, options); + var disabled = options && options.cache === false; + if (!disabled && cache.hasOwnProperty(key)) { + return cache[key]; } - if (options.isNumber) { - return toRegex(Math.min(a, b), Math.max(a, b), options); + if (Array.isArray(pattern)) { + for (var i = 0; i < pattern.length; i++) { + arr.push.apply(arr, braces.create(pattern[i], options)); + } + } else { + arr = braces.create(pattern, options); } - var start = String.fromCharCode(Math.min(a, b)); - var stop = String.fromCharCode(Math.max(a, b)); - return '[' + start + '-' + stop + ']'; -} - -function toSequence(arr, zeros, options) { - var greater = '', lesser = ''; - if (zeros.greater.length) { - greater = zeros.greater.join('|'); - } - if (zeros.lesser.length) { - lesser = '-(' + zeros.lesser.join('|') + ')'; + if (options && options.nodupes === true) { + arr = unique(arr); } - var res = greater && lesser - ? greater + '|' + lesser - : greater || lesser; - if (options.capture) { - return '(' + res + ')'; + if (!disabled) { + cache[key] = arr; } - return res; + return arr; } -function zeros(val, options) { - if (options.isPadded) { - var str = String(val); - var len = str.length; - var dash = ''; - if (str.charAt(0) === '-') { - dash = '-'; - str = str.slice(1); - } - var diff = options.maxLength - len; - var pad = repeat('0', diff); - val = (dash + pad + str); - } - if (options.stringify) { - return String(val); - } - return val; -} +/** + * Expands a brace pattern into an array. This method is called by the main [braces](#braces) function when `options.expand` is true. Before using this method it's recommended that you read the [performance notes](#performance)) and advantages of using [.optimize](#optimize) instead. + * + * ```js + * var braces = require('braces'); + * console.log(braces.expand('a/{b,c}/d')); + * //=> ['a/b/d', 'a/c/d']; + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ -function toNumber(val) { - return Number(val) || 0; -} +braces.expand = function(pattern, options) { + return braces.create(pattern, extend({}, options, {expand: true})); +}; -function isPadded(str) { - return /^-?0\d/.test(str); -} +/** + * Expands a brace pattern into a regex-compatible, optimized string. This method is called by the main [braces](#braces) function by default. + * + * ```js + * var braces = require('braces'); + * console.log(braces.expand('a/{b,c}/d')); + * //=> ['a/(b|c)/d'] + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ -function isValid(min, max) { - return (isValidNumber(min) || isValidLetter(min)) - && (isValidNumber(max) || isValidLetter(max)); -} +braces.optimize = function(pattern, options) { + return braces.create(pattern, options); +}; -function isValidLetter(ch) { - return typeof ch === 'string' && ch.length === 1 && /^\w+$/.test(ch); -} +/** + * Processes a brace pattern and returns either an expanded array (if `options.expand` is true), a highly optimized regex-compatible string. This method is called by the main [braces](#braces) function. + * + * ```js + * var braces = require('braces'); + * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}')) + * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)' + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ -function isValidNumber(n) { - return isNumber(n) && !/\./.test(n); -} +braces.create = function(pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected a string'); + } -/** - * Expose `fillRange` - * @type {Function} - */ + var maxLength = (options && options.maxLength) || MAX_LENGTH; + if (pattern.length >= maxLength) { + throw new Error('expected pattern to be less than ' + maxLength + ' characters'); + } -module.exports = fillRange; + function create() { + if (pattern === '' || pattern.length < 3) { + return [pattern]; + } + if (utils.isEmptySets(pattern)) { + return []; + } -/***/ }), -/* 640 */ -/***/ (function(module, exports, __webpack_require__) { + if (utils.isQuotedString(pattern)) { + return [pattern.slice(1, -1)]; + } -"use strict"; -/*! - * is-number - * - * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT License. - */ + var proto = new Braces(options); + var result = !options || options.expand !== true + ? proto.optimize(pattern, options) + : proto.expand(pattern, options); + // get the generated pattern(s) + var arr = result.output; + // filter out empty strings if specified + if (options && options.noempty === true) { + arr = arr.filter(Boolean); + } -var typeOf = __webpack_require__(641); + // filter out duplicates if specified + if (options && options.nodupes === true) { + arr = unique(arr); + } -module.exports = function isNumber(num) { - var type = typeOf(num); + Object.defineProperty(arr, 'result', { + enumerable: false, + value: result + }); - if (type === 'string') { - if (!num.trim()) return false; - } else if (type !== 'number') { - return false; + return arr; } - return (num - num + 1) >= 0; + return memoize('create', pattern, options, create); }; - -/***/ }), -/* 641 */ -/***/ (function(module, exports, __webpack_require__) { - -var isBuffer = __webpack_require__(642); -var toString = Object.prototype.toString; - /** - * Get the native `typeof` a value. + * Create a regular expression from the given string `pattern`. * - * @param {*} `val` - * @return {*} Native javascript type + * ```js + * var braces = require('braces'); + * + * console.log(braces.makeRe('id-{200..300}')); + * //=> /^(?:id-(20[0-9]|2[1-9][0-9]|300))$/ + * ``` + * @param {String} `pattern` The pattern to convert to regex. + * @param {Object} `options` + * @return {RegExp} + * @api public */ -module.exports = function kindOf(val) { - // primitivies - if (typeof val === 'undefined') { - return 'undefined'; - } - if (val === null) { - return 'null'; - } - if (val === true || val === false || val instanceof Boolean) { - return 'boolean'; - } - if (typeof val === 'string' || val instanceof String) { - return 'string'; - } - if (typeof val === 'number' || val instanceof Number) { - return 'number'; +braces.makeRe = function(pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected a string'); } - // functions - if (typeof val === 'function' || val instanceof Function) { - return 'function'; + var maxLength = (options && options.maxLength) || MAX_LENGTH; + if (pattern.length >= maxLength) { + throw new Error('expected pattern to be less than ' + maxLength + ' characters'); } - // array - if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { - return 'array'; + function makeRe() { + var arr = braces(pattern, options); + var opts = extend({strictErrors: false}, options); + return toRegex(arr, opts); } - // check for instances of RegExp and Date before calling `toString` - if (val instanceof RegExp) { - return 'regexp'; - } - if (val instanceof Date) { - return 'date'; - } + return memoize('makeRe', pattern, options, makeRe); +}; - // other objects - var type = toString.call(val); +/** + * Parse the given `str` with the given `options`. + * + * ```js + * var braces = require('braces'); + * var ast = braces.parse('a/{b,c}/d'); + * console.log(ast); + * // { type: 'root', + * // errors: [], + * // input: 'a/{b,c}/d', + * // nodes: + * // [ { type: 'bos', val: '' }, + * // { type: 'text', val: 'a/' }, + * // { type: 'brace', + * // nodes: + * // [ { type: 'brace.open', val: '{' }, + * // { type: 'text', val: 'b,c' }, + * // { type: 'brace.close', val: '}' } ] }, + * // { type: 'text', val: '/d' }, + * // { type: 'eos', val: '' } ] } + * ``` + * @param {String} `pattern` Brace pattern to parse + * @param {Object} `options` + * @return {Object} Returns an AST + * @api public + */ - if (type === '[object RegExp]') { - return 'regexp'; - } - if (type === '[object Date]') { - return 'date'; - } - if (type === '[object Arguments]') { - return 'arguments'; - } - if (type === '[object Error]') { - return 'error'; - } +braces.parse = function(pattern, options) { + var proto = new Braces(options); + return proto.parse(pattern, options); +}; - // buffer - if (isBuffer(val)) { - return 'buffer'; - } +/** + * Compile the given `ast` or string with the given `options`. + * + * ```js + * var braces = require('braces'); + * var ast = braces.parse('a/{b,c}/d'); + * console.log(braces.compile(ast)); + * // { options: { source: 'string' }, + * // state: {}, + * // compilers: + * // { eos: [Function], + * // noop: [Function], + * // bos: [Function], + * // brace: [Function], + * // 'brace.open': [Function], + * // text: [Function], + * // 'brace.close': [Function] }, + * // output: [ 'a/(b|c)/d' ], + * // ast: + * // { ... }, + * // parsingErrors: [] } + * ``` + * @param {Object|String} `ast` AST from [.parse](#parse). If a string is passed it will be parsed first. + * @param {Object} `options` + * @return {Object} Returns an object that has an `output` property with the compiled string. + * @api public + */ - // es6: Map, WeakMap, Set, WeakSet - if (type === '[object Set]') { - return 'set'; - } - if (type === '[object WeakSet]') { - return 'weakset'; - } - if (type === '[object Map]') { - return 'map'; - } - if (type === '[object WeakMap]') { - return 'weakmap'; - } - if (type === '[object Symbol]') { - return 'symbol'; - } +braces.compile = function(ast, options) { + var proto = new Braces(options); + return proto.compile(ast, options); +}; - // typed arrays - if (type === '[object Int8Array]') { - return 'int8array'; - } - if (type === '[object Uint8Array]') { - return 'uint8array'; - } - if (type === '[object Uint8ClampedArray]') { - return 'uint8clampedarray'; - } - if (type === '[object Int16Array]') { - return 'int16array'; - } - if (type === '[object Uint16Array]') { - return 'uint16array'; - } - if (type === '[object Int32Array]') { - return 'int32array'; - } - if (type === '[object Uint32Array]') { - return 'uint32array'; - } - if (type === '[object Float32Array]') { - return 'float32array'; - } - if (type === '[object Float64Array]') { - return 'float64array'; - } +/** + * Clear the regex cache. + * + * ```js + * braces.clearCache(); + * ``` + * @api public + */ - // must be a plain object - return 'object'; +braces.clearCache = function() { + cache = braces.cache = {}; }; +/** + * Memoize a generated regex or function. A unique key is generated + * from the method name, pattern, and user-defined options. Set + * options.memoize to false to disable. + */ -/***/ }), -/* 642 */ -/***/ (function(module, exports) { +function memoize(type, pattern, options, fn) { + var key = utils.createKey(type + ':' + pattern, options); + var disabled = options && options.cache === false; + if (disabled) { + braces.clearCache(); + return fn(pattern, options); + } -/*! - * Determine if an object is a Buffer - * - * @author Feross Aboukhadijeh - * @license MIT - */ + if (cache.hasOwnProperty(key)) { + return cache[key]; + } -// The _isBuffer check is for Safari 5-7 support, because it's missing -// Object.prototype.constructor. Remove this eventually -module.exports = function (obj) { - return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) + var res = fn(pattern, options); + cache[key] = res; + return res; } -function isBuffer (obj) { - return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) -} +/** + * Expose `Braces` constructor and methods + * @type {Function} + */ -// For Node v0.10 support. Remove this eventually. -function isSlowBuffer (obj) { - return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) -} +braces.Braces = Braces; +braces.compilers = compilers; +braces.parsers = parsers; +braces.cache = cache; + +/** + * Expose `braces` + * @type {Function} + */ + +module.exports = braces; /***/ }), -/* 643 */ +/* 648 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var isObject = __webpack_require__(644); +var safe = __webpack_require__(649); +var define = __webpack_require__(655); +var extend = __webpack_require__(661); +var not = __webpack_require__(665); +var MAX_LENGTH = 1024 * 64; -module.exports = function extend(o/*, objects*/) { - if (!isObject(o)) { o = {}; } +/** + * Session cache + */ - var len = arguments.length; - for (var i = 1; i < len; i++) { - var obj = arguments[i]; +var cache = {}; - if (isObject(obj)) { - assign(o, obj); - } - } - return o; -}; +/** + * Create a regular expression from the given `pattern` string. + * + * @param {String|RegExp} `pattern` Pattern can be a string or regular expression. + * @param {Object} `options` + * @return {RegExp} + * @api public + */ -function assign(a, b) { - for (var key in b) { - if (hasOwn(b, key)) { - a[key] = b[key]; - } +module.exports = function(patterns, options) { + if (!Array.isArray(patterns)) { + return makeRe(patterns, options); } -} + return makeRe(patterns.join('|'), options); +}; /** - * Returns true if the given `key` is an own property of `obj`. + * Create a regular expression from the given `pattern` string. + * + * @param {String|RegExp} `pattern` Pattern can be a string or regular expression. + * @param {Object} `options` + * @return {RegExp} + * @api public */ -function hasOwn(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -} +function makeRe(pattern, options) { + if (pattern instanceof RegExp) { + return pattern; + } + if (typeof pattern !== 'string') { + throw new TypeError('expected a string'); + } -/***/ }), -/* 644 */ -/***/ (function(module, exports, __webpack_require__) { + if (pattern.length > MAX_LENGTH) { + throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters'); + } -"use strict"; -/*! - * is-extendable - * - * Copyright (c) 2015, Jon Schlinkert. - * Licensed under the MIT License. - */ + var key = pattern; + // do this before shallow cloning options, it's a lot faster + if (!options || (options && options.cache !== false)) { + key = createKey(pattern, options); + if (cache.hasOwnProperty(key)) { + return cache[key]; + } + } + var opts = extend({}, options); + if (opts.contains === true) { + if (opts.negate === true) { + opts.strictNegate = false; + } else { + opts.strict = false; + } + } -module.exports = function isExtendable(val) { - return typeof val !== 'undefined' && val !== null - && (typeof val === 'object' || typeof val === 'function'); -}; + if (opts.strict === false) { + opts.strictOpen = false; + opts.strictClose = false; + } + var open = opts.strictOpen !== false ? '^' : ''; + var close = opts.strictClose !== false ? '$' : ''; + var flags = opts.flags || ''; + var regex; -/***/ }), -/* 645 */ -/***/ (function(module, exports, __webpack_require__) { + if (opts.nocase === true && !/i/.test(flags)) { + flags += 'i'; + } -"use strict"; -/*! - * repeat-string - * - * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT License. - */ + try { + if (opts.negate || typeof opts.strictNegate === 'boolean') { + pattern = not.create(pattern, opts); + } + var str = open + '(?:' + pattern + ')' + close; + regex = new RegExp(str, flags); + if (opts.safe === true && safe(regex) === false) { + throw new Error('potentially unsafe regular expression: ' + regex.source); + } -/** - * Results cache - */ + } catch (err) { + if (opts.strictErrors === true || opts.safe === true) { + err.key = key; + err.pattern = pattern; + err.originalOptions = options; + err.createdOptions = opts; + throw err; + } -var res = ''; -var cache; + try { + regex = new RegExp('^' + pattern.replace(/(\W)/g, '\\$1') + '$'); + } catch (err) { + regex = /.^/; //<= match nothing + } + } + + if (opts.cache !== false) { + memoize(regex, key, pattern, opts); + } + return regex; +} /** - * Expose `repeat` + * Memoize generated regex. This can result in dramatic speed improvements + * and simplify debugging by adding options and pattern to the regex. It can be + * disabled by passing setting `options.cache` to false. */ -module.exports = repeat; +function memoize(regex, key, pattern, options) { + define(regex, 'cached', true); + define(regex, 'pattern', pattern); + define(regex, 'options', options); + define(regex, 'key', key); + cache[key] = regex; +} /** - * Repeat the given `string` the specified `number` - * of times. - * - * **Example:** - * - * ```js - * var repeat = require('repeat-string'); - * repeat('A', 5); - * //=> AAAAA - * ``` - * - * @param {String} `string` The string to repeat - * @param {Number} `number` The number of times to repeat the string - * @return {String} Repeated string - * @api public + * Create the key to use for memoization. The key is generated + * by iterating over the options and concatenating key-value pairs + * to the pattern string. */ -function repeat(str, num) { - if (typeof str !== 'string') { - throw new TypeError('expected a string'); - } - - // cover common, quick use cases - if (num === 1) return str; - if (num === 2) return str + str; - - var max = str.length * num; - if (cache !== str || typeof cache === 'undefined') { - cache = str; - res = ''; - } else if (res.length >= max) { - return res.substr(0, max); - } - - while (max > res.length && num > 1) { - if (num & 1) { - res += str; +function createKey(pattern, options) { + if (!options) return pattern; + var key = pattern; + for (var prop in options) { + if (options.hasOwnProperty(prop)) { + key += ';' + prop + '=' + String(options[prop]); } - - num >>= 1; - str += str; } - - res += str; - res = res.substr(0, max); - return res; + return key; } - -/***/ }), -/* 646 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/*! - * to-regex-range - * - * Copyright (c) 2015, 2017, Jon Schlinkert. - * Released under the MIT License. +/** + * Expose `makeRe` */ +module.exports.makeRe = makeRe; -var repeat = __webpack_require__(645); -var isNumber = __webpack_require__(640); -var cache = {}; +/***/ }), +/* 649 */ +/***/ (function(module, exports, __webpack_require__) { -function toRegexRange(min, max, options) { - if (isNumber(min) === false) { - throw new RangeError('toRegexRange: first argument is invalid.'); - } +var parse = __webpack_require__(650); +var types = parse.types; - if (typeof max === 'undefined' || min === max) { - return String(min); - } +module.exports = function (re, opts) { + if (!opts) opts = {}; + var replimit = opts.limit === undefined ? 25 : opts.limit; + + if (isRegExp(re)) re = re.source; + else if (typeof re !== 'string') re = String(re); + + try { re = parse(re) } + catch (err) { return false } + + var reps = 0; + return (function walk (node, starHeight) { + if (node.type === types.REPETITION) { + starHeight ++; + reps ++; + if (starHeight > 1) return false; + if (reps > replimit) return false; + } + + if (node.options) { + for (var i = 0, len = node.options.length; i < len; i++) { + var ok = walk({ stack: node.options[i] }, starHeight); + if (!ok) return false; + } + } + var stack = node.stack || (node.value && node.value.stack); + if (!stack) return true; + + for (var i = 0; i < stack.length; i++) { + var ok = walk(stack[i], starHeight); + if (!ok) return false; + } + + return true; + })(re, 0); +}; - if (isNumber(max) === false) { - throw new RangeError('toRegexRange: second argument is invalid.'); - } +function isRegExp (x) { + return {}.toString.call(x) === '[object RegExp]'; +} - options = options || {}; - var relax = String(options.relaxZeros); - var shorthand = String(options.shorthand); - var capture = String(options.capture); - var key = min + ':' + max + '=' + relax + shorthand + capture; - if (cache.hasOwnProperty(key)) { - return cache[key].result; - } - var a = Math.min(min, max); - var b = Math.max(min, max); +/***/ }), +/* 650 */ +/***/ (function(module, exports, __webpack_require__) { - if (Math.abs(a - b) === 1) { - var result = min + '|' + max; - if (options.capture) { - return '(' + result + ')'; - } - return result; - } +var util = __webpack_require__(651); +var types = __webpack_require__(652); +var sets = __webpack_require__(653); +var positions = __webpack_require__(654); - var isPadded = padding(min) || padding(max); - var positives = []; - var negatives = []; - var tok = {min: min, max: max, a: a, b: b}; - if (isPadded) { - tok.isPadded = isPadded; - tok.maxLen = String(tok.max).length; - } +module.exports = function(regexpStr) { + var i = 0, l, c, + start = { type: types.ROOT, stack: []}, - if (a < 0) { - var newMin = b < 0 ? Math.abs(b) : 1; - var newMax = Math.abs(a); - negatives = splitToPatterns(newMin, newMax, tok, options); - a = tok.a = 0; - } + // Keep track of last clause/group and stack. + lastGroup = start, + last = start.stack, + groupStack = []; - if (b >= 0) { - positives = splitToPatterns(a, b, tok, options); - } - tok.negatives = negatives; - tok.positives = positives; - tok.result = siftPatterns(negatives, positives, options); + var repeatErr = function(i) { + util.error(regexpStr, 'Nothing to repeat at column ' + (i - 1)); + }; - if (options.capture && (positives.length + negatives.length) > 1) { - tok.result = '(' + tok.result + ')'; - } + // Decode a few escaped characters. + var str = util.strToChars(regexpStr); + l = str.length; - cache[key] = tok; - return tok.result; -} + // Iterate through each character in string. + while (i < l) { + c = str[i++]; -function siftPatterns(neg, pos, options) { - var onlyNegative = filterPatterns(neg, pos, '-', false, options) || []; - var onlyPositive = filterPatterns(pos, neg, '', false, options) || []; - var intersected = filterPatterns(neg, pos, '-?', true, options) || []; - var subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); - return subpatterns.join('|'); -} + switch (c) { + // Handle escaped characters, inclues a few sets. + case '\\': + c = str[i++]; -function splitToRanges(min, max) { - min = Number(min); - max = Number(max); + switch (c) { + case 'b': + last.push(positions.wordBoundary()); + break; - var nines = 1; - var stops = [max]; - var stop = +countNines(min, nines); + case 'B': + last.push(positions.nonWordBoundary()); + break; - while (min <= stop && stop <= max) { - stops = push(stops, stop); - nines += 1; - stop = +countNines(min, nines); - } + case 'w': + last.push(sets.words()); + break; - var zeros = 1; - stop = countZeros(max + 1, zeros) - 1; + case 'W': + last.push(sets.notWords()); + break; - while (min < stop && stop <= max) { - stops = push(stops, stop); - zeros += 1; - stop = countZeros(max + 1, zeros) - 1; - } + case 'd': + last.push(sets.ints()); + break; - stops.sort(compare); - return stops; -} + case 'D': + last.push(sets.notInts()); + break; -/** - * Convert a range to a regex pattern - * @param {Number} `start` - * @param {Number} `stop` - * @return {String} - */ + case 's': + last.push(sets.whitespace()); + break; -function rangeToPattern(start, stop, options) { - if (start === stop) { - return {pattern: String(start), digits: []}; - } + case 'S': + last.push(sets.notWhitespace()); + break; - var zipped = zip(String(start), String(stop)); - var len = zipped.length, i = -1; + default: + // Check if c is integer. + // In which case it's a reference. + if (/\d/.test(c)) { + last.push({ type: types.REFERENCE, value: parseInt(c, 10) }); - var pattern = ''; - var digits = 0; + // Escaped character. + } else { + last.push({ type: types.CHAR, value: c.charCodeAt(0) }); + } + } - while (++i < len) { - var numbers = zipped[i]; - var startDigit = numbers[0]; - var stopDigit = numbers[1]; + break; - if (startDigit === stopDigit) { - pattern += startDigit; - } else if (startDigit !== '0' || stopDigit !== '9') { - pattern += toCharacterClass(startDigit, stopDigit); + // Positionals. + case '^': + last.push(positions.begin()); + break; - } else { - digits += 1; - } - } + case '$': + last.push(positions.end()); + break; - if (digits) { - pattern += options.shorthand ? '\\d' : '[0-9]'; - } - return { pattern: pattern, digits: [digits] }; -} + // Handle custom sets. + case '[': + // Check if this class is 'anti' i.e. [^abc]. + var not; + if (str[i] === '^') { + not = true; + i++; + } else { + not = false; + } -function splitToPatterns(min, max, tok, options) { - var ranges = splitToRanges(min, max); - var len = ranges.length; - var idx = -1; + // Get all the characters in class. + var classTokens = util.tokenizeClass(str.slice(i), regexpStr); - var tokens = []; - var start = min; - var prev; + // Increase index by length of class. + i += classTokens[1]; + last.push({ + type: types.SET, + set: classTokens[0], + not: not, + }); - while (++idx < len) { - var range = ranges[idx]; - var obj = rangeToPattern(start, range, options); - var zeros = ''; + break; - if (!tok.isPadded && prev && prev.pattern === obj.pattern) { - if (prev.digits.length > 1) { - prev.digits.pop(); - } - prev.digits.push(obj.digits[0]); - prev.string = prev.pattern + toQuantifier(prev.digits); - start = range + 1; - continue; - } - if (tok.isPadded) { - zeros = padZeros(range, tok); - } + // Class of any character except \n. + case '.': + last.push(sets.anyChar()); + break; - obj.string = zeros + obj.pattern + toQuantifier(obj.digits); - tokens.push(obj); - start = range + 1; - prev = obj; - } - return tokens; -} + // Push group onto stack. + case '(': + // Create group. + var group = { + type: types.GROUP, + stack: [], + remember: true, + }; -function filterPatterns(arr, comparison, prefix, intersection, options) { - var res = []; + c = str[i]; - for (var i = 0; i < arr.length; i++) { - var tok = arr[i]; - var ele = tok.string; + // If if this is a special kind of group. + if (c === '?') { + c = str[i + 1]; + i += 2; - if (options.relaxZeros !== false) { - if (prefix === '-' && ele.charAt(0) === '0') { - if (ele.charAt(1) === '{') { - ele = '0*' + ele.replace(/^0\{\d+\}/, ''); - } else { - ele = '0*' + ele.slice(1); - } - } - } + // Match if followed by. + if (c === '=') { + group.followedBy = true; - if (!intersection && !contains(comparison, 'string', ele)) { - res.push(prefix + ele); - } + // Match if not followed by. + } else if (c === '!') { + group.notFollowedBy = true; - if (intersection && contains(comparison, 'string', ele)) { - res.push(prefix + ele); - } - } - return res; -} + } else if (c !== ':') { + util.error(regexpStr, + 'Invalid group, character \'' + c + + '\' after \'?\' at column ' + (i - 1)); + } -/** - * Zip strings (`for in` can be used on string characters) - */ + group.remember = false; + } -function zip(a, b) { - var arr = []; - for (var ch in a) arr.push([a[ch], b[ch]]); - return arr; -} + // Insert subgroup into current group stack. + last.push(group); -function compare(a, b) { - return a > b ? 1 : b > a ? -1 : 0; -} + // Remember the current group for when the group closes. + groupStack.push(lastGroup); -function push(arr, ele) { - if (arr.indexOf(ele) === -1) arr.push(ele); - return arr; -} + // Make this new group the current group. + lastGroup = group; + last = group.stack; + break; -function contains(arr, key, val) { - for (var i = 0; i < arr.length; i++) { - if (arr[i][key] === val) { - return true; - } - } - return false; -} -function countNines(min, len) { - return String(min).slice(0, -len) + repeat('9', len); -} + // Pop group out of stack. + case ')': + if (groupStack.length === 0) { + util.error(regexpStr, 'Unmatched ) at column ' + (i - 1)); + } + lastGroup = groupStack.pop(); -function countZeros(integer, zeros) { - return integer - (integer % Math.pow(10, zeros)); -} + // Check if this group has a PIPE. + // To get back the correct last stack. + last = lastGroup.options ? + lastGroup.options[lastGroup.options.length - 1] : lastGroup.stack; + break; -function toQuantifier(digits) { - var start = digits[0]; - var stop = digits[1] ? (',' + digits[1]) : ''; - if (!stop && (!start || start === 1)) { - return ''; - } - return '{' + start + stop + '}'; -} -function toCharacterClass(a, b) { - return '[' + a + ((b - a === 1) ? '' : '-') + b + ']'; -} + // Use pipe character to give more choices. + case '|': + // Create array where options are if this is the first PIPE + // in this clause. + if (!lastGroup.options) { + lastGroup.options = [lastGroup.stack]; + delete lastGroup.stack; + } -function padding(str) { - return /^-?(0+)\d/.exec(str); -} + // Create a new stack and add to options for rest of clause. + var stack = []; + lastGroup.options.push(stack); + last = stack; + break; -function padZeros(val, tok) { - if (tok.isPadded) { - var diff = Math.abs(tok.maxLen - String(val).length); - switch (diff) { - case 0: - return ''; - case 1: - return '0'; - default: { - return '0{' + diff + '}'; - } - } - } - return val; -} -/** - * Expose `toRegexRange` - */ + // Repetition. + // For every repetition, remove last element from last stack + // then insert back a RANGE object. + // This design is chosen because there could be more than + // one repetition symbols in a regex i.e. `a?+{2,3}`. + case '{': + var rs = /^(\d+)(,(\d+)?)?\}/.exec(str.slice(i)), min, max; + if (rs !== null) { + if (last.length === 0) { + repeatErr(i); + } + min = parseInt(rs[1], 10); + max = rs[2] ? rs[3] ? parseInt(rs[3], 10) : Infinity : min; + i += rs[0].length; -module.exports = toRegexRange; + last.push({ + type: types.REPETITION, + min: min, + max: max, + value: last.pop(), + }); + } else { + last.push({ + type: types.CHAR, + value: 123, + }); + } + break; + case '?': + if (last.length === 0) { + repeatErr(i); + } + last.push({ + type: types.REPETITION, + min: 0, + max: 1, + value: last.pop(), + }); + break; -/***/ }), -/* 647 */ -/***/ (function(module, exports, __webpack_require__) { + case '+': + if (last.length === 0) { + repeatErr(i); + } + last.push({ + type: types.REPETITION, + min: 1, + max: Infinity, + value: last.pop(), + }); + break; -"use strict"; -/*! - * repeat-element - * - * Copyright (c) 2015 Jon Schlinkert. - * Licensed under the MIT license. - */ + case '*': + if (last.length === 0) { + repeatErr(i); + } + last.push({ + type: types.REPETITION, + min: 0, + max: Infinity, + value: last.pop(), + }); + break; + // Default is a character that is not `\[](){}?+*^$`. + default: + last.push({ + type: types.CHAR, + value: c.charCodeAt(0), + }); + } -module.exports = function repeat(ele, num) { - var arr = new Array(num); + } - for (var i = 0; i < num; i++) { - arr[i] = ele; + // Check if any groups have not been closed. + if (groupStack.length !== 0) { + util.error(regexpStr, 'Unterminated group'); } - return arr; + return start; }; +module.exports.types = types; + /***/ }), -/* 648 */ +/* 651 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +var types = __webpack_require__(652); +var sets = __webpack_require__(653); + +// All of these are private and only used by randexp. +// It's assumed that they will always be called with the correct input. -var Node = __webpack_require__(649); -var utils = __webpack_require__(634); +var CTRL = '@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ ?'; +var SLSH = { '0': 0, 't': 9, 'n': 10, 'v': 11, 'f': 12, 'r': 13 }; /** - * Braces parsers + * Finds character representations in str and convert all to + * their respective characters + * + * @param {String} str + * @return {String} */ +exports.strToChars = function(str) { + /* jshint maxlen: false */ + var chars_regex = /(\[\\b\])|(\\)?\\(?:u([A-F0-9]{4})|x([A-F0-9]{2})|(0?[0-7]{2})|c([@A-Z\[\\\]\^?])|([0tnvfr]))/g; + str = str.replace(chars_regex, function(s, b, lbs, a16, b16, c8, dctrl, eslsh) { + if (lbs) { + return s; + } -module.exports = function(braces, options) { - braces.parser - .set('bos', function() { - if (!this.parsed) { - this.ast = this.nodes[0] = new Node(this.ast); - } - }) - - /** - * Character parsers - */ - - .set('escape', function() { - var pos = this.position(); - var m = this.match(/^(?:\\(.)|\$\{)/); - if (!m) return; - - var prev = this.prev(); - var last = utils.last(prev.nodes); - - var node = pos(new Node({ - type: 'text', - multiplier: 1, - val: m[0] - })); - - if (node.val === '\\\\') { - return node; - } - - if (node.val === '${') { - var str = this.input; - var idx = -1; - var ch; - - while ((ch = str[++idx])) { - this.consume(1); - node.val += ch; - if (ch === '\\') { - node.val += str[++idx]; - continue; - } - if (ch === '}') { - break; - } - } - } - - if (this.options.unescape !== false) { - node.val = node.val.replace(/\\([{}])/g, '$1'); - } + var code = b ? 8 : + a16 ? parseInt(a16, 16) : + b16 ? parseInt(b16, 16) : + c8 ? parseInt(c8, 8) : + dctrl ? CTRL.indexOf(dctrl) : + SLSH[eslsh]; - if (last.val === '"' && this.input.charAt(0) === '"') { - last.val = node.val; - this.consume(1); - return; - } + var c = String.fromCharCode(code); - return concatNodes.call(this, pos, node, prev, options); - }) + // Escape special regex characters. + if (/[\[\]{}\^$.|?*+()]/.test(c)) { + c = '\\' + c; + } - /** - * Brackets: "[...]" (basic, this is overridden by - * other parsers in more advanced implementations) - */ + return c; + }); - .set('bracket', function() { - var isInside = this.isInside('brace'); - var pos = this.position(); - var m = this.match(/^(?:\[([!^]?)([^\]]{2,}|\]-)(\]|[^*+?]+)|\[)/); - if (!m) return; + return str; +}; - var prev = this.prev(); - var val = m[0]; - var negated = m[1] ? '^' : ''; - var inner = m[2] || ''; - var close = m[3] || ''; - if (isInside && prev.type === 'brace') { - prev.text = prev.text || ''; - prev.text += val; - } +/** + * turns class into tokens + * reads str until it encounters a ] not preceeded by a \ + * + * @param {String} str + * @param {String} regexpStr + * @return {Array., Number>} + */ +exports.tokenizeClass = function(str, regexpStr) { + /* jshint maxlen: false */ + var tokens = []; + var regexp = /\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(?:\\)?([^\]]))|(\])|(?:\\)?(.)/g; + var rs, c; - var esc = this.input.slice(0, 2); - if (inner === '' && esc === '\\]') { - inner += esc; - this.consume(2); - var str = this.input; - var idx = -1; - var ch; + while ((rs = regexp.exec(str)) != null) { + if (rs[1]) { + tokens.push(sets.words()); - while ((ch = str[++idx])) { - this.consume(1); - if (ch === ']') { - close = ch; - break; - } - inner += ch; - } - } + } else if (rs[2]) { + tokens.push(sets.ints()); - return pos(new Node({ - type: 'bracket', - val: val, - escaped: close !== ']', - negated: negated, - inner: inner, - close: close - })); - }) + } else if (rs[3]) { + tokens.push(sets.whitespace()); - /** - * Empty braces (we capture these early to - * speed up processing in the compiler) - */ + } else if (rs[4]) { + tokens.push(sets.notWords()); - .set('multiplier', function() { - var isInside = this.isInside('brace'); - var pos = this.position(); - var m = this.match(/^\{((?:,|\{,+\})+)\}/); - if (!m) return; + } else if (rs[5]) { + tokens.push(sets.notInts()); - this.multiplier = true; - var prev = this.prev(); - var val = m[0]; + } else if (rs[6]) { + tokens.push(sets.notWhitespace()); - if (isInside && prev.type === 'brace') { - prev.text = prev.text || ''; - prev.text += val; - } + } else if (rs[7]) { + tokens.push({ + type: types.RANGE, + from: (rs[8] || rs[9]).charCodeAt(0), + to: rs[10].charCodeAt(0), + }); - var node = pos(new Node({ - type: 'text', - multiplier: 1, - match: m, - val: val - })); + } else if (c = rs[12]) { + tokens.push({ + type: types.CHAR, + value: c.charCodeAt(0), + }); - return concatNodes.call(this, pos, node, prev, options); - }) + } else { + return [tokens, regexp.lastIndex]; + } + } - /** - * Open - */ + exports.error(regexpStr, 'Unterminated character class'); +}; - .set('brace.open', function() { - var pos = this.position(); - var m = this.match(/^\{(?!(?:[^\\}]?|,+)\})/); - if (!m) return; - var prev = this.prev(); - var last = utils.last(prev.nodes); +/** + * Shortcut to throw errors. + * + * @param {String} regexp + * @param {String} msg + */ +exports.error = function(regexp, msg) { + throw new SyntaxError('Invalid regular expression: /' + regexp + '/: ' + msg); +}; - // if the last parsed character was an extglob character - // we need to _not optimize_ the brace pattern because - // it might be mistaken for an extglob by a downstream parser - if (last && last.val && isExtglobChar(last.val.slice(-1))) { - last.optimize = false; - } - var open = pos(new Node({ - type: 'brace.open', - val: m[0] - })); +/***/ }), +/* 652 */ +/***/ (function(module, exports) { - var node = pos(new Node({ - type: 'brace', - nodes: [] - })); +module.exports = { + ROOT : 0, + GROUP : 1, + POSITION : 2, + SET : 3, + RANGE : 4, + REPETITION : 5, + REFERENCE : 6, + CHAR : 7, +}; - node.push(open); - prev.push(node); - this.push('brace', node); - }) - /** - * Close - */ +/***/ }), +/* 653 */ +/***/ (function(module, exports, __webpack_require__) { - .set('brace.close', function() { - var pos = this.position(); - var m = this.match(/^\}/); - if (!m || !m[0]) return; +var types = __webpack_require__(652); - var brace = this.pop('brace'); - var node = pos(new Node({ - type: 'brace.close', - val: m[0] - })); +var INTS = function() { + return [{ type: types.RANGE , from: 48, to: 57 }]; +}; - if (!this.isType(brace, 'brace')) { - if (this.options.strict) { - throw new Error('missing opening "{"'); - } - node.type = 'text'; - node.multiplier = 0; - node.escaped = true; - return node; - } +var WORDS = function() { + return [ + { type: types.CHAR, value: 95 }, + { type: types.RANGE, from: 97, to: 122 }, + { type: types.RANGE, from: 65, to: 90 } + ].concat(INTS()); +}; - var prev = this.prev(); - var last = utils.last(prev.nodes); - if (last.text) { - var lastNode = utils.last(last.nodes); - if (lastNode.val === ')' && /[!@*?+]\(/.test(last.text)) { - var open = last.nodes[0]; - var text = last.nodes[1]; - if (open.type === 'brace.open' && text && text.type === 'text') { - text.optimize = false; - } - } - } +var WHITESPACE = function() { + return [ + { type: types.CHAR, value: 9 }, + { type: types.CHAR, value: 10 }, + { type: types.CHAR, value: 11 }, + { type: types.CHAR, value: 12 }, + { type: types.CHAR, value: 13 }, + { type: types.CHAR, value: 32 }, + { type: types.CHAR, value: 160 }, + { type: types.CHAR, value: 5760 }, + { type: types.CHAR, value: 6158 }, + { type: types.CHAR, value: 8192 }, + { type: types.CHAR, value: 8193 }, + { type: types.CHAR, value: 8194 }, + { type: types.CHAR, value: 8195 }, + { type: types.CHAR, value: 8196 }, + { type: types.CHAR, value: 8197 }, + { type: types.CHAR, value: 8198 }, + { type: types.CHAR, value: 8199 }, + { type: types.CHAR, value: 8200 }, + { type: types.CHAR, value: 8201 }, + { type: types.CHAR, value: 8202 }, + { type: types.CHAR, value: 8232 }, + { type: types.CHAR, value: 8233 }, + { type: types.CHAR, value: 8239 }, + { type: types.CHAR, value: 8287 }, + { type: types.CHAR, value: 12288 }, + { type: types.CHAR, value: 65279 } + ]; +}; - if (brace.nodes.length > 2) { - var first = brace.nodes[1]; - if (first.type === 'text' && first.val === ',') { - brace.nodes.splice(1, 1); - brace.nodes.push(first); - } - } +var NOTANYCHAR = function() { + return [ + { type: types.CHAR, value: 10 }, + { type: types.CHAR, value: 13 }, + { type: types.CHAR, value: 8232 }, + { type: types.CHAR, value: 8233 }, + ]; +}; - brace.push(node); - }) +// Predefined class objects. +exports.words = function() { + return { type: types.SET, set: WORDS(), not: false }; +}; - /** - * Capture boundary characters - */ +exports.notWords = function() { + return { type: types.SET, set: WORDS(), not: true }; +}; - .set('boundary', function() { - var pos = this.position(); - var m = this.match(/^[$^](?!\{)/); - if (!m) return; - return pos(new Node({ - type: 'text', - val: m[0] - })); - }) +exports.ints = function() { + return { type: types.SET, set: INTS(), not: false }; +}; - /** - * One or zero, non-comma characters wrapped in braces - */ +exports.notInts = function() { + return { type: types.SET, set: INTS(), not: true }; +}; - .set('nobrace', function() { - var isInside = this.isInside('brace'); - var pos = this.position(); - var m = this.match(/^\{[^,]?\}/); - if (!m) return; +exports.whitespace = function() { + return { type: types.SET, set: WHITESPACE(), not: false }; +}; - var prev = this.prev(); - var val = m[0]; +exports.notWhitespace = function() { + return { type: types.SET, set: WHITESPACE(), not: true }; +}; - if (isInside && prev.type === 'brace') { - prev.text = prev.text || ''; - prev.text += val; - } +exports.anyChar = function() { + return { type: types.SET, set: NOTANYCHAR(), not: true }; +}; - return pos(new Node({ - type: 'text', - multiplier: 0, - val: val - })); - }) - /** - * Text - */ +/***/ }), +/* 654 */ +/***/ (function(module, exports, __webpack_require__) { - .set('text', function() { - var isInside = this.isInside('brace'); - var pos = this.position(); - var m = this.match(/^((?!\\)[^${}[\]])+/); - if (!m) return; +var types = __webpack_require__(652); - var prev = this.prev(); - var val = m[0]; +exports.wordBoundary = function() { + return { type: types.POSITION, value: 'b' }; +}; - if (isInside && prev.type === 'brace') { - prev.text = prev.text || ''; - prev.text += val; - } +exports.nonWordBoundary = function() { + return { type: types.POSITION, value: 'B' }; +}; - var node = pos(new Node({ - type: 'text', - multiplier: 1, - val: val - })); +exports.begin = function() { + return { type: types.POSITION, value: '^' }; +}; - return concatNodes.call(this, pos, node, prev, options); - }); +exports.end = function() { + return { type: types.POSITION, value: '$' }; }; -/** - * Returns true if the character is an extglob character. - */ -function isExtglobChar(ch) { - return ch === '!' || ch === '@' || ch === '*' || ch === '?' || ch === '+'; -} +/***/ }), +/* 655 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * Combine text nodes, and calculate empty sets (`{,,}`) - * @param {Function} `pos` Function to calculate node position - * @param {Object} `node` AST node - * @return {Object} +"use strict"; +/*! + * define-property + * + * Copyright (c) 2015-2018, Jon Schlinkert. + * Released under the MIT License. */ -function concatNodes(pos, node, parent, options) { - node.orig = node.val; - var prev = this.prev(); - var last = utils.last(prev.nodes); - var isEscaped = false; - - if (node.val.length > 1) { - var a = node.val.charAt(0); - var b = node.val.slice(-1); - - isEscaped = (a === '"' && b === '"') - || (a === "'" && b === "'") - || (a === '`' && b === '`'); - } - if (isEscaped && options.unescape !== false) { - node.val = node.val.slice(1, node.val.length - 1); - node.escaped = true; - } - if (node.match) { - var match = node.match[1]; - if (!match || match.indexOf('}') === -1) { - match = node.match[0]; - } +var isobject = __webpack_require__(656); +var isDescriptor = __webpack_require__(657); +var define = (typeof Reflect !== 'undefined' && Reflect.defineProperty) + ? Reflect.defineProperty + : Object.defineProperty; - // replace each set with a single "," - var val = match.replace(/\{/g, ',').replace(/\}/g, ''); - node.multiplier *= val.length; - node.val = ''; +module.exports = function defineProperty(obj, key, val) { + if (!isobject(obj) && typeof obj !== 'function' && !Array.isArray(obj)) { + throw new TypeError('expected an object, function, or array'); } - var simpleText = last.type === 'text' - && last.multiplier === 1 - && node.multiplier === 1 - && node.val; + if (typeof key !== 'string') { + throw new TypeError('expected "key" to be a string'); + } - if (simpleText) { - last.val += node.val; - return; + if (isDescriptor(val)) { + define(obj, key, val); + return obj; } - prev.push(node); -} + define(obj, key, { + configurable: true, + enumerable: false, + writable: true, + value: val + }); + + return obj; +}; /***/ }), -/* 649 */ +/* 656 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +/*! + * isobject + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ -var isObject = __webpack_require__(618); -var define = __webpack_require__(650); -var utils = __webpack_require__(651); -var ownNames; -/** - * Create a new AST `Node` with the given `val` and `type`. +module.exports = function isObject(val) { + return val != null && typeof val === 'object' && Array.isArray(val) === false; +}; + + +/***/ }), +/* 657 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * is-descriptor * - * ```js - * var node = new Node('*', 'Star'); - * var node = new Node({type: 'star', val: '*'}); - * ``` - * @name Node - * @param {String|Object} `val` Pass a matched substring, or an object to merge onto the node. - * @param {String} `type` The node type to use when `val` is a string. - * @return {Object} node instance - * @api public + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. */ -function Node(val, type, parent) { - if (typeof type !== 'string') { - parent = type; - type = null; + + +var typeOf = __webpack_require__(658); +var isAccessor = __webpack_require__(659); +var isData = __webpack_require__(660); + +module.exports = function isDescriptor(obj, key) { + if (typeOf(obj) !== 'object') { + return false; } + if ('get' in obj) { + return isAccessor(obj, key); + } + return isData(obj, key); +}; - define(this, 'parent', parent); - define(this, 'isNode', true); - define(this, 'expect', null); - if (typeof type !== 'string' && isObject(val)) { - lazyKeys(); - var keys = Object.keys(val); - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - if (ownNames.indexOf(key) === -1) { - this[key] = val[key]; - } - } - } else { - this.type = type; - this.val = val; +/***/ }), +/* 658 */ +/***/ (function(module, exports) { + +var toString = Object.prototype.toString; + +module.exports = function kindOf(val) { + if (val === void 0) return 'undefined'; + if (val === null) return 'null'; + + var type = typeof val; + if (type === 'boolean') return 'boolean'; + if (type === 'string') return 'string'; + if (type === 'number') return 'number'; + if (type === 'symbol') return 'symbol'; + if (type === 'function') { + return isGeneratorFn(val) ? 'generatorfunction' : 'function'; } -} -/** - * Returns true if the given value is a node. - * - * ```js - * var Node = require('snapdragon-node'); - * var node = new Node({type: 'foo'}); - * console.log(Node.isNode(node)); //=> true - * console.log(Node.isNode({})); //=> false - * ``` - * @param {Object} `node` - * @returns {Boolean} - * @api public - */ + if (isArray(val)) return 'array'; + if (isBuffer(val)) return 'buffer'; + if (isArguments(val)) return 'arguments'; + if (isDate(val)) return 'date'; + if (isError(val)) return 'error'; + if (isRegexp(val)) return 'regexp'; -Node.isNode = function(node) { - return utils.isNode(node); -}; + switch (ctorName(val)) { + case 'Symbol': return 'symbol'; + case 'Promise': return 'promise'; -/** - * Define a non-enumberable property on the node instance. - * Useful for adding properties that shouldn't be extended - * or visible during debugging. - * - * ```js - * var node = new Node(); - * node.define('foo', 'something non-enumerable'); - * ``` - * @param {String} `name` - * @param {any} `val` - * @return {Object} returns the node instance - * @api public - */ + // Set, Map, WeakSet, WeakMap + case 'WeakMap': return 'weakmap'; + case 'WeakSet': return 'weakset'; + case 'Map': return 'map'; + case 'Set': return 'set'; -Node.prototype.define = function(name, val) { - define(this, name, val); - return this; -}; + // 8-bit typed arrays + case 'Int8Array': return 'int8array'; + case 'Uint8Array': return 'uint8array'; + case 'Uint8ClampedArray': return 'uint8clampedarray'; -/** - * Returns true if `node.val` is an empty string, or `node.nodes` does - * not contain any non-empty text nodes. - * - * ```js - * var node = new Node({type: 'text'}); - * node.isEmpty(); //=> true - * node.val = 'foo'; - * node.isEmpty(); //=> false - * ``` - * @param {Function} `fn` (optional) Filter function that is called on `node` and/or child nodes. `isEmpty` will return false immediately when the filter function returns false on any nodes. - * @return {Boolean} - * @api public - */ + // 16-bit typed arrays + case 'Int16Array': return 'int16array'; + case 'Uint16Array': return 'uint16array'; -Node.prototype.isEmpty = function(fn) { - return utils.isEmpty(this, fn); -}; + // 32-bit typed arrays + case 'Int32Array': return 'int32array'; + case 'Uint32Array': return 'uint32array'; + case 'Float32Array': return 'float32array'; + case 'Float64Array': return 'float64array'; + } -/** - * Given node `foo` and node `bar`, push node `bar` onto `foo.nodes`, and - * set `foo` as `bar.parent`. - * - * ```js - * var foo = new Node({type: 'foo'}); - * var bar = new Node({type: 'bar'}); - * foo.push(bar); - * ``` - * @param {Object} `node` - * @return {Number} Returns the length of `node.nodes` - * @api public - */ + if (isGeneratorObj(val)) { + return 'generator'; + } -Node.prototype.push = function(node) { - assert(Node.isNode(node), 'expected node to be an instance of Node'); - define(node, 'parent', this); + // Non-plain objects + type = toString.call(val); + switch (type) { + case '[object Object]': return 'object'; + // iterators + case '[object Map Iterator]': return 'mapiterator'; + case '[object Set Iterator]': return 'setiterator'; + case '[object String Iterator]': return 'stringiterator'; + case '[object Array Iterator]': return 'arrayiterator'; + } - this.nodes = this.nodes || []; - return this.nodes.push(node); + // other + return type.slice(8, -1).toLowerCase().replace(/\s/g, ''); }; -/** - * Given node `foo` and node `bar`, unshift node `bar` onto `foo.nodes`, and - * set `foo` as `bar.parent`. - * - * ```js - * var foo = new Node({type: 'foo'}); - * var bar = new Node({type: 'bar'}); - * foo.unshift(bar); - * ``` - * @param {Object} `node` - * @return {Number} Returns the length of `node.nodes` - * @api public - */ +function ctorName(val) { + return typeof val.constructor === 'function' ? val.constructor.name : null; +} -Node.prototype.unshift = function(node) { - assert(Node.isNode(node), 'expected node to be an instance of Node'); - define(node, 'parent', this); +function isArray(val) { + if (Array.isArray) return Array.isArray(val); + return val instanceof Array; +} - this.nodes = this.nodes || []; - return this.nodes.unshift(node); -}; +function isError(val) { + return val instanceof Error || (typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number'); +} -/** - * Pop a node from `node.nodes`. - * - * ```js - * var node = new Node({type: 'foo'}); - * node.push(new Node({type: 'a'})); - * node.push(new Node({type: 'b'})); - * node.push(new Node({type: 'c'})); - * node.push(new Node({type: 'd'})); - * console.log(node.nodes.length); - * //=> 4 - * node.pop(); - * console.log(node.nodes.length); - * //=> 3 - * ``` - * @return {Number} Returns the popped `node` - * @api public - */ +function isDate(val) { + if (val instanceof Date) return true; + return typeof val.toDateString === 'function' + && typeof val.getDate === 'function' + && typeof val.setDate === 'function'; +} -Node.prototype.pop = function() { - return this.nodes && this.nodes.pop(); -}; +function isRegexp(val) { + if (val instanceof RegExp) return true; + return typeof val.flags === 'string' + && typeof val.ignoreCase === 'boolean' + && typeof val.multiline === 'boolean' + && typeof val.global === 'boolean'; +} -/** - * Shift a node from `node.nodes`. - * - * ```js - * var node = new Node({type: 'foo'}); - * node.push(new Node({type: 'a'})); - * node.push(new Node({type: 'b'})); - * node.push(new Node({type: 'c'})); - * node.push(new Node({type: 'd'})); - * console.log(node.nodes.length); - * //=> 4 - * node.shift(); - * console.log(node.nodes.length); - * //=> 3 - * ``` - * @return {Object} Returns the shifted `node` - * @api public - */ +function isGeneratorFn(name, val) { + return ctorName(name) === 'GeneratorFunction'; +} -Node.prototype.shift = function() { - return this.nodes && this.nodes.shift(); -}; +function isGeneratorObj(val) { + return typeof val.throw === 'function' + && typeof val.return === 'function' + && typeof val.next === 'function'; +} + +function isArguments(val) { + try { + if (typeof val.length === 'number' && typeof val.callee === 'function') { + return true; + } + } catch (err) { + if (err.message.indexOf('callee') !== -1) { + return true; + } + } + return false; +} /** - * Remove `node` from `node.nodes`. - * - * ```js - * node.remove(childNode); - * ``` - * @param {Object} `node` - * @return {Object} Returns the removed node. - * @api public + * If you need to support Safari 5-7 (8-10 yr-old browser), + * take a look at https://github.com/feross/is-buffer */ -Node.prototype.remove = function(node) { - assert(Node.isNode(node), 'expected node to be an instance of Node'); - this.nodes = this.nodes || []; - var idx = node.index; - if (idx !== -1) { - node.index = -1; - return this.nodes.splice(idx, 1); +function isBuffer(val) { + if (val.constructor && typeof val.constructor.isBuffer === 'function') { + return val.constructor.isBuffer(val); } - return null; -}; + return false; +} -/** - * Get the first child node from `node.nodes` that matches the given `type`. - * If `type` is a number, the child node at that index is returned. - * - * ```js - * var child = node.find(1); //<= index of the node to get - * var child = node.find('foo'); //<= node.type of a child node - * var child = node.find(/^(foo|bar)$/); //<= regex to match node.type - * var child = node.find(['foo', 'bar']); //<= array of node.type(s) - * ``` - * @param {String} `type` - * @return {Object} Returns a child node or undefined. - * @api public - */ -Node.prototype.find = function(type) { - return utils.findNode(this.nodes, type); -}; +/***/ }), +/* 659 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * Return true if the node is the given `type`. +"use strict"; +/*! + * is-accessor-descriptor * - * ```js - * var node = new Node({type: 'bar'}); - * cosole.log(node.isType('foo')); // false - * cosole.log(node.isType(/^(foo|bar)$/)); // true - * cosole.log(node.isType(['foo', 'bar'])); // true - * ``` - * @param {String} `type` - * @return {Boolean} - * @api public + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. */ -Node.prototype.isType = function(type) { - return utils.isType(this, type); -}; -/** - * Return true if the `node.nodes` has the given `type`. - * - * ```js - * var foo = new Node({type: 'foo'}); - * var bar = new Node({type: 'bar'}); - * foo.push(bar); - * - * cosole.log(foo.hasType('qux')); // false - * cosole.log(foo.hasType(/^(qux|bar)$/)); // true - * cosole.log(foo.hasType(['qux', 'bar'])); // true - * ``` - * @param {String} `type` - * @return {Boolean} - * @api public - */ -Node.prototype.hasType = function(type) { - return utils.hasType(this, type); +var typeOf = __webpack_require__(658); + +// accessor descriptor properties +var accessor = { + get: 'function', + set: 'function', + configurable: 'boolean', + enumerable: 'boolean' }; -/** - * Get the siblings array, or `null` if it doesn't exist. - * - * ```js - * var foo = new Node({type: 'foo'}); - * var bar = new Node({type: 'bar'}); - * var baz = new Node({type: 'baz'}); - * foo.push(bar); - * foo.push(baz); - * - * console.log(bar.siblings.length) // 2 - * console.log(baz.siblings.length) // 2 - * ``` - * @return {Array} - * @api public - */ +function isAccessorDescriptor(obj, prop) { + if (typeof prop === 'string') { + var val = Object.getOwnPropertyDescriptor(obj, prop); + return typeof val !== 'undefined'; + } -Object.defineProperty(Node.prototype, 'siblings', { - set: function() { - throw new Error('node.siblings is a getter and cannot be defined'); - }, - get: function() { - return this.parent ? this.parent.nodes : null; + if (typeOf(obj) !== 'object') { + return false; } -}); -/** - * Get the node's current index from `node.parent.nodes`. - * This should always be correct, even when the parent adds nodes. - * - * ```js - * var foo = new Node({type: 'foo'}); - * var bar = new Node({type: 'bar'}); - * var baz = new Node({type: 'baz'}); - * var qux = new Node({type: 'qux'}); - * foo.push(bar); - * foo.push(baz); - * foo.unshift(qux); - * - * console.log(bar.index) // 1 - * console.log(baz.index) // 2 - * console.log(qux.index) // 0 - * ``` - * @return {Number} - * @api public - */ + if (has(obj, 'value') || has(obj, 'writable')) { + return false; + } -Object.defineProperty(Node.prototype, 'index', { - set: function(index) { - define(this, 'idx', index); - }, - get: function() { - if (!Array.isArray(this.siblings)) { - return -1; - } - var tok = this.idx !== -1 ? this.siblings[this.idx] : null; - if (tok !== this) { - this.idx = this.siblings.indexOf(this); - } - return this.idx; + if (!has(obj, 'get') || typeof obj.get !== 'function') { + return false; } -}); -/** - * Get the previous node from the siblings array or `null`. - * - * ```js - * var foo = new Node({type: 'foo'}); - * var bar = new Node({type: 'bar'}); - * var baz = new Node({type: 'baz'}); - * foo.push(bar); - * foo.push(baz); - * - * console.log(baz.prev.type) // 'bar' - * ``` - * @return {Object} - * @api public - */ + // tldr: it's valid to have "set" be undefined + // "set" might be undefined if `Object.getOwnPropertyDescriptor` + // was used to get the value, and only `get` was defined by the user + if (has(obj, 'set') && typeof obj[key] !== 'function' && typeof obj[key] !== 'undefined') { + return false; + } -Object.defineProperty(Node.prototype, 'prev', { - set: function() { - throw new Error('node.prev is a getter and cannot be defined'); - }, - get: function() { - if (Array.isArray(this.siblings)) { - return this.siblings[this.index - 1] || this.parent.prev; + for (var key in obj) { + if (!accessor.hasOwnProperty(key)) { + continue; + } + + if (typeOf(obj[key]) === accessor[key]) { + continue; + } + + if (typeof obj[key] !== 'undefined') { + return false; } - return null; } -}); + return true; +} + +function has(obj, key) { + return {}.hasOwnProperty.call(obj, key); +} /** - * Get the siblings array, or `null` if it doesn't exist. - * - * ```js - * var foo = new Node({type: 'foo'}); - * var bar = new Node({type: 'bar'}); - * var baz = new Node({type: 'baz'}); - * foo.push(bar); - * foo.push(baz); - * - * console.log(bar.siblings.length) // 2 - * console.log(baz.siblings.length) // 2 - * ``` - * @return {Object} - * @api public + * Expose `isAccessorDescriptor` */ -Object.defineProperty(Node.prototype, 'next', { - set: function() { - throw new Error('node.next is a getter and cannot be defined'); - }, - get: function() { - if (Array.isArray(this.siblings)) { - return this.siblings[this.index + 1] || this.parent.next; - } - return null; - } -}); +module.exports = isAccessorDescriptor; -/** - * Get the first node from `node.nodes`. - * - * ```js - * var foo = new Node({type: 'foo'}); - * var bar = new Node({type: 'bar'}); - * var baz = new Node({type: 'baz'}); - * var qux = new Node({type: 'qux'}); - * foo.push(bar); - * foo.push(baz); - * foo.push(qux); + +/***/ }), +/* 660 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * is-data-descriptor * - * console.log(foo.first.type) // 'bar' - * ``` - * @return {Object} The first node, or undefiend - * @api public + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. */ -Object.defineProperty(Node.prototype, 'first', { - get: function() { - return this.nodes ? this.nodes[0] : null; + + +var typeOf = __webpack_require__(658); + +module.exports = function isDataDescriptor(obj, prop) { + // data descriptor properties + var data = { + configurable: 'boolean', + enumerable: 'boolean', + writable: 'boolean' + }; + + if (typeOf(obj) !== 'object') { + return false; } -}); -/** - * Get the last node from `node.nodes`. - * - * ```js - * var foo = new Node({type: 'foo'}); - * var bar = new Node({type: 'bar'}); - * var baz = new Node({type: 'baz'}); - * var qux = new Node({type: 'qux'}); - * foo.push(bar); - * foo.push(baz); - * foo.push(qux); - * - * console.log(foo.last.type) // 'qux' - * ``` - * @return {Object} The last node, or undefiend - * @api public - */ + if (typeof prop === 'string') { + var val = Object.getOwnPropertyDescriptor(obj, prop); + return typeof val !== 'undefined'; + } -Object.defineProperty(Node.prototype, 'last', { - get: function() { - return this.nodes ? utils.last(this.nodes) : null; + if (!('value' in obj) && !('writable' in obj)) { + return false; } -}); -/** - * Get the last node from `node.nodes`. - * - * ```js - * var foo = new Node({type: 'foo'}); - * var bar = new Node({type: 'bar'}); - * var baz = new Node({type: 'baz'}); - * var qux = new Node({type: 'qux'}); - * foo.push(bar); - * foo.push(baz); - * foo.push(qux); - * - * console.log(foo.last.type) // 'qux' - * ``` - * @return {Object} The last node, or undefiend - * @api public - */ + for (var key in obj) { + if (key === 'value') continue; -Object.defineProperty(Node.prototype, 'scope', { - get: function() { - if (this.isScope !== true) { - return this.parent ? this.parent.scope : this; + if (!data.hasOwnProperty(key)) { + continue; + } + + if (typeOf(obj[key]) === data[key]) { + continue; + } + + if (typeof obj[key] !== 'undefined') { + return false; } - return this; } -}); + return true; +}; -/** - * Get own property names from Node prototype, but only the - * first time `Node` is instantiated - */ -function lazyKeys() { - if (!ownNames) { - ownNames = Object.getOwnPropertyNames(Node.prototype); +/***/ }), +/* 661 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var isExtendable = __webpack_require__(662); +var assignSymbols = __webpack_require__(664); + +module.exports = Object.assign || function(obj/*, objects*/) { + if (obj === null || typeof obj === 'undefined') { + throw new TypeError('Cannot convert undefined or null to object'); + } + if (!isObject(obj)) { + obj = {}; + } + for (var i = 1; i < arguments.length; i++) { + var val = arguments[i]; + if (isString(val)) { + val = toObject(val); + } + if (isObject(val)) { + assign(obj, val); + assignSymbols(obj, val); + } + } + return obj; +}; + +function assign(a, b) { + for (var key in b) { + if (hasOwn(b, key)) { + a[key] = b[key]; + } + } +} + +function isString(val) { + return (val && typeof val === 'string'); +} + +function toObject(str) { + var obj = {}; + for (var i in str) { + obj[i] = str[i]; } + return obj; +} + +function isObject(val) { + return (val && typeof val === 'object') || isExtendable(val); } /** - * Simplified assertion. Throws an error is `val` is falsey. + * Returns true if the given `key` is an own property of `obj`. */ -function assert(val, message) { - if (!val) throw new Error(message); +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); } -/** - * Expose `Node` +function isEnum(obj, key) { + return Object.prototype.propertyIsEnumerable.call(obj, key); +} + + +/***/ }), +/* 662 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * is-extendable + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. */ -exports = module.exports = Node; + + +var isPlainObject = __webpack_require__(663); + +module.exports = function isExtendable(val) { + return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); +}; /***/ }), -/* 650 */ +/* 663 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /*! - * define-property + * is-plain-object * - * Copyright (c) 2015, 2017, Jon Schlinkert. + * Copyright (c) 2014-2017, Jon Schlinkert. * Released under the MIT License. */ -var isDescriptor = __webpack_require__(619); +var isObject = __webpack_require__(656); -module.exports = function defineProperty(obj, prop, val) { - if (typeof obj !== 'object' && typeof obj !== 'function') { - throw new TypeError('expected an object or function.'); +function isObjectObject(o) { + return isObject(o) === true + && Object.prototype.toString.call(o) === '[object Object]'; +} + +module.exports = function isPlainObject(o) { + var ctor,prot; + + if (isObjectObject(o) === false) return false; + + // If has modified constructor + ctor = o.constructor; + if (typeof ctor !== 'function') return false; + + // If has modified prototype + prot = ctor.prototype; + if (isObjectObject(prot) === false) return false; + + // If constructor does not have an Object-specific method + if (prot.hasOwnProperty('isPrototypeOf') === false) { + return false; } - if (typeof prop !== 'string') { - throw new TypeError('expected `prop` to be a string.'); + // Most likely a plain Object + return true; +}; + + +/***/ }), +/* 664 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * assign-symbols + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +module.exports = function(receiver, objects) { + if (receiver === null || typeof receiver === 'undefined') { + throw new TypeError('expected first argument to be an object.'); } - if (isDescriptor(val) && ('set' in val || 'get' in val)) { - return Object.defineProperty(obj, prop, val); + if (typeof objects === 'undefined' || typeof Symbol === 'undefined') { + return receiver; } - return Object.defineProperty(obj, prop, { - configurable: true, - enumerable: false, - writable: true, - value: val - }); + if (typeof Object.getOwnPropertySymbols !== 'function') { + return receiver; + } + + var isEnumerable = Object.prototype.propertyIsEnumerable; + var target = Object(receiver); + var len = arguments.length, i = 0; + + while (++i < len) { + var provider = Object(arguments[i]); + var names = Object.getOwnPropertySymbols(provider); + + for (var j = 0; j < names.length; j++) { + var key = names[j]; + + if (isEnumerable.call(provider, key)) { + target[key] = provider[key]; + } + } + } + return target; }; /***/ }), -/* 651 */ +/* 665 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var typeOf = __webpack_require__(652); -var utils = module.exports; +var extend = __webpack_require__(666); +var safe = __webpack_require__(649); /** - * Returns true if the given value is a node. + * The main export is a function that takes a `pattern` string and an `options` object. * * ```js - * var Node = require('snapdragon-node'); - * var node = new Node({type: 'foo'}); - * console.log(utils.isNode(node)); //=> true - * console.log(utils.isNode({})); //=> false + & var not = require('regex-not'); + & console.log(not('foo')); + & //=> /^(?:(?!^(?:foo)$).)*$/ * ``` - * @param {Object} `node` Instance of [snapdragon-node][] - * @returns {Boolean} + * + * @param {String} `pattern` + * @param {Object} `options` + * @return {RegExp} Converts the given `pattern` to a regex using the specified `options`. * @api public */ -utils.isNode = function(node) { - return typeOf(node) === 'object' && node.isNode === true; -}; +function toRegex(pattern, options) { + return new RegExp(toRegex.create(pattern, options)); +} /** - * Emit an empty string for the given `node`. + * Create a regex-compatible string from the given `pattern` and `options`. * * ```js - * // do nothing for beginning-of-string - * snapdragon.compiler.set('bos', utils.noop); + & var not = require('regex-not'); + & console.log(not.create('foo')); + & //=> '^(?:(?!^(?:foo)$).)*$' * ``` - * @param {Object} `node` Instance of [snapdragon-node][] - * @returns {undefined} + * @param {String} `pattern` + * @param {Object} `options` + * @return {String} * @api public */ -utils.noop = function(node) { - append(this, '', node); -}; +toRegex.create = function(pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected a string'); + } -/** - * Appdend `node.val` to `compiler.output`, exactly as it was created - * by the parser. - * - * ```js - * snapdragon.compiler.set('text', utils.identity); - * ``` - * @param {Object} `node` Instance of [snapdragon-node][] - * @returns {undefined} - * @api public - */ + var opts = extend({}, options); + if (opts.contains === true) { + opts.strictNegate = false; + } -utils.identity = function(node) { - append(this, node.val, node); -}; + var open = opts.strictOpen !== false ? '^' : ''; + var close = opts.strictClose !== false ? '$' : ''; + var endChar = opts.endChar ? opts.endChar : '+'; + var str = pattern; -/** - * Previously named `.emit`, this method appends the given `val` - * to `compiler.output` for the given node. Useful when you know - * what value should be appended advance, regardless of the actual - * value of `node.val`. - * - * ```js - * snapdragon.compiler - * .set('i', function(node) { - * this.mapVisit(node); - * }) - * .set('i.open', utils.append('')) - * .set('i.close', utils.append('')) - * ``` - * @param {Object} `node` Instance of [snapdragon-node][] - * @returns {Function} Returns a compiler middleware function. - * @api public - */ + if (opts.strictNegate === false) { + str = '(?:(?!(?:' + pattern + ')).)' + endChar; + } else { + str = '(?:(?!^(?:' + pattern + ')$).)' + endChar; + } -utils.append = function(val) { - return function(node) { - append(this, val, node); - }; + var res = open + str + close; + if (opts.safe === true && safe(res) === false) { + throw new Error('potentially unsafe regular expression: ' + res); + } + + return res; }; /** - * Used in compiler middleware, this onverts an AST node into - * an empty `text` node and deletes `node.nodes` if it exists. - * The advantage of this method is that, as opposed to completely - * removing the node, indices will not need to be re-calculated - * in sibling nodes, and nothing is appended to the output. - * - * ```js - * utils.toNoop(node); - * // convert `node.nodes` to the given value instead of deleting it - * utils.toNoop(node, []); - * ``` - * @param {Object} `node` Instance of [snapdragon-node][] - * @param {Array} `nodes` Optionally pass a new `nodes` value, to replace the existing `node.nodes` array. - * @api public + * Expose `toRegex` */ -utils.toNoop = function(node, nodes) { - if (nodes) { - node.nodes = nodes; - } else { - delete node.nodes; - node.type = 'text'; - node.val = ''; +module.exports = toRegex; + + +/***/ }), +/* 666 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var isExtendable = __webpack_require__(667); +var assignSymbols = __webpack_require__(664); + +module.exports = Object.assign || function(obj/*, objects*/) { + if (obj === null || typeof obj === 'undefined') { + throw new TypeError('Cannot convert undefined or null to object'); } + if (!isObject(obj)) { + obj = {}; + } + for (var i = 1; i < arguments.length; i++) { + var val = arguments[i]; + if (isString(val)) { + val = toObject(val); + } + if (isObject(val)) { + assign(obj, val); + assignSymbols(obj, val); + } + } + return obj; }; +function assign(a, b) { + for (var key in b) { + if (hasOwn(b, key)) { + a[key] = b[key]; + } + } +} + +function isString(val) { + return (val && typeof val === 'string'); +} + +function toObject(str) { + var obj = {}; + for (var i in str) { + obj[i] = str[i]; + } + return obj; +} + +function isObject(val) { + return (val && typeof val === 'object') || isExtendable(val); +} + /** - * Visit `node` with the given `fn`. The built-in `.visit` method in snapdragon - * automatically calls registered compilers, this allows you to pass a visitor - * function. - * - * ```js - * snapdragon.compiler.set('i', function(node) { - * utils.visit(node, function(childNode) { - * // do stuff with "childNode" - * return childNode; - * }); - * }); - * ``` - * @param {Object} `node` Instance of [snapdragon-node][] - * @param {Function} `fn` - * @return {Object} returns the node after recursively visiting all child nodes. - * @api public + * Returns true if the given `key` is an own property of `obj`. */ -utils.visit = function(node, fn) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); - assert(isFunction(fn), 'expected a visitor function'); - fn(node); - return node.nodes ? utils.mapVisit(node, fn) : node; -}; +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +function isEnum(obj, key) { + return Object.prototype.propertyIsEnumerable.call(obj, key); +} + + +/***/ }), +/* 667 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * Map [visit](#visit) the given `fn` over `node.nodes`. This is called by - * [visit](#visit), use this method if you do not want `fn` to be called on - * the first node. +"use strict"; +/*! + * is-extendable * - * ```js - * snapdragon.compiler.set('i', function(node) { - * utils.mapVisit(node, function(childNode) { - * // do stuff with "childNode" - * return childNode; - * }); - * }); - * ``` - * @param {Object} `node` Instance of [snapdragon-node][] - * @param {Object} `options` - * @param {Function} `fn` - * @return {Object} returns the node - * @api public + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. */ -utils.mapVisit = function(node, fn) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); - assert(isArray(node.nodes), 'expected node.nodes to be an array'); - assert(isFunction(fn), 'expected a visitor function'); - for (var i = 0; i < node.nodes.length; i++) { - utils.visit(node.nodes[i], fn); - } - return node; + +var isPlainObject = __webpack_require__(663); + +module.exports = function isExtendable(val) { + return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); }; -/** - * Unshift an `*.open` node onto `node.nodes`. - * - * ```js - * var Node = require('snapdragon-node'); - * snapdragon.parser.set('brace', function(node) { - * var match = this.match(/^{/); - * if (match) { - * var parent = new Node({type: 'brace'}); - * utils.addOpen(parent, Node); - * console.log(parent.nodes[0]): - * // { type: 'brace.open', val: '' }; - * - * // push the parent "brace" node onto the stack - * this.push(parent); + +/***/ }), +/* 668 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * array-unique * - * // return the parent node, so it's also added to the AST - * return brace; - * } - * }); - * ``` - * @param {Object} `node` Instance of [snapdragon-node][] - * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][]. - * @param {Function} `filter` Optionaly specify a filter function to exclude the node. - * @return {Object} Returns the created opening node. - * @api public + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. */ -utils.addOpen = function(node, Node, val, filter) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); - assert(isFunction(Node), 'expected Node to be a constructor function'); - if (typeof val === 'function') { - filter = val; - val = ''; + +module.exports = function unique(arr) { + if (!Array.isArray(arr)) { + throw new TypeError('array-unique expects an array.'); } - if (typeof filter === 'function' && !filter(node)) return; - var open = new Node({ type: node.type + '.open', val: val}); - var unshift = node.unshift || node.unshiftNode; - if (typeof unshift === 'function') { - unshift.call(node, open); - } else { - utils.unshiftNode(node, open); + var len = arr.length; + var i = -1; + + while (i++ < len) { + var j = i + 1; + + for (; j < arr.length; ++j) { + if (arr[i] === arr[j]) { + arr.splice(j--, 1); + } + } } - return open; + return arr; }; -/** - * Push a `*.close` node onto `node.nodes`. - * - * ```js - * var Node = require('snapdragon-node'); - * snapdragon.parser.set('brace', function(node) { - * var match = this.match(/^}/); - * if (match) { - * var parent = this.parent(); - * if (parent.type !== 'brace') { - * throw new Error('missing opening: ' + '}'); - * } - * - * utils.addClose(parent, Node); - * console.log(parent.nodes[parent.nodes.length - 1]): - * // { type: 'brace.close', val: '' }; - * - * // no need to return a node, since the parent - * // was already added to the AST - * return; - * } - * }); - * ``` - * @param {Object} `node` Instance of [snapdragon-node][] - * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][]. - * @param {Function} `filter` Optionaly specify a filter function to exclude the node. - * @return {Object} Returns the created closing node. - * @api public - */ +module.exports.immutable = function uniqueImmutable(arr) { + if (!Array.isArray(arr)) { + throw new TypeError('array-unique expects an array.'); + } -utils.addClose = function(node, Node, val, filter) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); - assert(isFunction(Node), 'expected Node to be a constructor function'); + var arrLen = arr.length; + var newArr = new Array(arrLen); - if (typeof val === 'function') { - filter = val; - val = ''; + for (var i = 0; i < arrLen; i++) { + newArr[i] = arr[i]; } - if (typeof filter === 'function' && !filter(node)) return; - var close = new Node({ type: node.type + '.close', val: val}); - var push = node.push || node.pushNode; - if (typeof push === 'function') { - push.call(node, close); - } else { - utils.pushNode(node, close); - } - return close; + return module.exports(newArr); }; -/** - * Wraps the given `node` with `*.open` and `*.close` nodes. - * - * @param {Object} `node` Instance of [snapdragon-node][] - * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][]. - * @param {Function} `filter` Optionaly specify a filter function to exclude the node. - * @return {Object} Returns the node - * @api public - */ -utils.wrapNodes = function(node, Node, filter) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); - assert(isFunction(Node), 'expected Node to be a constructor function'); +/***/ }), +/* 669 */ +/***/ (function(module, exports, __webpack_require__) { - utils.addOpen(node, Node, filter); - utils.addClose(node, Node, filter); - return node; -}; +"use strict"; -/** - * Push the given `node` onto `parent.nodes`, and set `parent` as `node.parent. - * - * ```js - * var parent = new Node({type: 'foo'}); - * var node = new Node({type: 'bar'}); - * utils.pushNode(parent, node); - * console.log(parent.nodes[0].type) // 'bar' - * console.log(node.parent.type) // 'foo' - * ``` - * @param {Object} `parent` - * @param {Object} `node` Instance of [snapdragon-node][] - * @return {Object} Returns the child node - * @api public - */ -utils.pushNode = function(parent, node) { - assert(utils.isNode(parent), 'expected parent node to be an instance of Node'); - assert(utils.isNode(node), 'expected node to be an instance of Node'); +var isObject = __webpack_require__(670); - node.define('parent', parent); - parent.nodes = parent.nodes || []; - parent.nodes.push(node); - return node; +module.exports = function extend(o/*, objects*/) { + if (!isObject(o)) { o = {}; } + + var len = arguments.length; + for (var i = 1; i < len; i++) { + var obj = arguments[i]; + + if (isObject(obj)) { + assign(o, obj); + } + } + return o; }; +function assign(a, b) { + for (var key in b) { + if (hasOwn(b, key)) { + a[key] = b[key]; + } + } +} + /** - * Unshift `node` onto `parent.nodes`, and set `parent` as `node.parent. - * - * ```js - * var parent = new Node({type: 'foo'}); - * var node = new Node({type: 'bar'}); - * utils.unshiftNode(parent, node); - * console.log(parent.nodes[0].type) // 'bar' - * console.log(node.parent.type) // 'foo' - * ``` - * @param {Object} `parent` - * @param {Object} `node` Instance of [snapdragon-node][] - * @return {undefined} - * @api public + * Returns true if the given `key` is an own property of `obj`. */ -utils.unshiftNode = function(parent, node) { - assert(utils.isNode(parent), 'expected parent node to be an instance of Node'); - assert(utils.isNode(node), 'expected node to be an instance of Node'); +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} - node.define('parent', parent); - parent.nodes = parent.nodes || []; - parent.nodes.unshift(node); -}; -/** - * Pop the last `node` off of `parent.nodes`. The advantage of - * using this method is that it checks for `node.nodes` and works - * with any version of `snapdragon-node`. +/***/ }), +/* 670 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * is-extendable * - * ```js - * var parent = new Node({type: 'foo'}); - * utils.pushNode(parent, new Node({type: 'foo'})); - * utils.pushNode(parent, new Node({type: 'bar'})); - * utils.pushNode(parent, new Node({type: 'baz'})); - * console.log(parent.nodes.length); //=> 3 - * utils.popNode(parent); - * console.log(parent.nodes.length); //=> 2 - * ``` - * @param {Object} `parent` - * @param {Object} `node` Instance of [snapdragon-node][] - * @return {Number|Undefined} Returns the length of `node.nodes` or undefined. - * @api public + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. */ -utils.popNode = function(node) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); - if (typeof node.pop === 'function') { - return node.pop(); - } - return node.nodes && node.nodes.pop(); -}; -/** - * Shift the first `node` off of `parent.nodes`. The advantage of - * using this method is that it checks for `node.nodes` and works - * with any version of `snapdragon-node`. - * - * ```js - * var parent = new Node({type: 'foo'}); - * utils.pushNode(parent, new Node({type: 'foo'})); - * utils.pushNode(parent, new Node({type: 'bar'})); - * utils.pushNode(parent, new Node({type: 'baz'})); - * console.log(parent.nodes.length); //=> 3 - * utils.shiftNode(parent); - * console.log(parent.nodes.length); //=> 2 - * ``` - * @param {Object} `parent` - * @param {Object} `node` Instance of [snapdragon-node][] - * @return {Number|Undefined} Returns the length of `node.nodes` or undefined. - * @api public - */ -utils.shiftNode = function(node) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); - if (typeof node.shift === 'function') { - return node.shift(); - } - return node.nodes && node.nodes.shift(); +module.exports = function isExtendable(val) { + return typeof val !== 'undefined' && val !== null + && (typeof val === 'object' || typeof val === 'function'); }; -/** - * Remove the specified `node` from `parent.nodes`. - * - * ```js - * var parent = new Node({type: 'abc'}); - * var foo = new Node({type: 'foo'}); - * utils.pushNode(parent, foo); - * utils.pushNode(parent, new Node({type: 'bar'})); - * utils.pushNode(parent, new Node({type: 'baz'})); - * console.log(parent.nodes.length); //=> 3 - * utils.removeNode(parent, foo); - * console.log(parent.nodes.length); //=> 2 - * ``` - * @param {Object} `parent` - * @param {Object} `node` Instance of [snapdragon-node][] - * @return {Object|undefined} Returns the removed node, if successful, or undefined if it does not exist on `parent.nodes`. - * @api public - */ -utils.removeNode = function(parent, node) { - assert(utils.isNode(parent), 'expected parent.node to be an instance of Node'); - assert(utils.isNode(node), 'expected node to be an instance of Node'); +/***/ }), +/* 671 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var utils = __webpack_require__(672); + +module.exports = function(braces, options) { + braces.compiler + + /** + * bos + */ + + .set('bos', function() { + if (this.output) return; + this.ast.queue = isEscaped(this.ast) ? [this.ast.val] : []; + this.ast.count = 1; + }) + + /** + * Square brackets + */ + + .set('bracket', function(node) { + var close = node.close; + var open = !node.escaped ? '[' : '\\['; + var negated = node.negated; + var inner = node.inner; + + inner = inner.replace(/\\(?=[\\\w]|$)/g, '\\\\'); + if (inner === ']-') { + inner = '\\]\\-'; + } + + if (negated && inner.indexOf('.') === -1) { + inner += '.'; + } + if (negated && inner.indexOf('/') === -1) { + inner += '/'; + } + + var val = open + negated + inner + close; + var queue = node.parent.queue; + var last = utils.arrayify(queue.pop()); + + queue.push(utils.join(last, val)); + queue.push.apply(queue, []); + }) + + /** + * Brace + */ + + .set('brace', function(node) { + node.queue = isEscaped(node) ? [node.val] : []; + node.count = 1; + return this.mapVisit(node.nodes); + }) + + /** + * Open + */ + + .set('brace.open', function(node) { + node.parent.open = node.val; + }) + + /** + * Inner + */ + + .set('text', function(node) { + var queue = node.parent.queue; + var escaped = node.escaped; + var segs = [node.val]; + + if (node.optimize === false) { + options = utils.extend({}, options, {optimize: false}); + } + + if (node.multiplier > 1) { + node.parent.count *= node.multiplier; + } + + if (options.quantifiers === true && utils.isQuantifier(node.val)) { + escaped = true; + + } else if (node.val.length > 1) { + if (isType(node.parent, 'brace') && !isEscaped(node)) { + var expanded = utils.expand(node.val, options); + segs = expanded.segs; + + if (expanded.isOptimized) { + node.parent.isOptimized = true; + } + + // if nothing was expanded, we probably have a literal brace + if (!segs.length) { + var val = (expanded.val || node.val); + if (options.unescape !== false) { + // unescape unexpanded brace sequence/set separators + val = val.replace(/\\([,.])/g, '$1'); + // strip quotes + val = val.replace(/["'`]/g, ''); + } + + segs = [val]; + escaped = true; + } + } + + } else if (node.val === ',') { + if (options.expand) { + node.parent.queue.push(['']); + segs = ['']; + } else { + segs = ['|']; + } + } else { + escaped = true; + } + + if (escaped && isType(node.parent, 'brace')) { + if (node.parent.nodes.length <= 4 && node.parent.count === 1) { + node.parent.escaped = true; + } else if (node.parent.length <= 3) { + node.parent.escaped = true; + } + } + + if (!hasQueue(node.parent)) { + node.parent.queue = segs; + return; + } + + var last = utils.arrayify(queue.pop()); + if (node.parent.count > 1 && options.expand) { + last = multiply(last, node.parent.count); + node.parent.count = 1; + } + + queue.push(utils.join(utils.flatten(last), segs.shift())); + queue.push.apply(queue, segs); + }) + + /** + * Close + */ + + .set('brace.close', function(node) { + var queue = node.parent.queue; + var prev = node.parent.parent; + var last = prev.queue.pop(); + var open = node.parent.open; + var close = node.val; + + if (open && close && isOptimized(node, options)) { + open = '('; + close = ')'; + } + + // if a close brace exists, and the previous segment is one character + // don't wrap the result in braces or parens + var ele = utils.last(queue); + if (node.parent.count > 1 && options.expand) { + ele = multiply(queue.pop(), node.parent.count); + node.parent.count = 1; + queue.push(ele); + } + + if (close && typeof ele === 'string' && ele.length === 1) { + open = ''; + close = ''; + } + + if ((isLiteralBrace(node, options) || noInner(node)) && !node.parent.hasEmpty) { + queue.push(utils.join(open, queue.pop() || '')); + queue = utils.flatten(utils.join(queue, close)); + } + + if (typeof last === 'undefined') { + prev.queue = [queue]; + } else { + prev.queue.push(utils.flatten(utils.join(last, queue))); + } + }) + + /** + * eos + */ - if (!parent.nodes) { - return null; - } + .set('eos', function(node) { + if (this.input) return; - if (typeof parent.remove === 'function') { - return parent.remove(node); - } + if (options.optimize !== false) { + this.output = utils.last(utils.flatten(this.ast.queue)); + } else if (Array.isArray(utils.last(this.ast.queue))) { + this.output = utils.flatten(this.ast.queue.pop()); + } else { + this.output = utils.flatten(this.ast.queue); + } + + if (node.parent.count > 1 && options.expand) { + this.output = multiply(this.output, node.parent.count); + } + + this.output = utils.arrayify(this.output); + this.ast.queue = []; + }); - var idx = parent.nodes.indexOf(node); - if (idx !== -1) { - return parent.nodes.splice(idx, 1); - } }; /** - * Returns true if `node.type` matches the given `type`. Throws a - * `TypeError` if `node` is not an instance of `Node`. - * - * ```js - * var Node = require('snapdragon-node'); - * var node = new Node({type: 'foo'}); - * console.log(utils.isType(node, 'foo')); // false - * console.log(utils.isType(node, 'bar')); // true - * ``` - * @param {Object} `node` Instance of [snapdragon-node][] - * @param {String} `type` - * @return {Boolean} - * @api public + * Multiply the segments in the current brace level */ -utils.isType = function(node, type) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); - switch (typeOf(type)) { - case 'array': - var types = type.slice(); - for (var i = 0; i < types.length; i++) { - if (utils.isType(node, types[i])) { - return true; - } - } - return false; - case 'string': - return node.type === type; - case 'regexp': - return type.test(node.type); - default: { - throw new TypeError('expected "type" to be an array, string or regexp'); - } - } -}; +function multiply(queue, n, options) { + return utils.flatten(utils.repeat(utils.arrayify(queue), n)); +} /** - * Returns true if the given `node` has the given `type` in `node.nodes`. - * Throws a `TypeError` if `node` is not an instance of `Node`. - * - * ```js - * var Node = require('snapdragon-node'); - * var node = new Node({ - * type: 'foo', - * nodes: [ - * new Node({type: 'bar'}), - * new Node({type: 'baz'}) - * ] - * }); - * console.log(utils.hasType(node, 'xyz')); // false - * console.log(utils.hasType(node, 'baz')); // true - * ``` - * @param {Object} `node` Instance of [snapdragon-node][] - * @param {String} `type` - * @return {Boolean} - * @api public + * Return true if `node` is escaped */ -utils.hasType = function(node, type) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); - if (!Array.isArray(node.nodes)) return false; - for (var i = 0; i < node.nodes.length; i++) { - if (utils.isType(node.nodes[i], type)) { - return true; - } - } - return false; -}; +function isEscaped(node) { + return node.escaped === true; +} /** - * Returns the first node from `node.nodes` of the given `type` - * - * ```js - * var node = new Node({ - * type: 'foo', - * nodes: [ - * new Node({type: 'text', val: 'abc'}), - * new Node({type: 'text', val: 'xyz'}) - * ] - * }); - * - * var textNode = utils.firstOfType(node.nodes, 'text'); - * console.log(textNode.val); - * //=> 'abc' - * ``` - * @param {Array} `nodes` - * @param {String} `type` - * @return {Object|undefined} Returns the first matching node or undefined. - * @api public + * Returns true if regex parens should be used for sets. If the parent `type` + * is not `brace`, then we're on a root node, which means we should never + * expand segments and open/close braces should be `{}` (since this indicates + * a brace is missing from the set) */ -utils.firstOfType = function(nodes, type) { - for (var i = 0; i < nodes.length; i++) { - var node = nodes[i]; - if (utils.isType(node, type)) { - return node; - } - } -}; +function isOptimized(node, options) { + if (node.parent.isOptimized) return true; + return isType(node.parent, 'brace') + && !isEscaped(node.parent) + && options.expand !== true; +} /** - * Returns the node at the specified index, or the first node of the - * given `type` from `node.nodes`. - * - * ```js - * var node = new Node({ - * type: 'foo', - * nodes: [ - * new Node({type: 'text', val: 'abc'}), - * new Node({type: 'text', val: 'xyz'}) - * ] - * }); - * - * var nodeOne = utils.findNode(node.nodes, 'text'); - * console.log(nodeOne.val); - * //=> 'abc' - * - * var nodeTwo = utils.findNode(node.nodes, 1); - * console.log(nodeTwo.val); - * //=> 'xyz' - * ``` - * - * @param {Array} `nodes` - * @param {String|Number} `type` Node type or index. - * @return {Object} Returns a node or undefined. - * @api public + * Returns true if the value in `node` should be wrapped in a literal brace. + * @return {Boolean} */ -utils.findNode = function(nodes, type) { - if (!Array.isArray(nodes)) { - return null; - } - if (typeof type === 'number') { - return nodes[type]; - } - return utils.firstOfType(nodes, type); -}; +function isLiteralBrace(node, options) { + return isEscaped(node.parent) || options.optimize !== false; +} /** - * Returns true if the given node is an "*.open" node. - * - * ```js - * var Node = require('snapdragon-node'); - * var brace = new Node({type: 'brace'}); - * var open = new Node({type: 'brace.open'}); - * var close = new Node({type: 'brace.close'}); - * - * console.log(utils.isOpen(brace)); // false - * console.log(utils.isOpen(open)); // true - * console.log(utils.isOpen(close)); // false - * ``` - * @param {Object} `node` Instance of [snapdragon-node][] + * Returns true if the given `node` does not have an inner value. * @return {Boolean} - * @api public */ -utils.isOpen = function(node) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); - return node.type.slice(-5) === '.open'; -}; +function noInner(node, type) { + if (node.parent.queue.length === 1) { + return true; + } + var nodes = node.parent.nodes; + return nodes.length === 3 + && isType(nodes[0], 'brace.open') + && !isType(nodes[1], 'text') + && isType(nodes[2], 'brace.close'); +} /** - * Returns true if the given node is a "*.close" node. - * - * ```js - * var Node = require('snapdragon-node'); - * var brace = new Node({type: 'brace'}); - * var open = new Node({type: 'brace.open'}); - * var close = new Node({type: 'brace.close'}); - * - * console.log(utils.isClose(brace)); // false - * console.log(utils.isClose(open)); // false - * console.log(utils.isClose(close)); // true - * ``` - * @param {Object} `node` Instance of [snapdragon-node][] + * Returns true if the given `node` is the given `type` * @return {Boolean} - * @api public */ -utils.isClose = function(node) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); - return node.type.slice(-6) === '.close'; -}; +function isType(node, type) { + return typeof node !== 'undefined' && node.type === type; +} /** - * Returns true if `node.nodes` **has** an `.open` node - * - * ```js - * var Node = require('snapdragon-node'); - * var brace = new Node({ - * type: 'brace', - * nodes: [] - * }); - * - * var open = new Node({type: 'brace.open'}); - * console.log(utils.hasOpen(brace)); // false - * - * brace.pushNode(open); - * console.log(utils.hasOpen(brace)); // true - * ``` - * @param {Object} `node` Instance of [snapdragon-node][] + * Returns true if the given `node` has a non-empty queue. * @return {Boolean} - * @api public */ -utils.hasOpen = function(node) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); - var first = node.first || node.nodes ? node.nodes[0] : null; - if (utils.isNode(first)) { - return first.type === node.type + '.open'; - } - return false; -}; +function hasQueue(node) { + return Array.isArray(node.queue) && node.queue.length; +} + + +/***/ }), +/* 672 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var splitString = __webpack_require__(673); +var utils = module.exports; /** - * Returns true if `node.nodes` **has** a `.close` node - * - * ```js - * var Node = require('snapdragon-node'); - * var brace = new Node({ - * type: 'brace', - * nodes: [] - * }); - * - * var close = new Node({type: 'brace.close'}); - * console.log(utils.hasClose(brace)); // false - * - * brace.pushNode(close); - * console.log(utils.hasClose(brace)); // true - * ``` - * @param {Object} `node` Instance of [snapdragon-node][] - * @return {Boolean} - * @api public + * Module dependencies */ -utils.hasClose = function(node) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); - var last = node.last || node.nodes ? node.nodes[node.nodes.length - 1] : null; - if (utils.isNode(last)) { - return last.type === node.type + '.close'; - } - return false; +utils.extend = __webpack_require__(669); +utils.flatten = __webpack_require__(676); +utils.isObject = __webpack_require__(656); +utils.fillRange = __webpack_require__(677); +utils.repeat = __webpack_require__(685); +utils.unique = __webpack_require__(668); + +utils.define = function(obj, key, val) { + Object.defineProperty(obj, key, { + writable: true, + configurable: true, + enumerable: false, + value: val + }); }; /** - * Returns true if `node.nodes` has both `.open` and `.close` nodes - * - * ```js - * var Node = require('snapdragon-node'); - * var brace = new Node({ - * type: 'brace', - * nodes: [] - * }); - * - * var open = new Node({type: 'brace.open'}); - * var close = new Node({type: 'brace.close'}); - * console.log(utils.hasOpen(brace)); // false - * console.log(utils.hasClose(brace)); // false - * - * brace.pushNode(open); - * brace.pushNode(close); - * console.log(utils.hasOpen(brace)); // true - * console.log(utils.hasClose(brace)); // true - * ``` - * @param {Object} `node` Instance of [snapdragon-node][] - * @return {Boolean} - * @api public + * Returns true if the given string contains only empty brace sets. */ -utils.hasOpenAndClose = function(node) { - return utils.hasOpen(node) && utils.hasClose(node); +utils.isEmptySets = function(str) { + return /^(?:\{,\})+$/.test(str); }; /** - * Push the given `node` onto the `state.inside` array for the - * given type. This array is used as a specialized "stack" for - * only the given `node.type`. - * - * ```js - * var state = { inside: {}}; - * var node = new Node({type: 'brace'}); - * utils.addType(state, node); - * console.log(state.inside); - * //=> { brace: [{type: 'brace'}] } - * ``` - * @param {Object} `state` The `compiler.state` object or custom state object. - * @param {Object} `node` Instance of [snapdragon-node][] - * @return {Array} Returns the `state.inside` stack for the given type. - * @api public + * Returns true if the given string contains only empty brace sets. */ -utils.addType = function(state, node) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); - assert(isObject(state), 'expected state to be an object'); +utils.isQuotedString = function(str) { + var open = str.charAt(0); + if (open === '\'' || open === '"' || open === '`') { + return str.slice(-1) === open; + } + return false; +}; - var type = node.parent - ? node.parent.type - : node.type.replace(/\.open$/, ''); +/** + * Create the key to use for memoization. The unique key is generated + * by iterating over the options and concatenating key-value pairs + * to the pattern string. + */ - if (!state.hasOwnProperty('inside')) { - state.inside = {}; +utils.createKey = function(pattern, options) { + var id = pattern; + if (typeof options === 'undefined') { + return id; } - if (!state.inside.hasOwnProperty(type)) { - state.inside[type] = []; + var keys = Object.keys(options); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + id += ';' + key + '=' + String(options[key]); } - - var arr = state.inside[type]; - arr.push(node); - return arr; + return id; }; /** - * Remove the given `node` from the `state.inside` array for the - * given type. This array is used as a specialized "stack" for - * only the given `node.type`. - * - * ```js - * var state = { inside: {}}; - * var node = new Node({type: 'brace'}); - * utils.addType(state, node); - * console.log(state.inside); - * //=> { brace: [{type: 'brace'}] } - * utils.removeType(state, node); - * //=> { brace: [] } - * ``` - * @param {Object} `state` The `compiler.state` object or custom state object. - * @param {Object} `node` Instance of [snapdragon-node][] - * @return {Array} Returns the `state.inside` stack for the given type. - * @api public + * Normalize options */ -utils.removeType = function(state, node) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); - assert(isObject(state), 'expected state to be an object'); - - var type = node.parent - ? node.parent.type - : node.type.replace(/\.close$/, ''); - - if (state.inside.hasOwnProperty(type)) { - return state.inside[type].pop(); +utils.createOptions = function(options) { + var opts = utils.extend.apply(null, arguments); + if (typeof opts.expand === 'boolean') { + opts.optimize = !opts.expand; } + if (typeof opts.optimize === 'boolean') { + opts.expand = !opts.optimize; + } + if (opts.optimize === true) { + opts.makeRe = true; + } + return opts; }; /** - * Returns true if `node.val` is an empty string, or `node.nodes` does - * not contain any non-empty text nodes. - * - * ```js - * var node = new Node({type: 'text'}); - * utils.isEmpty(node); //=> true - * node.val = 'foo'; - * utils.isEmpty(node); //=> false - * ``` - * @param {Object} `node` Instance of [snapdragon-node][] - * @param {Function} `fn` - * @return {Boolean} - * @api public + * Join patterns in `a` to patterns in `b` */ -utils.isEmpty = function(node, fn) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); +utils.join = function(a, b, options) { + options = options || {}; + a = utils.arrayify(a); + b = utils.arrayify(b); - if (!Array.isArray(node.nodes)) { - if (node.type !== 'text') { - return true; - } - if (typeof fn === 'function') { - return fn(node, node.parent); - } - return !utils.trim(node.val); - } + if (!a.length) return b; + if (!b.length) return a; - for (var i = 0; i < node.nodes.length; i++) { - var child = node.nodes[i]; - if (utils.isOpen(child) || utils.isClose(child)) { + var len = a.length; + var idx = -1; + var arr = []; + + while (++idx < len) { + var val = a[idx]; + if (Array.isArray(val)) { + for (var i = 0; i < val.length; i++) { + val[i] = utils.join(val[i], b, options); + } + arr.push(val); continue; } - if (!utils.isEmpty(child, fn)) { - return false; + + for (var j = 0; j < b.length; j++) { + var bval = b[j]; + + if (Array.isArray(bval)) { + arr.push(utils.join(val, bval, options)); + } else { + arr.push(val + bval); + } } } - - return true; + return arr; }; /** - * Returns true if the `state.inside` stack for the given type exists - * and has one or more nodes on it. - * - * ```js - * var state = { inside: {}}; - * var node = new Node({type: 'brace'}); - * console.log(utils.isInsideType(state, 'brace')); //=> false - * utils.addType(state, node); - * console.log(utils.isInsideType(state, 'brace')); //=> true - * utils.removeType(state, node); - * console.log(utils.isInsideType(state, 'brace')); //=> false - * ``` - * @param {Object} `state` - * @param {String} `type` - * @return {Boolean} - * @api public + * Split the given string on `,` if not escaped. */ -utils.isInsideType = function(state, type) { - assert(isObject(state), 'expected state to be an object'); - assert(isString(type), 'expected type to be a string'); - - if (!state.hasOwnProperty('inside')) { - return false; +utils.split = function(str, options) { + var opts = utils.extend({sep: ','}, options); + if (typeof opts.keepQuotes !== 'boolean') { + opts.keepQuotes = true; } - - if (!state.inside.hasOwnProperty(type)) { - return false; + if (opts.unescape === false) { + opts.keepEscaping = true; } - - return state.inside[type].length > 0; + return splitString(str, opts, utils.escapeBrackets(opts)); }; /** - * Returns true if `node` is either a child or grand-child of the given `type`, - * or `state.inside[type]` is a non-empty array. + * Expand ranges or sets in the given `pattern`. * - * ```js - * var state = { inside: {}}; - * var node = new Node({type: 'brace'}); - * var open = new Node({type: 'brace.open'}); - * console.log(utils.isInside(state, open, 'brace')); //=> false - * utils.pushNode(node, open); - * console.log(utils.isInside(state, open, 'brace')); //=> true - * ``` - * @param {Object} `state` Either the `compiler.state` object, if it exists, or a user-supplied state object. - * @param {Object} `node` Instance of [snapdragon-node][] - * @param {String} `type` The `node.type` to check for. - * @return {Boolean} - * @api public + * @param {String} `str` + * @param {Object} `options` + * @return {Object} */ -utils.isInside = function(state, node, type) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); - assert(isObject(state), 'expected state to be an object'); +utils.expand = function(str, options) { + var opts = utils.extend({rangeLimit: 10000}, options); + var segs = utils.split(str, opts); + var tok = { segs: segs }; - if (Array.isArray(type)) { - for (var i = 0; i < type.length; i++) { - if (utils.isInside(state, node, type[i])) { - return true; - } - } - return false; + if (utils.isQuotedString(str)) { + return tok; } - var parent = node.parent; - if (typeof type === 'string') { - return (parent && parent.type === type) || utils.isInsideType(state, type); + if (opts.rangeLimit === true) { + opts.rangeLimit = 10000; } - if (typeOf(type) === 'regexp') { - if (parent && parent.type && type.test(parent.type)) { - return true; + if (segs.length > 1) { + if (opts.optimize === false) { + tok.val = segs[0]; + return tok; } - var keys = Object.keys(state.inside); - var len = keys.length; - var idx = -1; - while (++idx < len) { - var key = keys[idx]; - var val = state.inside[key]; + tok.segs = utils.stringifyArray(tok.segs); + } else if (segs.length === 1) { + var arr = str.split('..'); - if (Array.isArray(val) && val.length !== 0 && type.test(key)) { - return true; + if (arr.length === 1) { + tok.val = tok.segs[tok.segs.length - 1] || tok.val || str; + tok.segs = []; + return tok; + } + + if (arr.length === 2 && arr[0] === arr[1]) { + tok.escaped = true; + tok.val = arr[0]; + tok.segs = []; + return tok; + } + + if (arr.length > 1) { + if (opts.optimize !== false) { + opts.optimize = true; + delete opts.expand; + } + + if (opts.optimize !== true) { + var min = Math.min(arr[0], arr[1]); + var max = Math.max(arr[0], arr[1]); + var step = arr[2] || 1; + + if (opts.rangeLimit !== false && ((max - min) / step >= opts.rangeLimit)) { + throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.'); + } + } + + arr.push(opts); + tok.segs = utils.fillRange.apply(null, arr); + + if (!tok.segs.length) { + tok.escaped = true; + tok.val = str; + return tok; + } + + if (opts.optimize === true) { + tok.segs = utils.stringifyArray(tok.segs); + } + + if (tok.segs === '') { + tok.val = str; + } else { + tok.val = tok.segs[0]; } + return tok; } + } else { + tok.val = str; } - return false; + return tok; }; /** - * Get the last `n` element from the given `array`. Used for getting - * a node from `node.nodes.` - * - * @param {Array} `array` - * @param {Number} `n` + * Ensure commas inside brackets and parens are not split. + * @param {Object} `tok` Token from the `split-string` module * @return {undefined} - * @api public */ -utils.last = function(arr, n) { - return arr[arr.length - (n || 1)]; -}; +utils.escapeBrackets = function(options) { + return function(tok) { + if (tok.escaped && tok.val === 'b') { + tok.val = '\\b'; + return; + } -/** - * Cast the given `val` to an array. - * - * ```js - * console.log(utils.arrayify('')); - * //=> [] - * console.log(utils.arrayify('foo')); - * //=> ['foo'] - * console.log(utils.arrayify(['foo'])); - * //=> ['foo'] - * ``` - * @param {any} `val` - * @return {Array} - * @api public - */ + if (tok.val !== '(' && tok.val !== '[') return; + var opts = utils.extend({}, options); + var brackets = []; + var parens = []; + var stack = []; + var val = tok.val; + var str = tok.str; + var i = tok.idx - 1; -utils.arrayify = function(val) { - if (typeof val === 'string' && val !== '') { - return [val]; - } - if (!Array.isArray(val)) { - return []; - } - return val; -}; + while (++i < str.length) { + var ch = str[i]; -/** - * Convert the given `val` to a string by joining with `,`. Useful - * for creating a cheerio/CSS/DOM-style selector from a list of strings. - * - * @param {any} `val` - * @return {Array} - * @api public - */ + if (ch === '\\') { + val += (opts.keepEscaping === false ? '' : ch) + str[++i]; + continue; + } -utils.stringify = function(val) { - return utils.arrayify(val).join(','); -}; + if (ch === '(') { + parens.push(ch); + stack.push(ch); + } -/** - * Ensure that the given value is a string and call `.trim()` on it, - * or return an empty string. - * - * @param {String} `str` - * @return {String} - * @api public - */ + if (ch === '[') { + brackets.push(ch); + stack.push(ch); + } -utils.trim = function(str) { - return typeof str === 'string' ? str.trim() : ''; -}; + if (ch === ')') { + parens.pop(); + stack.pop(); + if (!stack.length) { + val += ch; + break; + } + } -/** - * Return true if val is an object - */ + if (ch === ']') { + brackets.pop(); + stack.pop(); + if (!stack.length) { + val += ch; + break; + } + } + val += ch; + } -function isObject(val) { - return typeOf(val) === 'object'; -} + tok.split = false; + tok.val = val.slice(1); + tok.idx = i; + }; +}; /** - * Return true if val is a string + * Returns true if the given string looks like a regex quantifier + * @return {Boolean} */ -function isString(val) { - return typeof val === 'string'; -} +utils.isQuantifier = function(str) { + return /^(?:[0-9]?,[0-9]|[0-9],)$/.test(str); +}; /** - * Return true if val is a function + * Cast `val` to an array. + * @param {*} `val` */ -function isFunction(val) { - return typeof val === 'function'; -} +utils.stringifyArray = function(arr) { + return [utils.arrayify(arr).join('|')]; +}; /** - * Return true if val is an array + * Cast `val` to an array. + * @param {*} `val` */ -function isArray(val) { - return Array.isArray(val); -} +utils.arrayify = function(arr) { + if (typeof arr === 'undefined') { + return []; + } + if (typeof arr === 'string') { + return [arr]; + } + return arr; +}; /** - * Shim to ensure the `.append` methods work with any version of snapdragon + * Returns true if the given `str` is a non-empty string + * @return {Boolean} */ -function append(compiler, val, node) { - if (typeof compiler.append !== 'function') { - return compiler.emit(val, node); - } - return compiler.append(val, node); -} +utils.isString = function(str) { + return str != null && typeof str === 'string'; +}; /** - * Simplified assertion. Throws an error is `val` is falsey. + * Get the last element from `array` + * @param {Array} `array` + * @return {*} */ -function assert(val, message) { - if (!val) throw new Error(message); -} +utils.last = function(arr, n) { + return arr[arr.length - (n || 1)]; +}; + +utils.escapeRegex = function(str) { + return str.replace(/\\?([!^*?()[\]{}+?/])/g, '\\$1'); +}; /***/ }), -/* 652 */ +/* 673 */ /***/ (function(module, exports, __webpack_require__) { -var isBuffer = __webpack_require__(642); -var toString = Object.prototype.toString; - -/** - * Get the native `typeof` a value. +"use strict"; +/*! + * split-string * - * @param {*} `val` - * @return {*} Native javascript type + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. */ -module.exports = function kindOf(val) { - // primitivies - if (typeof val === 'undefined') { - return 'undefined'; - } - if (val === null) { - return 'null'; - } - if (val === true || val === false || val instanceof Boolean) { - return 'boolean'; - } - if (typeof val === 'string' || val instanceof String) { - return 'string'; - } - if (typeof val === 'number' || val instanceof Number) { - return 'number'; - } - // functions - if (typeof val === 'function' || val instanceof Function) { - return 'function'; - } - // array - if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { - return 'array'; - } +var extend = __webpack_require__(674); - // check for instances of RegExp and Date before calling `toString` - if (val instanceof RegExp) { - return 'regexp'; - } - if (val instanceof Date) { - return 'date'; +module.exports = function(str, options, fn) { + if (typeof str !== 'string') { + throw new TypeError('expected a string'); } - // other objects - var type = toString.call(val); - - if (type === '[object RegExp]') { - return 'regexp'; - } - if (type === '[object Date]') { - return 'date'; - } - if (type === '[object Arguments]') { - return 'arguments'; - } - if (type === '[object Error]') { - return 'error'; + if (typeof options === 'function') { + fn = options; + options = null; } - // buffer - if (isBuffer(val)) { - return 'buffer'; + // allow separator to be defined as a string + if (typeof options === 'string') { + options = { sep: options }; } - // es6: Map, WeakMap, Set, WeakSet - if (type === '[object Set]') { - return 'set'; - } - if (type === '[object WeakSet]') { - return 'weakset'; - } - if (type === '[object Map]') { - return 'map'; - } - if (type === '[object WeakMap]') { - return 'weakmap'; - } - if (type === '[object Symbol]') { - return 'symbol'; - } + var opts = extend({sep: '.'}, options); + var quotes = opts.quotes || ['"', "'", '`']; + var brackets; - // typed arrays - if (type === '[object Int8Array]') { - return 'int8array'; - } - if (type === '[object Uint8Array]') { - return 'uint8array'; - } - if (type === '[object Uint8ClampedArray]') { - return 'uint8clampedarray'; - } - if (type === '[object Int16Array]') { - return 'int16array'; - } - if (type === '[object Uint16Array]') { - return 'uint16array'; - } - if (type === '[object Int32Array]') { - return 'int32array'; - } - if (type === '[object Uint32Array]') { - return 'uint32array'; - } - if (type === '[object Float32Array]') { - return 'float32array'; - } - if (type === '[object Float64Array]') { - return 'float64array'; + if (opts.brackets === true) { + brackets = { + '<': '>', + '(': ')', + '[': ']', + '{': '}' + }; + } else if (opts.brackets) { + brackets = opts.brackets; } - // must be a plain object - return 'object'; -}; - - -/***/ }), -/* 653 */ -/***/ (function(module, exports, __webpack_require__) { + var tokens = []; + var stack = []; + var arr = ['']; + var sep = opts.sep; + var len = str.length; + var idx = -1; + var closeIdx; -"use strict"; + function expected() { + if (brackets && stack.length) { + return brackets[stack[stack.length - 1]]; + } + } + while (++idx < len) { + var ch = str[idx]; + var next = str[idx + 1]; + var tok = { val: ch, idx: idx, arr: arr, str: str }; + tokens.push(tok); -var extend = __webpack_require__(631); -var Snapdragon = __webpack_require__(654); -var compilers = __webpack_require__(633); -var parsers = __webpack_require__(648); -var utils = __webpack_require__(634); + if (ch === '\\') { + tok.val = keepEscaping(opts, str, idx) === true ? (ch + next) : next; + tok.escaped = true; + if (typeof fn === 'function') { + fn(tok); + } + arr[arr.length - 1] += tok.val; + idx++; + continue; + } -/** - * Customize Snapdragon parser and renderer - */ + if (brackets && brackets[ch]) { + stack.push(ch); + var e = expected(); + var i = idx + 1; -function Braces(options) { - this.options = extend({}, options); -} + if (str.indexOf(e, i + 1) !== -1) { + while (stack.length && i < len) { + var s = str[++i]; + if (s === '\\') { + s++; + continue; + } -/** - * Initialize braces - */ + if (quotes.indexOf(s) !== -1) { + i = getClosingQuote(str, s, i + 1); + continue; + } -Braces.prototype.init = function(options) { - if (this.isInitialized) return; - this.isInitialized = true; - var opts = utils.createOptions({}, this.options, options); - this.snapdragon = this.options.snapdragon || new Snapdragon(opts); - this.compiler = this.snapdragon.compiler; - this.parser = this.snapdragon.parser; + e = expected(); + if (stack.length && str.indexOf(e, i + 1) === -1) { + break; + } - compilers(this.snapdragon, opts); - parsers(this.snapdragon, opts); + if (brackets[s]) { + stack.push(s); + continue; + } - /** - * Call Snapdragon `.parse` method. When AST is returned, we check to - * see if any unclosed braces are left on the stack and, if so, we iterate - * over the stack and correct the AST so that compilers are called in the correct - * order and unbalance braces are properly escaped. - */ + if (e === s) { + stack.pop(); + } + } + } - utils.define(this.snapdragon, 'parse', function(pattern, options) { - var parsed = Snapdragon.prototype.parse.apply(this, arguments); - this.parser.ast.input = pattern; + closeIdx = i; + if (closeIdx === -1) { + arr[arr.length - 1] += ch; + continue; + } - var stack = this.parser.stack; - while (stack.length) { - addParent({type: 'brace.close', val: ''}, stack.pop()); + ch = str.slice(idx, closeIdx + 1); + tok.val = ch; + tok.idx = idx = closeIdx; } - function addParent(node, parent) { - utils.define(node, 'parent', parent); - parent.nodes.push(node); - } + if (quotes.indexOf(ch) !== -1) { + closeIdx = getClosingQuote(str, ch, idx + 1); + if (closeIdx === -1) { + arr[arr.length - 1] += ch; + continue; + } - // add non-enumerable parser reference - utils.define(parsed, 'parser', this.parser); - return parsed; - }); -}; + if (keepQuotes(ch, opts) === true) { + ch = str.slice(idx, closeIdx + 1); + } else { + ch = str.slice(idx + 1, closeIdx); + } -/** - * Decorate `.parse` method - */ + tok.val = ch; + tok.idx = idx = closeIdx; + } -Braces.prototype.parse = function(ast, options) { - if (ast && typeof ast === 'object' && ast.nodes) return ast; - this.init(options); - return this.snapdragon.parse(ast, options); -}; + if (typeof fn === 'function') { + fn(tok, tokens); + ch = tok.val; + idx = tok.idx; + } -/** - * Decorate `.compile` method - */ + if (tok.val === sep && tok.split !== false) { + arr.push(''); + continue; + } -Braces.prototype.compile = function(ast, options) { - if (typeof ast === 'string') { - ast = this.parse(ast, options); - } else { - this.init(options); + arr[arr.length - 1] += tok.val; } - return this.snapdragon.compile(ast, options); -}; - -/** - * Expand - */ -Braces.prototype.expand = function(pattern) { - var ast = this.parse(pattern, {expand: true}); - return this.compile(ast, {expand: true}); + return arr; }; -/** - * Optimize - */ - -Braces.prototype.optimize = function(pattern) { - var ast = this.parse(pattern, {optimize: true}); - return this.compile(ast, {optimize: true}); -}; +function getClosingQuote(str, ch, i, brackets) { + var idx = str.indexOf(ch, i); + if (str.charAt(idx - 1) === '\\') { + return getClosingQuote(str, ch, idx + 1); + } + return idx; +} -/** - * Expose `Braces` - */ +function keepQuotes(ch, opts) { + if (opts.keepDoubleQuotes === true && ch === '"') return true; + if (opts.keepSingleQuotes === true && ch === "'") return true; + return opts.keepQuotes; +} -module.exports = Braces; +function keepEscaping(opts, str, idx) { + if (typeof opts.keepEscaping === 'function') { + return opts.keepEscaping(str, idx); + } + return opts.keepEscaping === true || str[idx + 1] === '\\'; +} /***/ }), -/* 654 */ +/* 674 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var Base = __webpack_require__(655); -var define = __webpack_require__(685); -var Compiler = __webpack_require__(696); -var Parser = __webpack_require__(719); -var utils = __webpack_require__(699); -var regexCache = {}; -var cache = {}; - -/** - * Create a new instance of `Snapdragon` with the given `options`. - * - * ```js - * var snapdragon = new Snapdragon(); - * ``` - * - * @param {Object} `options` - * @api public - */ - -function Snapdragon(options) { - Base.call(this, null, options); - this.options = utils.extend({source: 'string'}, this.options); - this.compiler = new Compiler(this.options); - this.parser = new Parser(this.options); +var isExtendable = __webpack_require__(675); +var assignSymbols = __webpack_require__(664); - Object.defineProperty(this, 'compilers', { - get: function() { - return this.compiler.compilers; +module.exports = Object.assign || function(obj/*, objects*/) { + if (obj === null || typeof obj === 'undefined') { + throw new TypeError('Cannot convert undefined or null to object'); + } + if (!isObject(obj)) { + obj = {}; + } + for (var i = 1; i < arguments.length; i++) { + var val = arguments[i]; + if (isString(val)) { + val = toObject(val); } - }); - - Object.defineProperty(this, 'parsers', { - get: function() { - return this.parser.parsers; + if (isObject(val)) { + assign(obj, val); + assignSymbols(obj, val); } - }); + } + return obj; +}; - Object.defineProperty(this, 'regex', { - get: function() { - return this.parser.regex; +function assign(a, b) { + for (var key in b) { + if (hasOwn(b, key)) { + a[key] = b[key]; } - }); + } } -/** - * Inherit Base - */ - -Base.extend(Snapdragon); +function isString(val) { + return (val && typeof val === 'string'); +} -/** - * Add a parser to `snapdragon.parsers` for capturing the given `type` using - * the specified regex or parser function. A function is useful if you need - * to customize how the token is created and/or have access to the parser - * instance to check options, etc. - * - * ```js - * snapdragon - * .capture('slash', /^\//) - * .capture('dot', function() { - * var pos = this.position(); - * var m = this.match(/^\./); - * if (!m) return; - * return pos({ - * type: 'dot', - * val: m[0] - * }); - * }); - * ``` - * @param {String} `type` - * @param {RegExp|Function} `regex` - * @return {Object} Returns the parser instance for chaining - * @api public - */ +function toObject(str) { + var obj = {}; + for (var i in str) { + obj[i] = str[i]; + } + return obj; +} -Snapdragon.prototype.capture = function() { - return this.parser.capture.apply(this.parser, arguments); -}; +function isObject(val) { + return (val && typeof val === 'object') || isExtendable(val); +} /** - * Register a plugin `fn`. - * - * ```js - * var snapdragon = new Snapdgragon([options]); - * snapdragon.use(function() { - * console.log(this); //<= snapdragon instance - * console.log(this.parser); //<= parser instance - * console.log(this.compiler); //<= compiler instance - * }); - * ``` - * @param {Object} `fn` - * @api public + * Returns true if the given `key` is an own property of `obj`. */ -Snapdragon.prototype.use = function(fn) { - fn.call(this, this); - return this; -}; +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} -/** - * Parse the given `str`. - * - * ```js - * var snapdragon = new Snapdgragon([options]); - * // register parsers - * snapdragon.parser.use(function() {}); - * - * // parse - * var ast = snapdragon.parse('foo/bar'); - * console.log(ast); - * ``` - * @param {String} `str` - * @param {Object} `options` Set `options.sourcemap` to true to enable source maps. - * @return {Object} Returns an AST. - * @api public - */ +function isEnum(obj, key) { + return Object.prototype.propertyIsEnumerable.call(obj, key); +} -Snapdragon.prototype.parse = function(str, options) { - this.options = utils.extend({}, this.options, options); - var parsed = this.parser.parse(str, this.options); - // add non-enumerable parser reference - define(parsed, 'parser', this.parser); - return parsed; -}; +/***/ }), +/* 675 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * Compile the given `AST`. - * - * ```js - * var snapdragon = new Snapdgragon([options]); - * // register plugins - * snapdragon.use(function() {}); - * // register parser plugins - * snapdragon.parser.use(function() {}); - * // register compiler plugins - * snapdragon.compiler.use(function() {}); - * - * // parse - * var ast = snapdragon.parse('foo/bar'); +"use strict"; +/*! + * is-extendable * - * // compile - * var res = snapdragon.compile(ast); - * console.log(res.output); - * ``` - * @param {Object} `ast` - * @param {Object} `options` - * @return {Object} Returns an object with an `output` property with the rendered string. - * @api public + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. */ -Snapdragon.prototype.compile = function(ast, options) { - this.options = utils.extend({}, this.options, options); - var compiled = this.compiler.compile(ast, this.options); - - // add non-enumerable compiler reference - define(compiled, 'compiler', this.compiler); - return compiled; -}; - -/** - * Expose `Snapdragon` - */ -module.exports = Snapdragon; -/** - * Expose `Parser` and `Compiler` - */ +var isPlainObject = __webpack_require__(663); -module.exports.Compiler = Compiler; -module.exports.Parser = Parser; +module.exports = function isExtendable(val) { + return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); +}; /***/ }), -/* 655 */ +/* 676 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; - - -var util = __webpack_require__(234); -var define = __webpack_require__(656); -var CacheBase = __webpack_require__(657); -var Emitter = __webpack_require__(658); -var isObject = __webpack_require__(618); -var merge = __webpack_require__(679); -var pascal = __webpack_require__(682); -var cu = __webpack_require__(683); - -/** - * Optionally define a custom `cache` namespace to use. +/*! + * arr-flatten + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. */ -function namespace(name) { - var Cache = name ? CacheBase.namespace(name) : CacheBase; - var fns = []; - - /** - * Create an instance of `Base` with the given `config` and `options`. - * - * ```js - * // initialize with `config` and `options` - * var app = new Base({isApp: true}, {abc: true}); - * app.set('foo', 'bar'); - * - * // values defined with the given `config` object will be on the root of the instance - * console.log(app.baz); //=> undefined - * console.log(app.foo); //=> 'bar' - * // or use `.get` - * console.log(app.get('isApp')); //=> true - * console.log(app.get('foo')); //=> 'bar' - * - * // values defined with the given `options` object will be on `app.options - * console.log(app.options.abc); //=> true - * ``` - * - * @param {Object} `config` If supplied, this object is passed to [cache-base][] to merge onto the the instance upon instantiation. - * @param {Object} `options` If supplied, this object is used to initialize the `base.options` object. - * @api public - */ - - function Base(config, options) { - if (!(this instanceof Base)) { - return new Base(config, options); - } - Cache.call(this, config); - this.is('base'); - this.initBase(config, options); - } - - /** - * Inherit cache-base - */ - - util.inherits(Base, Cache); - /** - * Add static emitter methods - */ - Emitter(Base); +module.exports = function (arr) { + return flat(arr, []); +}; - /** - * Initialize `Base` defaults with the given `config` object - */ +function flat(arr, res) { + var i = 0, cur; + var len = arr.length; + for (; i < len; i++) { + cur = arr[i]; + Array.isArray(cur) ? flat(cur, res) : res.push(cur); + } + return res; +} - Base.prototype.initBase = function(config, options) { - this.options = merge({}, this.options, options); - this.cache = this.cache || {}; - this.define('registered', {}); - if (name) this[name] = {}; - // make `app._callbacks` non-enumerable - this.define('_callbacks', this._callbacks); - if (isObject(config)) { - this.visit('set', config); - } - Base.run(this, 'use', fns); - }; +/***/ }), +/* 677 */ +/***/ (function(module, exports, __webpack_require__) { - /** - * Set the given `name` on `app._name` and `app.is*` properties. Used for doing - * lookups in plugins. - * - * ```js - * app.is('foo'); - * console.log(app._name); - * //=> 'foo' - * console.log(app.isFoo); - * //=> true - * app.is('bar'); - * console.log(app.isFoo); - * //=> true - * console.log(app.isBar); - * //=> true - * console.log(app._name); - * //=> 'bar' - * ``` - * @name .is - * @param {String} `name` - * @return {Boolean} - * @api public - */ +"use strict"; +/*! + * fill-range + * + * Copyright (c) 2014-2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ - Base.prototype.is = function(name) { - if (typeof name !== 'string') { - throw new TypeError('expected name to be a string'); - } - this.define('is' + pascal(name), true); - this.define('_name', name); - this.define('_appname', name); - return this; - }; - /** - * Returns true if a plugin has already been registered on an instance. - * - * Plugin implementors are encouraged to use this first thing in a plugin - * to prevent the plugin from being called more than once on the same - * instance. - * - * ```js - * var base = new Base(); - * base.use(function(app) { - * if (app.isRegistered('myPlugin')) return; - * // do stuff to `app` - * }); - * - * // to also record the plugin as being registered - * base.use(function(app) { - * if (app.isRegistered('myPlugin', true)) return; - * // do stuff to `app` - * }); - * ``` - * @name .isRegistered - * @emits `plugin` Emits the name of the plugin being registered. Useful for unit tests, to ensure plugins are only registered once. - * @param {String} `name` The plugin name. - * @param {Boolean} `register` If the plugin if not already registered, to record it as being registered pass `true` as the second argument. - * @return {Boolean} Returns true if a plugin is already registered. - * @api public - */ - Base.prototype.isRegistered = function(name, register) { - if (this.registered.hasOwnProperty(name)) { - return true; - } - if (register !== false) { - this.registered[name] = true; - this.emit('plugin', name); - } - return false; - }; +var util = __webpack_require__(234); +var isNumber = __webpack_require__(678); +var extend = __webpack_require__(681); +var repeat = __webpack_require__(683); +var toRegex = __webpack_require__(684); - /** - * Define a plugin function to be called immediately upon init. Plugins are chainable - * and expose the following arguments to the plugin function: - * - * - `app`: the current instance of `Base` - * - `base`: the [first ancestor instance](#base) of `Base` - * - * ```js - * var app = new Base() - * .use(foo) - * .use(bar) - * .use(baz) - * ``` - * @name .use - * @param {Function} `fn` plugin function to call - * @return {Object} Returns the item instance for chaining. - * @api public - */ +/** + * Return a range of numbers or letters. + * + * @param {String} `start` Start of the range + * @param {String} `stop` End of the range + * @param {String} `step` Increment or decrement to use. + * @param {Function} `fn` Custom function to modify each element in the range. + * @return {Array} + */ - Base.prototype.use = function(fn) { - fn.call(this, this); - return this; - }; +function fillRange(start, stop, step, options) { + if (typeof start === 'undefined') { + return []; + } - /** - * The `.define` method is used for adding non-enumerable property on the instance. - * Dot-notation is **not supported** with `define`. - * - * ```js - * // arbitrary `render` function using lodash `template` - * app.define('render', function(str, locals) { - * return _.template(str)(locals); - * }); - * ``` - * @name .define - * @param {String} `key` The name of the property to define. - * @param {any} `value` - * @return {Object} Returns the instance for chaining. - * @api public - */ + if (typeof stop === 'undefined' || start === stop) { + // special case, for handling negative zero + var isString = typeof start === 'string'; + if (isNumber(start) && !toNumber(start)) { + return [isString ? '0' : 0]; + } + return [start]; + } - Base.prototype.define = function(key, val) { - if (isObject(key)) { - return this.visit('define', key); + if (typeof step !== 'number' && typeof step !== 'string') { + options = step; + step = undefined; + } + + if (typeof options === 'function') { + options = { transform: options }; + } + + var opts = extend({step: step}, options); + if (opts.step && !isValidNumber(opts.step)) { + if (opts.strictRanges === true) { + throw new TypeError('expected options.step to be a number'); } - define(this, key, val); - return this; - }; + return []; + } - /** - * Mix property `key` onto the Base prototype. If base is inherited using - * `Base.extend` this method will be overridden by a new `mixin` method that will - * only add properties to the prototype of the inheriting application. - * - * ```js - * app.mixin('foo', function() { - * // do stuff - * }); - * ``` - * @name .mixin - * @param {String} `key` - * @param {Object|Array} `val` - * @return {Object} Returns the `base` instance for chaining. - * @api public - */ + opts.isNumber = isValidNumber(start) && isValidNumber(stop); + if (!opts.isNumber && !isValid(start, stop)) { + if (opts.strictRanges === true) { + throw new RangeError('invalid range arguments: ' + util.inspect([start, stop])); + } + return []; + } - Base.prototype.mixin = function(key, val) { - Base.prototype[key] = val; - return this; - }; + opts.isPadded = isPadded(start) || isPadded(stop); + opts.toString = opts.stringify + || typeof opts.step === 'string' + || typeof start === 'string' + || typeof stop === 'string' + || !opts.isNumber; - /** - * Non-enumberable mixin array, used by the static [Base.mixin]() method. - */ + if (opts.isPadded) { + opts.maxLength = Math.max(String(start).length, String(stop).length); + } - Base.prototype.mixins = Base.prototype.mixins || []; + // support legacy minimatch/fill-range options + if (typeof opts.optimize === 'boolean') opts.toRegex = opts.optimize; + if (typeof opts.makeRe === 'boolean') opts.toRegex = opts.makeRe; + return expand(start, stop, opts); +} - /** - * Getter/setter used when creating nested instances of `Base`, for storing a reference - * to the first ancestor instance. This works by setting an instance of `Base` on the `parent` - * property of a "child" instance. The `base` property defaults to the current instance if - * no `parent` property is defined. - * - * ```js - * // create an instance of `Base`, this is our first ("base") instance - * var first = new Base(); - * first.foo = 'bar'; // arbitrary property, to make it easier to see what's happening later - * - * // create another instance - * var second = new Base(); - * // create a reference to the first instance (`first`) - * second.parent = first; - * - * // create another instance - * var third = new Base(); - * // create a reference to the previous instance (`second`) - * // repeat this pattern every time a "child" instance is created - * third.parent = second; - * - * // we can always access the first instance using the `base` property - * console.log(first.base.foo); - * //=> 'bar' - * console.log(second.base.foo); - * //=> 'bar' - * console.log(third.base.foo); - * //=> 'bar' - * // and now you know how to get to third base ;) - * ``` - * @name .base - * @api public - */ +function expand(start, stop, options) { + var a = options.isNumber ? toNumber(start) : start.charCodeAt(0); + var b = options.isNumber ? toNumber(stop) : stop.charCodeAt(0); - Object.defineProperty(Base.prototype, 'base', { - configurable: true, - get: function() { - return this.parent ? this.parent.base : this; + var step = Math.abs(toNumber(options.step)) || 1; + if (options.toRegex && step === 1) { + return toRange(a, b, start, stop, options); + } + + var zero = {greater: [], lesser: []}; + var asc = a < b; + var arr = new Array(Math.round((asc ? b - a : a - b) / step)); + var idx = 0; + + while (asc ? a <= b : a >= b) { + var val = options.isNumber ? a : String.fromCharCode(a); + if (options.toRegex && (val >= 0 || !options.isNumber)) { + zero.greater.push(val); + } else { + zero.lesser.push(Math.abs(val)); } - }); - /** - * Static method for adding global plugin functions that will - * be added to an instance when created. - * - * ```js - * Base.use(function(app) { - * app.foo = 'bar'; - * }); - * var app = new Base(); - * console.log(app.foo); - * //=> 'bar' - * ``` - * @name #use - * @param {Function} `fn` Plugin function to use on each instance. - * @return {Object} Returns the `Base` constructor for chaining - * @api public - */ + if (options.isPadded) { + val = zeros(val, options); + } - define(Base, 'use', function(fn) { - fns.push(fn); - return Base; - }); + if (options.toString) { + val = String(val); + } - /** - * Run an array of functions by passing each function - * to a method on the given object specified by the given property. - * - * @param {Object} `obj` Object containing method to use. - * @param {String} `prop` Name of the method on the object to use. - * @param {Array} `arr` Array of functions to pass to the method. - */ + if (typeof options.transform === 'function') { + arr[idx++] = options.transform(val, a, b, step, idx, arr, options); + } else { + arr[idx++] = val; + } - define(Base, 'run', function(obj, prop, arr) { - var len = arr.length, i = 0; - while (len--) { - obj[prop](arr[i++]); + if (asc) { + a += step; + } else { + a -= step; } - return Base; - }); + } - /** - * Static method for inheriting the prototype and static methods of the `Base` class. - * This method greatly simplifies the process of creating inheritance-based applications. - * See [static-extend][] for more details. - * - * ```js - * var extend = cu.extend(Parent); - * Parent.extend(Child); - * - * // optional methods - * Parent.extend(Child, { - * foo: function() {}, - * bar: function() {} - * }); - * ``` - * @name #extend - * @param {Function} `Ctor` constructor to extend - * @param {Object} `methods` Optional prototype properties to mix in. - * @return {Object} Returns the `Base` constructor for chaining - * @api public - */ + if (options.toRegex === true) { + return toSequence(arr, zero, options); + } + return arr; +} - define(Base, 'extend', cu.extend(Base, function(Ctor, Parent) { - Ctor.prototype.mixins = Ctor.prototype.mixins || []; +function toRange(a, b, start, stop, options) { + if (options.isPadded) { + return toRegex(start, stop, options); + } - define(Ctor, 'mixin', function(fn) { - var mixin = fn(Ctor.prototype, Ctor); - if (typeof mixin === 'function') { - Ctor.prototype.mixins.push(mixin); - } - return Ctor; - }); + if (options.isNumber) { + return toRegex(Math.min(a, b), Math.max(a, b), options); + } - define(Ctor, 'mixins', function(Child) { - Base.run(Child, 'mixin', Ctor.prototype.mixins); - return Ctor; - }); + var start = String.fromCharCode(Math.min(a, b)); + var stop = String.fromCharCode(Math.max(a, b)); + return '[' + start + '-' + stop + ']'; +} - Ctor.prototype.mixin = function(key, value) { - Ctor.prototype[key] = value; - return this; - }; - return Base; - })); +function toSequence(arr, zeros, options) { + var greater = '', lesser = ''; + if (zeros.greater.length) { + greater = zeros.greater.join('|'); + } + if (zeros.lesser.length) { + lesser = '-(' + zeros.lesser.join('|') + ')'; + } + var res = greater && lesser + ? greater + '|' + lesser + : greater || lesser; - /** - * Used for adding methods to the `Base` prototype, and/or to the prototype of child instances. - * When a mixin function returns a function, the returned function is pushed onto the `.mixins` - * array, making it available to be used on inheriting classes whenever `Base.mixins()` is - * called (e.g. `Base.mixins(Child)`). - * - * ```js - * Base.mixin(function(proto) { - * proto.foo = function(msg) { - * return 'foo ' + msg; - * }; - * }); - * ``` - * @name #mixin - * @param {Function} `fn` Function to call - * @return {Object} Returns the `Base` constructor for chaining - * @api public - */ + if (options.capture) { + return '(' + res + ')'; + } + return res; +} - define(Base, 'mixin', function(fn) { - var mixin = fn(Base.prototype, Base); - if (typeof mixin === 'function') { - Base.prototype.mixins.push(mixin); +function zeros(val, options) { + if (options.isPadded) { + var str = String(val); + var len = str.length; + var dash = ''; + if (str.charAt(0) === '-') { + dash = '-'; + str = str.slice(1); } - return Base; - }); - - /** - * Static method for running global mixin functions against a child constructor. - * Mixins must be registered before calling this method. - * - * ```js - * Base.extend(Child); - * Base.mixins(Child); - * ``` - * @name #mixins - * @param {Function} `Child` Constructor function of a child class - * @return {Object} Returns the `Base` constructor for chaining - * @api public - */ + var diff = options.maxLength - len; + var pad = repeat('0', diff); + val = (dash + pad + str); + } + if (options.stringify) { + return String(val); + } + return val; +} - define(Base, 'mixins', function(Child) { - Base.run(Child, 'mixin', Base.prototype.mixins); - return Base; - }); +function toNumber(val) { + return Number(val) || 0; +} - /** - * Similar to `util.inherit`, but copies all static properties, prototype properties, and - * getters/setters from `Provider` to `Receiver`. See [class-utils][]{#inherit} for more details. - * - * ```js - * Base.inherit(Foo, Bar); - * ``` - * @name #inherit - * @param {Function} `Receiver` Receiving (child) constructor - * @param {Function} `Provider` Providing (parent) constructor - * @return {Object} Returns the `Base` constructor for chaining - * @api public - */ +function isPadded(str) { + return /^-?0\d/.test(str); +} - define(Base, 'inherit', cu.inherit); - define(Base, 'bubble', cu.bubble); - return Base; +function isValid(min, max) { + return (isValidNumber(min) || isValidLetter(min)) + && (isValidNumber(max) || isValidLetter(max)); } -/** - * Expose `Base` with default settings - */ +function isValidLetter(ch) { + return typeof ch === 'string' && ch.length === 1 && /^\w+$/.test(ch); +} -module.exports = namespace(); +function isValidNumber(n) { + return isNumber(n) && !/\./.test(n); +} /** - * Allow users to define a namespace + * Expose `fillRange` + * @type {Function} */ -module.exports.namespace = namespace; +module.exports = fillRange; /***/ }), -/* 656 */ +/* 678 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /*! - * define-property + * is-number * - * Copyright (c) 2015, 2017, Jon Schlinkert. - * Released under the MIT License. + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. */ -var isDescriptor = __webpack_require__(619); - -module.exports = function defineProperty(obj, prop, val) { - if (typeof obj !== 'object' && typeof obj !== 'function') { - throw new TypeError('expected an object or function.'); - } +var typeOf = __webpack_require__(679); - if (typeof prop !== 'string') { - throw new TypeError('expected `prop` to be a string.'); - } +module.exports = function isNumber(num) { + var type = typeOf(num); - if (isDescriptor(val) && ('set' in val || 'get' in val)) { - return Object.defineProperty(obj, prop, val); + if (type === 'string') { + if (!num.trim()) return false; + } else if (type !== 'number') { + return false; } - return Object.defineProperty(obj, prop, { - configurable: true, - enumerable: false, - writable: true, - value: val - }); + return (num - num + 1) >= 0; }; /***/ }), -/* 657 */ +/* 679 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; - - -var isObject = __webpack_require__(618); -var Emitter = __webpack_require__(658); -var visit = __webpack_require__(659); -var toPath = __webpack_require__(662); -var union = __webpack_require__(664); -var del = __webpack_require__(670); -var get = __webpack_require__(667); -var has = __webpack_require__(675); -var set = __webpack_require__(678); +var isBuffer = __webpack_require__(680); +var toString = Object.prototype.toString; /** - * Create a `Cache` constructor that when instantiated will - * store values on the given `prop`. - * - * ```js - * var Cache = require('cache-base').namespace('data'); - * var cache = new Cache(); + * Get the native `typeof` a value. * - * cache.set('foo', 'bar'); - * //=> {data: {foo: 'bar'}} - * ``` - * @param {String} `prop` The property name to use for storing values. - * @return {Function} Returns a custom `Cache` constructor - * @api public + * @param {*} `val` + * @return {*} Native javascript type */ -function namespace(prop) { +module.exports = function kindOf(val) { + // primitivies + if (typeof val === 'undefined') { + return 'undefined'; + } + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (typeof val === 'string' || val instanceof String) { + return 'string'; + } + if (typeof val === 'number' || val instanceof Number) { + return 'number'; + } - /** - * Create a new `Cache`. Internally the `Cache` constructor is created using - * the `namespace` function, with `cache` defined as the storage object. - * - * ```js - * var app = new Cache(); - * ``` - * @param {Object} `cache` Optionally pass an object to initialize with. - * @constructor - * @api public - */ + // functions + if (typeof val === 'function' || val instanceof Function) { + return 'function'; + } - function Cache(cache) { - if (prop) { - this[prop] = {}; - } - if (cache) { - this.set(cache); - } + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; + } + + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; + } + + // other objects + var type = toString.call(val); + + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; + } + + // buffer + if (isBuffer(val)) { + return 'buffer'; + } + + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; + } + + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; } - /** - * Inherit Emitter - */ - - Emitter(Cache.prototype); + // must be a plain object + return 'object'; +}; - /** - * Assign `value` to `key`. Also emits `set` with - * the key and value. - * - * ```js - * app.on('set', function(key, val) { - * // do something when `set` is emitted - * }); - * - * app.set(key, value); - * - * // also takes an object or array - * app.set({name: 'Halle'}); - * app.set([{foo: 'bar'}, {baz: 'quux'}]); - * console.log(app); - * //=> {name: 'Halle', foo: 'bar', baz: 'quux'} - * ``` - * - * @name .set - * @emits `set` with `key` and `value` as arguments. - * @param {String} `key` - * @param {any} `value` - * @return {Object} Returns the instance for chaining. - * @api public - */ - Cache.prototype.set = function(key, val) { - if (Array.isArray(key) && arguments.length === 2) { - key = toPath(key); - } - if (isObject(key) || Array.isArray(key)) { - this.visit('set', key); - } else { - set(prop ? this[prop] : this, key, val); - this.emit('set', key, val); - } - return this; - }; +/***/ }), +/* 680 */ +/***/ (function(module, exports) { - /** - * Union `array` to `key`. Also emits `set` with - * the key and value. - * - * ```js - * app.union('a.b', ['foo']); - * app.union('a.b', ['bar']); - * console.log(app.get('a')); - * //=> {b: ['foo', 'bar']} - * ``` - * @name .union - * @param {String} `key` - * @param {any} `value` - * @return {Object} Returns the instance for chaining. - * @api public - */ +/*! + * Determine if an object is a Buffer + * + * @author Feross Aboukhadijeh + * @license MIT + */ - Cache.prototype.union = function(key, val) { - if (Array.isArray(key) && arguments.length === 2) { - key = toPath(key); - } - var ctx = prop ? this[prop] : this; - union(ctx, key, arrayify(val)); - this.emit('union', val); - return this; - }; +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +module.exports = function (obj) { + return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) +} - /** - * Return the value of `key`. Dot notation may be used - * to get [nested property values][get-value]. - * - * ```js - * app.set('a.b.c', 'd'); - * app.get('a.b'); - * //=> {c: 'd'} - * - * app.get(['a', 'b']); - * //=> {c: 'd'} - * ``` - * - * @name .get - * @emits `get` with `key` and `value` as arguments. - * @param {String} `key` The name of the property to get. Dot-notation may be used. - * @return {any} Returns the value of `key` - * @api public - */ +function isBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} - Cache.prototype.get = function(key) { - key = toPath(arguments); +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) +} - var ctx = prop ? this[prop] : this; - var val = get(ctx, key); - this.emit('get', key, val); - return val; - }; +/***/ }), +/* 681 */ +/***/ (function(module, exports, __webpack_require__) { - /** - * Return true if app has a stored value for `key`, - * false only if value is `undefined`. - * - * ```js - * app.set('foo', 'bar'); - * app.has('foo'); - * //=> true - * ``` - * - * @name .has - * @emits `has` with `key` and true or false as arguments. - * @param {String} `key` - * @return {Boolean} - * @api public - */ +"use strict"; - Cache.prototype.has = function(key) { - key = toPath(arguments); - var ctx = prop ? this[prop] : this; - var val = get(ctx, key); +var isObject = __webpack_require__(682); - var has = typeof val !== 'undefined'; - this.emit('has', key, has); - return has; - }; +module.exports = function extend(o/*, objects*/) { + if (!isObject(o)) { o = {}; } - /** - * Delete one or more properties from the instance. - * - * ```js - * app.del(); // delete all - * // or - * app.del('foo'); - * // or - * app.del(['foo', 'bar']); - * ``` - * @name .del - * @emits `del` with the `key` as the only argument. - * @param {String|Array} `key` Property name or array of property names. - * @return {Object} Returns the instance for chaining. - * @api public - */ + var len = arguments.length; + for (var i = 1; i < len; i++) { + var obj = arguments[i]; - Cache.prototype.del = function(key) { - if (Array.isArray(key)) { - this.visit('del', key); - } else { - del(prop ? this[prop] : this, key); - this.emit('del', key); + if (isObject(obj)) { + assign(o, obj); } - return this; - }; - - /** - * Reset the entire cache to an empty object. - * - * ```js - * app.clear(); - * ``` - * @api public - */ + } + return o; +}; - Cache.prototype.clear = function() { - if (prop) { - this[prop] = {}; +function assign(a, b) { + for (var key in b) { + if (hasOwn(b, key)) { + a[key] = b[key]; } - }; - - /** - * Visit `method` over the properties in the given object, or map - * visit over the object-elements in an array. - * - * @name .visit - * @param {String} `method` The name of the `base` method to call. - * @param {Object|Array} `val` The object or array to iterate over. - * @return {Object} Returns the instance for chaining. - * @api public - */ - - Cache.prototype.visit = function(method, val) { - visit(this, method, val); - return this; - }; - - return Cache; + } } /** - * Cast val to an array + * Returns true if the given `key` is an own property of `obj`. */ -function arrayify(val) { - return val ? (Array.isArray(val) ? val : [val]) : []; +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); } -/** - * Expose `Cache` - */ -module.exports = namespace(); +/***/ }), +/* 682 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * Expose `Cache.namespace` +"use strict"; +/*! + * is-extendable + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. */ -module.exports.namespace = namespace; - -/***/ }), -/* 658 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * Expose `Emitter`. - */ - -if (true) { - module.exports = Emitter; -} - -/** - * Initialize a new `Emitter`. - * - * @api public - */ - -function Emitter(obj) { - if (obj) return mixin(obj); -}; - -/** - * Mixin the emitter properties. - * - * @param {Object} obj - * @return {Object} - * @api private - */ - -function mixin(obj) { - for (var key in Emitter.prototype) { - obj[key] = Emitter.prototype[key]; - } - return obj; -} - -/** - * Listen on the given `event` with `fn`. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - -Emitter.prototype.on = -Emitter.prototype.addEventListener = function(event, fn){ - this._callbacks = this._callbacks || {}; - (this._callbacks['$' + event] = this._callbacks['$' + event] || []) - .push(fn); - return this; -}; - -/** - * Adds an `event` listener that will be invoked a single - * time then automatically removed. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - -Emitter.prototype.once = function(event, fn){ - function on() { - this.off(event, on); - fn.apply(this, arguments); - } - - on.fn = fn; - this.on(event, on); - return this; -}; - -/** - * Remove the given callback for `event` or all - * registered callbacks. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - -Emitter.prototype.off = -Emitter.prototype.removeListener = -Emitter.prototype.removeAllListeners = -Emitter.prototype.removeEventListener = function(event, fn){ - this._callbacks = this._callbacks || {}; - - // all - if (0 == arguments.length) { - this._callbacks = {}; - return this; - } - - // specific event - var callbacks = this._callbacks['$' + event]; - if (!callbacks) return this; - - // remove all handlers - if (1 == arguments.length) { - delete this._callbacks['$' + event]; - return this; - } - - // remove specific handler - var cb; - for (var i = 0; i < callbacks.length; i++) { - cb = callbacks[i]; - if (cb === fn || cb.fn === fn) { - callbacks.splice(i, 1); - break; - } - } - return this; -}; - -/** - * Emit `event` with the given args. - * - * @param {String} event - * @param {Mixed} ... - * @return {Emitter} - */ - -Emitter.prototype.emit = function(event){ - this._callbacks = this._callbacks || {}; - var args = [].slice.call(arguments, 1) - , callbacks = this._callbacks['$' + event]; - - if (callbacks) { - callbacks = callbacks.slice(0); - for (var i = 0, len = callbacks.length; i < len; ++i) { - callbacks[i].apply(this, args); - } - } - - return this; -}; - -/** - * Return array of callbacks for `event`. - * - * @param {String} event - * @return {Array} - * @api public - */ - -Emitter.prototype.listeners = function(event){ - this._callbacks = this._callbacks || {}; - return this._callbacks['$' + event] || []; -}; - -/** - * Check if this emitter has `event` handlers. - * - * @param {String} event - * @return {Boolean} - * @api public - */ - -Emitter.prototype.hasListeners = function(event){ - return !! this.listeners(event).length; -}; +module.exports = function isExtendable(val) { + return typeof val !== 'undefined' && val !== null + && (typeof val === 'object' || typeof val === 'function'); +}; /***/ }), -/* 659 */ +/* 683 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /*! - * collection-visit + * repeat-string * - * Copyright (c) 2015, 2017, Jon Schlinkert. - * Released under the MIT License. + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. */ -var visit = __webpack_require__(660); -var mapVisit = __webpack_require__(661); +/** + * Results cache + */ -module.exports = function(collection, method, val) { - var result; +var res = ''; +var cache; - if (typeof val === 'string' && (method in collection)) { - var args = [].slice.call(arguments, 2); - result = collection[method].apply(collection, args); - } else if (Array.isArray(val)) { - result = mapVisit.apply(null, arguments); - } else { - result = visit.apply(null, arguments); +/** + * Expose `repeat` + */ + +module.exports = repeat; + +/** + * Repeat the given `string` the specified `number` + * of times. + * + * **Example:** + * + * ```js + * var repeat = require('repeat-string'); + * repeat('A', 5); + * //=> AAAAA + * ``` + * + * @param {String} `string` The string to repeat + * @param {Number} `number` The number of times to repeat the string + * @return {String} Repeated string + * @api public + */ + +function repeat(str, num) { + if (typeof str !== 'string') { + throw new TypeError('expected a string'); } - if (typeof result !== 'undefined') { - return result; + // cover common, quick use cases + if (num === 1) return str; + if (num === 2) return str + str; + + var max = str.length * num; + if (cache !== str || typeof cache === 'undefined') { + cache = str; + res = ''; + } else if (res.length >= max) { + return res.substr(0, max); } - return collection; -}; + while (max > res.length && num > 1) { + if (num & 1) { + res += str; + } + + num >>= 1; + str += str; + } + + res += str; + res = res.substr(0, max); + return res; +} /***/ }), -/* 660 */ +/* 684 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /*! - * object-visit + * to-regex-range * * Copyright (c) 2015, 2017, Jon Schlinkert. * Released under the MIT License. @@ -68895,1933 +67696,2253 @@ module.exports = function(collection, method, val) { -var isObject = __webpack_require__(618); +var repeat = __webpack_require__(683); +var isNumber = __webpack_require__(678); +var cache = {}; + +function toRegexRange(min, max, options) { + if (isNumber(min) === false) { + throw new RangeError('toRegexRange: first argument is invalid.'); + } + + if (typeof max === 'undefined' || min === max) { + return String(min); + } + + if (isNumber(max) === false) { + throw new RangeError('toRegexRange: second argument is invalid.'); + } + + options = options || {}; + var relax = String(options.relaxZeros); + var shorthand = String(options.shorthand); + var capture = String(options.capture); + var key = min + ':' + max + '=' + relax + shorthand + capture; + if (cache.hasOwnProperty(key)) { + return cache[key].result; + } + + var a = Math.min(min, max); + var b = Math.max(min, max); + + if (Math.abs(a - b) === 1) { + var result = min + '|' + max; + if (options.capture) { + return '(' + result + ')'; + } + return result; + } + + var isPadded = padding(min) || padding(max); + var positives = []; + var negatives = []; -module.exports = function visit(thisArg, method, target, val) { - if (!isObject(thisArg) && typeof thisArg !== 'function') { - throw new Error('object-visit expects `thisArg` to be an object.'); + var tok = {min: min, max: max, a: a, b: b}; + if (isPadded) { + tok.isPadded = isPadded; + tok.maxLen = String(tok.max).length; } - if (typeof method !== 'string') { - throw new Error('object-visit expects `method` name to be a string'); + if (a < 0) { + var newMin = b < 0 ? Math.abs(b) : 1; + var newMax = Math.abs(a); + negatives = splitToPatterns(newMin, newMax, tok, options); + a = tok.a = 0; } - if (typeof thisArg[method] !== 'function') { - return thisArg; + if (b >= 0) { + positives = splitToPatterns(a, b, tok, options); } - var args = [].slice.call(arguments, 3); - target = target || {}; + tok.negatives = negatives; + tok.positives = positives; + tok.result = siftPatterns(negatives, positives, options); - for (var key in target) { - var arr = [key, target[key]].concat(args); - thisArg[method].apply(thisArg, arr); + if (options.capture && (positives.length + negatives.length) > 1) { + tok.result = '(' + tok.result + ')'; } - return thisArg; -}; + cache[key] = tok; + return tok.result; +} -/***/ }), -/* 661 */ -/***/ (function(module, exports, __webpack_require__) { +function siftPatterns(neg, pos, options) { + var onlyNegative = filterPatterns(neg, pos, '-', false, options) || []; + var onlyPositive = filterPatterns(pos, neg, '', false, options) || []; + var intersected = filterPatterns(neg, pos, '-?', true, options) || []; + var subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); + return subpatterns.join('|'); +} -"use strict"; +function splitToRanges(min, max) { + min = Number(min); + max = Number(max); + var nines = 1; + var stops = [max]; + var stop = +countNines(min, nines); -var util = __webpack_require__(234); -var visit = __webpack_require__(660); + while (min <= stop && stop <= max) { + stops = push(stops, stop); + nines += 1; + stop = +countNines(min, nines); + } + + var zeros = 1; + stop = countZeros(max + 1, zeros) - 1; + + while (min < stop && stop <= max) { + stops = push(stops, stop); + zeros += 1; + stop = countZeros(max + 1, zeros) - 1; + } + + stops.sort(compare); + return stops; +} /** - * Map `visit` over an array of objects. - * - * @param {Object} `collection` The context in which to invoke `method` - * @param {String} `method` Name of the method to call on `collection` - * @param {Object} `arr` Array of objects. + * Convert a range to a regex pattern + * @param {Number} `start` + * @param {Number} `stop` + * @return {String} */ -module.exports = function mapVisit(collection, method, val) { - if (isObject(val)) { - return visit.apply(null, arguments); +function rangeToPattern(start, stop, options) { + if (start === stop) { + return {pattern: String(start), digits: []}; } - if (!Array.isArray(val)) { - throw new TypeError('expected an array: ' + util.inspect(val)); - } + var zipped = zip(String(start), String(stop)); + var len = zipped.length, i = -1; - var args = [].slice.call(arguments, 3); + var pattern = ''; + var digits = 0; + + while (++i < len) { + var numbers = zipped[i]; + var startDigit = numbers[0]; + var stopDigit = numbers[1]; + + if (startDigit === stopDigit) { + pattern += startDigit; + + } else if (startDigit !== '0' || stopDigit !== '9') { + pattern += toCharacterClass(startDigit, stopDigit); - for (var i = 0; i < val.length; i++) { - var ele = val[i]; - if (isObject(ele)) { - visit.apply(null, [collection, method, ele].concat(args)); } else { - collection[method].apply(collection, [ele].concat(args)); + digits += 1; } } -}; -function isObject(val) { - return val && (typeof val === 'function' || (!Array.isArray(val) && typeof val === 'object')); -} + if (digits) { + pattern += options.shorthand ? '\\d' : '[0-9]'; + } + return { pattern: pattern, digits: [digits] }; +} -/***/ }), -/* 662 */ -/***/ (function(module, exports, __webpack_require__) { +function splitToPatterns(min, max, tok, options) { + var ranges = splitToRanges(min, max); + var len = ranges.length; + var idx = -1; -"use strict"; -/*! - * to-object-path - * - * Copyright (c) 2015, Jon Schlinkert. - * Licensed under the MIT License. - */ + var tokens = []; + var start = min; + var prev; + while (++idx < len) { + var range = ranges[idx]; + var obj = rangeToPattern(start, range, options); + var zeros = ''; + if (!tok.isPadded && prev && prev.pattern === obj.pattern) { + if (prev.digits.length > 1) { + prev.digits.pop(); + } + prev.digits.push(obj.digits[0]); + prev.string = prev.pattern + toQuantifier(prev.digits); + start = range + 1; + continue; + } -var typeOf = __webpack_require__(663); + if (tok.isPadded) { + zeros = padZeros(range, tok); + } -module.exports = function toPath(args) { - if (typeOf(args) !== 'arguments') { - args = arguments; + obj.string = zeros + obj.pattern + toQuantifier(obj.digits); + tokens.push(obj); + start = range + 1; + prev = obj; } - return filter(args).join('.'); -}; -function filter(arr) { - var len = arr.length; - var idx = -1; + return tokens; +} + +function filterPatterns(arr, comparison, prefix, intersection, options) { var res = []; - while (++idx < len) { - var ele = arr[idx]; - if (typeOf(ele) === 'arguments' || Array.isArray(ele)) { - res.push.apply(res, filter(ele)); - } else if (typeof ele === 'string') { - res.push(ele); + for (var i = 0; i < arr.length; i++) { + var tok = arr[i]; + var ele = tok.string; + + if (options.relaxZeros !== false) { + if (prefix === '-' && ele.charAt(0) === '0') { + if (ele.charAt(1) === '{') { + ele = '0*' + ele.replace(/^0\{\d+\}/, ''); + } else { + ele = '0*' + ele.slice(1); + } + } + } + + if (!intersection && !contains(comparison, 'string', ele)) { + res.push(prefix + ele); + } + + if (intersection && contains(comparison, 'string', ele)) { + res.push(prefix + ele); } } return res; } - -/***/ }), -/* 663 */ -/***/ (function(module, exports, __webpack_require__) { - -var isBuffer = __webpack_require__(642); -var toString = Object.prototype.toString; - /** - * Get the native `typeof` a value. - * - * @param {*} `val` - * @return {*} Native javascript type + * Zip strings (`for in` can be used on string characters) */ -module.exports = function kindOf(val) { - // primitivies - if (typeof val === 'undefined') { - return 'undefined'; - } - if (val === null) { - return 'null'; - } - if (val === true || val === false || val instanceof Boolean) { - return 'boolean'; - } - if (typeof val === 'string' || val instanceof String) { - return 'string'; - } - if (typeof val === 'number' || val instanceof Number) { - return 'number'; - } +function zip(a, b) { + var arr = []; + for (var ch in a) arr.push([a[ch], b[ch]]); + return arr; +} - // functions - if (typeof val === 'function' || val instanceof Function) { - return 'function'; - } +function compare(a, b) { + return a > b ? 1 : b > a ? -1 : 0; +} - // array - if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { - return 'array'; - } +function push(arr, ele) { + if (arr.indexOf(ele) === -1) arr.push(ele); + return arr; +} - // check for instances of RegExp and Date before calling `toString` - if (val instanceof RegExp) { - return 'regexp'; - } - if (val instanceof Date) { - return 'date'; +function contains(arr, key, val) { + for (var i = 0; i < arr.length; i++) { + if (arr[i][key] === val) { + return true; + } } + return false; +} - // other objects - var type = toString.call(val); +function countNines(min, len) { + return String(min).slice(0, -len) + repeat('9', len); +} - if (type === '[object RegExp]') { - return 'regexp'; - } - if (type === '[object Date]') { - return 'date'; - } - if (type === '[object Arguments]') { - return 'arguments'; - } - if (type === '[object Error]') { - return 'error'; - } +function countZeros(integer, zeros) { + return integer - (integer % Math.pow(10, zeros)); +} - // buffer - if (isBuffer(val)) { - return 'buffer'; +function toQuantifier(digits) { + var start = digits[0]; + var stop = digits[1] ? (',' + digits[1]) : ''; + if (!stop && (!start || start === 1)) { + return ''; } + return '{' + start + stop + '}'; +} - // es6: Map, WeakMap, Set, WeakSet - if (type === '[object Set]') { - return 'set'; - } - if (type === '[object WeakSet]') { - return 'weakset'; - } - if (type === '[object Map]') { - return 'map'; - } - if (type === '[object WeakMap]') { - return 'weakmap'; - } - if (type === '[object Symbol]') { - return 'symbol'; - } +function toCharacterClass(a, b) { + return '[' + a + ((b - a === 1) ? '' : '-') + b + ']'; +} - // typed arrays - if (type === '[object Int8Array]') { - return 'int8array'; - } - if (type === '[object Uint8Array]') { - return 'uint8array'; - } - if (type === '[object Uint8ClampedArray]') { - return 'uint8clampedarray'; - } - if (type === '[object Int16Array]') { - return 'int16array'; - } - if (type === '[object Uint16Array]') { - return 'uint16array'; - } - if (type === '[object Int32Array]') { - return 'int32array'; - } - if (type === '[object Uint32Array]') { - return 'uint32array'; - } - if (type === '[object Float32Array]') { - return 'float32array'; - } - if (type === '[object Float64Array]') { - return 'float64array'; +function padding(str) { + return /^-?(0+)\d/.exec(str); +} + +function padZeros(val, tok) { + if (tok.isPadded) { + var diff = Math.abs(tok.maxLen - String(val).length); + switch (diff) { + case 0: + return ''; + case 1: + return '0'; + default: { + return '0{' + diff + '}'; + } + } } + return val; +} - // must be a plain object - return 'object'; -}; +/** + * Expose `toRegexRange` + */ + +module.exports = toRegexRange; /***/ }), -/* 664 */ +/* 685 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +/*! + * repeat-element + * + * Copyright (c) 2015 Jon Schlinkert. + * Licensed under the MIT license. + */ -var isObject = __webpack_require__(665); -var union = __webpack_require__(666); -var get = __webpack_require__(667); -var set = __webpack_require__(668); -module.exports = function unionValue(obj, prop, value) { - if (!isObject(obj)) { - throw new TypeError('union-value expects the first argument to be an object.'); - } +module.exports = function repeat(ele, num) { + var arr = new Array(num); - if (typeof prop !== 'string') { - throw new TypeError('union-value expects `prop` to be a string.'); + for (var i = 0; i < num; i++) { + arr[i] = ele; } - var arr = arrayify(get(obj, prop)); - set(obj, prop, union(arr, arrayify(value))); - return obj; + return arr; }; -function arrayify(val) { - if (val === null || typeof val === 'undefined') { - return []; - } - if (Array.isArray(val)) { - return val; - } - return [val]; -} - /***/ }), -/* 665 */ +/* 686 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/*! - * is-extendable - * - * Copyright (c) 2015, Jon Schlinkert. - * Licensed under the MIT License. + + +var Node = __webpack_require__(687); +var utils = __webpack_require__(672); + +/** + * Braces parsers */ +module.exports = function(braces, options) { + braces.parser + .set('bos', function() { + if (!this.parsed) { + this.ast = this.nodes[0] = new Node(this.ast); + } + }) + /** + * Character parsers + */ -module.exports = function isExtendable(val) { - return typeof val !== 'undefined' && val !== null - && (typeof val === 'object' || typeof val === 'function'); -}; + .set('escape', function() { + var pos = this.position(); + var m = this.match(/^(?:\\(.)|\$\{)/); + if (!m) return; + var prev = this.prev(); + var last = utils.last(prev.nodes); -/***/ }), -/* 666 */ -/***/ (function(module, exports, __webpack_require__) { + var node = pos(new Node({ + type: 'text', + multiplier: 1, + val: m[0] + })); -"use strict"; + if (node.val === '\\\\') { + return node; + } + + if (node.val === '${') { + var str = this.input; + var idx = -1; + var ch; + + while ((ch = str[++idx])) { + this.consume(1); + node.val += ch; + if (ch === '\\') { + node.val += str[++idx]; + continue; + } + if (ch === '}') { + break; + } + } + } + + if (this.options.unescape !== false) { + node.val = node.val.replace(/\\([{}])/g, '$1'); + } + + if (last.val === '"' && this.input.charAt(0) === '"') { + last.val = node.val; + this.consume(1); + return; + } + + return concatNodes.call(this, pos, node, prev, options); + }) + + /** + * Brackets: "[...]" (basic, this is overridden by + * other parsers in more advanced implementations) + */ + + .set('bracket', function() { + var isInside = this.isInside('brace'); + var pos = this.position(); + var m = this.match(/^(?:\[([!^]?)([^\]]{2,}|\]-)(\]|[^*+?]+)|\[)/); + if (!m) return; + + var prev = this.prev(); + var val = m[0]; + var negated = m[1] ? '^' : ''; + var inner = m[2] || ''; + var close = m[3] || ''; + + if (isInside && prev.type === 'brace') { + prev.text = prev.text || ''; + prev.text += val; + } + + var esc = this.input.slice(0, 2); + if (inner === '' && esc === '\\]') { + inner += esc; + this.consume(2); + var str = this.input; + var idx = -1; + var ch; -module.exports = function union(init) { - if (!Array.isArray(init)) { - throw new TypeError('arr-union expects the first argument to be an array.'); - } + while ((ch = str[++idx])) { + this.consume(1); + if (ch === ']') { + close = ch; + break; + } + inner += ch; + } + } - var len = arguments.length; - var i = 0; + return pos(new Node({ + type: 'bracket', + val: val, + escaped: close !== ']', + negated: negated, + inner: inner, + close: close + })); + }) - while (++i < len) { - var arg = arguments[i]; - if (!arg) continue; + /** + * Empty braces (we capture these early to + * speed up processing in the compiler) + */ - if (!Array.isArray(arg)) { - arg = [arg]; - } + .set('multiplier', function() { + var isInside = this.isInside('brace'); + var pos = this.position(); + var m = this.match(/^\{((?:,|\{,+\})+)\}/); + if (!m) return; - for (var j = 0; j < arg.length; j++) { - var ele = arg[j]; + this.multiplier = true; + var prev = this.prev(); + var val = m[0]; - if (init.indexOf(ele) >= 0) { - continue; + if (isInside && prev.type === 'brace') { + prev.text = prev.text || ''; + prev.text += val; } - init.push(ele); - } - } - return init; -}; + var node = pos(new Node({ + type: 'text', + multiplier: 1, + match: m, + val: val + })); -/***/ }), -/* 667 */ -/***/ (function(module, exports) { + return concatNodes.call(this, pos, node, prev, options); + }) -/*! - * get-value - * - * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT License. - */ + /** + * Open + */ -module.exports = function(obj, prop, a, b, c) { - if (!isObject(obj) || !prop) { - return obj; - } + .set('brace.open', function() { + var pos = this.position(); + var m = this.match(/^\{(?!(?:[^\\}]?|,+)\})/); + if (!m) return; - prop = toString(prop); + var prev = this.prev(); + var last = utils.last(prev.nodes); - // allowing for multiple properties to be passed as - // a string or array, but much faster (3-4x) than doing - // `[].slice.call(arguments)` - if (a) prop += '.' + toString(a); - if (b) prop += '.' + toString(b); - if (c) prop += '.' + toString(c); + // if the last parsed character was an extglob character + // we need to _not optimize_ the brace pattern because + // it might be mistaken for an extglob by a downstream parser + if (last && last.val && isExtglobChar(last.val.slice(-1))) { + last.optimize = false; + } - if (prop in obj) { - return obj[prop]; - } + var open = pos(new Node({ + type: 'brace.open', + val: m[0] + })); - var segs = prop.split('.'); - var len = segs.length; - var i = -1; + var node = pos(new Node({ + type: 'brace', + nodes: [] + })); - while (obj && (++i < len)) { - var key = segs[i]; - while (key[key.length - 1] === '\\') { - key = key.slice(0, -1) + '.' + segs[++i]; - } - obj = obj[key]; - } - return obj; -}; + node.push(open); + prev.push(node); + this.push('brace', node); + }) -function isObject(val) { - return val !== null && (typeof val === 'object' || typeof val === 'function'); -} + /** + * Close + */ -function toString(val) { - if (!val) return ''; - if (Array.isArray(val)) { - return val.join('.'); - } - return val; -} + .set('brace.close', function() { + var pos = this.position(); + var m = this.match(/^\}/); + if (!m || !m[0]) return; + var brace = this.pop('brace'); + var node = pos(new Node({ + type: 'brace.close', + val: m[0] + })); -/***/ }), -/* 668 */ -/***/ (function(module, exports, __webpack_require__) { + if (!this.isType(brace, 'brace')) { + if (this.options.strict) { + throw new Error('missing opening "{"'); + } + node.type = 'text'; + node.multiplier = 0; + node.escaped = true; + return node; + } -"use strict"; -/*! - * set-value - * - * Copyright (c) 2014-2015, 2017, Jon Schlinkert. - * Released under the MIT License. - */ + var prev = this.prev(); + var last = utils.last(prev.nodes); + if (last.text) { + var lastNode = utils.last(last.nodes); + if (lastNode.val === ')' && /[!@*?+]\(/.test(last.text)) { + var open = last.nodes[0]; + var text = last.nodes[1]; + if (open.type === 'brace.open' && text && text.type === 'text') { + text.optimize = false; + } + } + } + if (brace.nodes.length > 2) { + var first = brace.nodes[1]; + if (first.type === 'text' && first.val === ',') { + brace.nodes.splice(1, 1); + brace.nodes.push(first); + } + } + brace.push(node); + }) -var split = __webpack_require__(635); -var extend = __webpack_require__(669); -var isPlainObject = __webpack_require__(625); -var isObject = __webpack_require__(665); + /** + * Capture boundary characters + */ -module.exports = function(obj, prop, val) { - if (!isObject(obj)) { - return obj; - } + .set('boundary', function() { + var pos = this.position(); + var m = this.match(/^[$^](?!\{)/); + if (!m) return; + return pos(new Node({ + type: 'text', + val: m[0] + })); + }) - if (Array.isArray(prop)) { - prop = [].concat.apply([], prop).join('.'); - } + /** + * One or zero, non-comma characters wrapped in braces + */ - if (typeof prop !== 'string') { - return obj; - } + .set('nobrace', function() { + var isInside = this.isInside('brace'); + var pos = this.position(); + var m = this.match(/^\{[^,]?\}/); + if (!m) return; - var keys = split(prop, {sep: '.', brackets: true}).filter(isValidKey); - var len = keys.length; - var idx = -1; - var current = obj; + var prev = this.prev(); + var val = m[0]; - while (++idx < len) { - var key = keys[idx]; - if (idx !== len - 1) { - if (!isObject(current[key])) { - current[key] = {}; + if (isInside && prev.type === 'brace') { + prev.text = prev.text || ''; + prev.text += val; } - current = current[key]; - continue; - } - - if (isPlainObject(current[key]) && isPlainObject(val)) { - current[key] = extend({}, current[key], val); - } else { - current[key] = val; - } - } - - return obj; -}; - -function isValidKey(key) { - return key !== '__proto__' && key !== 'constructor' && key !== 'prototype'; -} - -/***/ }), -/* 669 */ -/***/ (function(module, exports, __webpack_require__) { + return pos(new Node({ + type: 'text', + multiplier: 0, + val: val + })); + }) -"use strict"; + /** + * Text + */ + .set('text', function() { + var isInside = this.isInside('brace'); + var pos = this.position(); + var m = this.match(/^((?!\\)[^${}[\]])+/); + if (!m) return; -var isObject = __webpack_require__(665); + var prev = this.prev(); + var val = m[0]; -module.exports = function extend(o/*, objects*/) { - if (!isObject(o)) { o = {}; } + if (isInside && prev.type === 'brace') { + prev.text = prev.text || ''; + prev.text += val; + } - var len = arguments.length; - for (var i = 1; i < len; i++) { - var obj = arguments[i]; + var node = pos(new Node({ + type: 'text', + multiplier: 1, + val: val + })); - if (isObject(obj)) { - assign(o, obj); - } - } - return o; + return concatNodes.call(this, pos, node, prev, options); + }); }; -function assign(a, b) { - for (var key in b) { - if (hasOwn(b, key)) { - a[key] = b[key]; - } - } -} - /** - * Returns true if the given `key` is an own property of `obj`. + * Returns true if the character is an extglob character. */ -function hasOwn(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); +function isExtglobChar(ch) { + return ch === '!' || ch === '@' || ch === '*' || ch === '?' || ch === '+'; } - -/***/ }), -/* 670 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/*! - * unset-value - * - * Copyright (c) 2015, 2017, Jon Schlinkert. - * Released under the MIT License. +/** + * Combine text nodes, and calculate empty sets (`{,,}`) + * @param {Function} `pos` Function to calculate node position + * @param {Object} `node` AST node + * @return {Object} */ +function concatNodes(pos, node, parent, options) { + node.orig = node.val; + var prev = this.prev(); + var last = utils.last(prev.nodes); + var isEscaped = false; + if (node.val.length > 1) { + var a = node.val.charAt(0); + var b = node.val.slice(-1); -var isObject = __webpack_require__(618); -var has = __webpack_require__(671); - -module.exports = function unset(obj, prop) { - if (!isObject(obj)) { - throw new TypeError('expected an object.'); - } - if (obj.hasOwnProperty(prop)) { - delete obj[prop]; - return true; + isEscaped = (a === '"' && b === '"') + || (a === "'" && b === "'") + || (a === '`' && b === '`'); } - if (has(obj, prop)) { - var segs = prop.split('.'); - var last = segs.pop(); - while (segs.length && segs[segs.length - 1].slice(-1) === '\\') { - last = segs.pop().slice(0, -1) + '.' + last; - } - while (segs.length) obj = obj[prop = segs.shift()]; - return (delete obj[last]); + if (isEscaped && options.unescape !== false) { + node.val = node.val.slice(1, node.val.length - 1); + node.escaped = true; } - return true; -}; - - -/***/ }), -/* 671 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/*! - * has-value - * - * Copyright (c) 2014-2016, Jon Schlinkert. - * Licensed under the MIT License. - */ + if (node.match) { + var match = node.match[1]; + if (!match || match.indexOf('}') === -1) { + match = node.match[0]; + } + // replace each set with a single "," + var val = match.replace(/\{/g, ',').replace(/\}/g, ''); + node.multiplier *= val.length; + node.val = ''; + } -var isObject = __webpack_require__(672); -var hasValues = __webpack_require__(674); -var get = __webpack_require__(667); + var simpleText = last.type === 'text' + && last.multiplier === 1 + && node.multiplier === 1 + && node.val; -module.exports = function(obj, prop, noZero) { - if (isObject(obj)) { - return hasValues(get(obj, prop), noZero); + if (simpleText) { + last.val += node.val; + return; } - return hasValues(obj, prop); -}; + + prev.push(node); +} /***/ }), -/* 672 */ +/* 687 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/*! - * isobject - * - * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT License. - */ - - - -var isArray = __webpack_require__(673); - -module.exports = function isObject(val) { - return val != null && typeof val === 'object' && isArray(val) === false; -}; - - -/***/ }), -/* 673 */ -/***/ (function(module, exports) { - -var toString = {}.toString; - -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; -/***/ }), -/* 674 */ -/***/ (function(module, exports, __webpack_require__) { +var isObject = __webpack_require__(656); +var define = __webpack_require__(688); +var utils = __webpack_require__(689); +var ownNames; -"use strict"; -/*! - * has-values +/** + * Create a new AST `Node` with the given `val` and `type`. * - * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT License. + * ```js + * var node = new Node('*', 'Star'); + * var node = new Node({type: 'star', val: '*'}); + * ``` + * @name Node + * @param {String|Object} `val` Pass a matched substring, or an object to merge onto the node. + * @param {String} `type` The node type to use when `val` is a string. + * @return {Object} node instance + * @api public */ - - -module.exports = function hasValue(o, noZero) { - if (o === null || o === undefined) { - return false; +function Node(val, type, parent) { + if (typeof type !== 'string') { + parent = type; + type = null; } - if (typeof o === 'boolean') { - return true; - } + define(this, 'parent', parent); + define(this, 'isNode', true); + define(this, 'expect', null); - if (typeof o === 'number') { - if (o === 0 && noZero === true) { - return false; + if (typeof type !== 'string' && isObject(val)) { + lazyKeys(); + var keys = Object.keys(val); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + if (ownNames.indexOf(key) === -1) { + this[key] = val[key]; + } } - return true; + } else { + this.type = type; + this.val = val; } +} - if (o.length !== undefined) { - return o.length !== 0; - } +/** + * Returns true if the given value is a node. + * + * ```js + * var Node = require('snapdragon-node'); + * var node = new Node({type: 'foo'}); + * console.log(Node.isNode(node)); //=> true + * console.log(Node.isNode({})); //=> false + * ``` + * @param {Object} `node` + * @returns {Boolean} + * @api public + */ - for (var key in o) { - if (o.hasOwnProperty(key)) { - return true; - } - } - return false; +Node.isNode = function(node) { + return utils.isNode(node); }; - -/***/ }), -/* 675 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/*! - * has-value +/** + * Define a non-enumberable property on the node instance. + * Useful for adding properties that shouldn't be extended + * or visible during debugging. * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Licensed under the MIT License. + * ```js + * var node = new Node(); + * node.define('foo', 'something non-enumerable'); + * ``` + * @param {String} `name` + * @param {any} `val` + * @return {Object} returns the node instance + * @api public */ - - -var isObject = __webpack_require__(618); -var hasValues = __webpack_require__(676); -var get = __webpack_require__(667); - -module.exports = function(val, prop) { - return hasValues(isObject(val) && prop ? get(val, prop) : val); +Node.prototype.define = function(name, val) { + define(this, name, val); + return this; }; - -/***/ }), -/* 676 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/*! - * has-values +/** + * Returns true if `node.val` is an empty string, or `node.nodes` does + * not contain any non-empty text nodes. * - * Copyright (c) 2014-2015, 2017, Jon Schlinkert. - * Released under the MIT License. + * ```js + * var node = new Node({type: 'text'}); + * node.isEmpty(); //=> true + * node.val = 'foo'; + * node.isEmpty(); //=> false + * ``` + * @param {Function} `fn` (optional) Filter function that is called on `node` and/or child nodes. `isEmpty` will return false immediately when the filter function returns false on any nodes. + * @return {Boolean} + * @api public */ - - -var typeOf = __webpack_require__(677); -var isNumber = __webpack_require__(640); - -module.exports = function hasValue(val) { - // is-number checks for NaN and other edge cases - if (isNumber(val)) { - return true; - } - - switch (typeOf(val)) { - case 'null': - case 'boolean': - case 'function': - return true; - case 'string': - case 'arguments': - return val.length !== 0; - case 'error': - return val.message !== ''; - case 'array': - var len = val.length; - if (len === 0) { - return false; - } - for (var i = 0; i < len; i++) { - if (hasValue(val[i])) { - return true; - } - } - return false; - case 'file': - case 'map': - case 'set': - return val.size !== 0; - case 'object': - var keys = Object.keys(val); - if (keys.length === 0) { - return false; - } - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - if (hasValue(val[key])) { - return true; - } - } - return false; - default: { - return false; - } - } +Node.prototype.isEmpty = function(fn) { + return utils.isEmpty(this, fn); }; +/** + * Given node `foo` and node `bar`, push node `bar` onto `foo.nodes`, and + * set `foo` as `bar.parent`. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * foo.push(bar); + * ``` + * @param {Object} `node` + * @return {Number} Returns the length of `node.nodes` + * @api public + */ -/***/ }), -/* 677 */ -/***/ (function(module, exports, __webpack_require__) { +Node.prototype.push = function(node) { + assert(Node.isNode(node), 'expected node to be an instance of Node'); + define(node, 'parent', this); -var isBuffer = __webpack_require__(642); -var toString = Object.prototype.toString; + this.nodes = this.nodes || []; + return this.nodes.push(node); +}; /** - * Get the native `typeof` a value. + * Given node `foo` and node `bar`, unshift node `bar` onto `foo.nodes`, and + * set `foo` as `bar.parent`. * - * @param {*} `val` - * @return {*} Native javascript type + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * foo.unshift(bar); + * ``` + * @param {Object} `node` + * @return {Number} Returns the length of `node.nodes` + * @api public */ -module.exports = function kindOf(val) { - // primitivies - if (typeof val === 'undefined') { - return 'undefined'; - } - if (val === null) { - return 'null'; - } - if (val === true || val === false || val instanceof Boolean) { - return 'boolean'; - } - if (typeof val === 'string' || val instanceof String) { - return 'string'; - } - if (typeof val === 'number' || val instanceof Number) { - return 'number'; - } - - // functions - if (typeof val === 'function' || val instanceof Function) { - return 'function'; - } +Node.prototype.unshift = function(node) { + assert(Node.isNode(node), 'expected node to be an instance of Node'); + define(node, 'parent', this); - // array - if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { - return 'array'; - } + this.nodes = this.nodes || []; + return this.nodes.unshift(node); +}; - // check for instances of RegExp and Date before calling `toString` - if (val instanceof RegExp) { - return 'regexp'; - } - if (val instanceof Date) { - return 'date'; - } +/** + * Pop a node from `node.nodes`. + * + * ```js + * var node = new Node({type: 'foo'}); + * node.push(new Node({type: 'a'})); + * node.push(new Node({type: 'b'})); + * node.push(new Node({type: 'c'})); + * node.push(new Node({type: 'd'})); + * console.log(node.nodes.length); + * //=> 4 + * node.pop(); + * console.log(node.nodes.length); + * //=> 3 + * ``` + * @return {Number} Returns the popped `node` + * @api public + */ - // other objects - var type = toString.call(val); +Node.prototype.pop = function() { + return this.nodes && this.nodes.pop(); +}; - if (type === '[object RegExp]') { - return 'regexp'; - } - if (type === '[object Date]') { - return 'date'; - } - if (type === '[object Arguments]') { - return 'arguments'; - } - if (type === '[object Error]') { - return 'error'; - } - if (type === '[object Promise]') { - return 'promise'; - } +/** + * Shift a node from `node.nodes`. + * + * ```js + * var node = new Node({type: 'foo'}); + * node.push(new Node({type: 'a'})); + * node.push(new Node({type: 'b'})); + * node.push(new Node({type: 'c'})); + * node.push(new Node({type: 'd'})); + * console.log(node.nodes.length); + * //=> 4 + * node.shift(); + * console.log(node.nodes.length); + * //=> 3 + * ``` + * @return {Object} Returns the shifted `node` + * @api public + */ - // buffer - if (isBuffer(val)) { - return 'buffer'; - } +Node.prototype.shift = function() { + return this.nodes && this.nodes.shift(); +}; - // es6: Map, WeakMap, Set, WeakSet - if (type === '[object Set]') { - return 'set'; - } - if (type === '[object WeakSet]') { - return 'weakset'; - } - if (type === '[object Map]') { - return 'map'; - } - if (type === '[object WeakMap]') { - return 'weakmap'; - } - if (type === '[object Symbol]') { - return 'symbol'; - } +/** + * Remove `node` from `node.nodes`. + * + * ```js + * node.remove(childNode); + * ``` + * @param {Object} `node` + * @return {Object} Returns the removed node. + * @api public + */ - // typed arrays - if (type === '[object Int8Array]') { - return 'int8array'; - } - if (type === '[object Uint8Array]') { - return 'uint8array'; - } - if (type === '[object Uint8ClampedArray]') { - return 'uint8clampedarray'; - } - if (type === '[object Int16Array]') { - return 'int16array'; - } - if (type === '[object Uint16Array]') { - return 'uint16array'; - } - if (type === '[object Int32Array]') { - return 'int32array'; - } - if (type === '[object Uint32Array]') { - return 'uint32array'; - } - if (type === '[object Float32Array]') { - return 'float32array'; - } - if (type === '[object Float64Array]') { - return 'float64array'; +Node.prototype.remove = function(node) { + assert(Node.isNode(node), 'expected node to be an instance of Node'); + this.nodes = this.nodes || []; + var idx = node.index; + if (idx !== -1) { + node.index = -1; + return this.nodes.splice(idx, 1); } - - // must be a plain object - return 'object'; + return null; }; +/** + * Get the first child node from `node.nodes` that matches the given `type`. + * If `type` is a number, the child node at that index is returned. + * + * ```js + * var child = node.find(1); //<= index of the node to get + * var child = node.find('foo'); //<= node.type of a child node + * var child = node.find(/^(foo|bar)$/); //<= regex to match node.type + * var child = node.find(['foo', 'bar']); //<= array of node.type(s) + * ``` + * @param {String} `type` + * @return {Object} Returns a child node or undefined. + * @api public + */ -/***/ }), -/* 678 */ -/***/ (function(module, exports, __webpack_require__) { +Node.prototype.find = function(type) { + return utils.findNode(this.nodes, type); +}; -"use strict"; -/*! - * set-value +/** + * Return true if the node is the given `type`. * - * Copyright (c) 2014-2015, 2017, Jon Schlinkert. - * Released under the MIT License. + * ```js + * var node = new Node({type: 'bar'}); + * cosole.log(node.isType('foo')); // false + * cosole.log(node.isType(/^(foo|bar)$/)); // true + * cosole.log(node.isType(['foo', 'bar'])); // true + * ``` + * @param {String} `type` + * @return {Boolean} + * @api public */ +Node.prototype.isType = function(type) { + return utils.isType(this, type); +}; +/** + * Return true if the `node.nodes` has the given `type`. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * foo.push(bar); + * + * cosole.log(foo.hasType('qux')); // false + * cosole.log(foo.hasType(/^(qux|bar)$/)); // true + * cosole.log(foo.hasType(['qux', 'bar'])); // true + * ``` + * @param {String} `type` + * @return {Boolean} + * @api public + */ -var split = __webpack_require__(635); -var extend = __webpack_require__(669); -var isPlainObject = __webpack_require__(625); -var isObject = __webpack_require__(665); - -module.exports = function(obj, prop, val) { - if (!isObject(obj)) { - return obj; - } +Node.prototype.hasType = function(type) { + return utils.hasType(this, type); +}; - if (Array.isArray(prop)) { - prop = [].concat.apply([], prop).join('.'); - } +/** + * Get the siblings array, or `null` if it doesn't exist. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * var baz = new Node({type: 'baz'}); + * foo.push(bar); + * foo.push(baz); + * + * console.log(bar.siblings.length) // 2 + * console.log(baz.siblings.length) // 2 + * ``` + * @return {Array} + * @api public + */ - if (typeof prop !== 'string') { - return obj; +Object.defineProperty(Node.prototype, 'siblings', { + set: function() { + throw new Error('node.siblings is a getter and cannot be defined'); + }, + get: function() { + return this.parent ? this.parent.nodes : null; } +}); - var keys = split(prop, {sep: '.', brackets: true}).filter(isValidKey); - var len = keys.length; - var idx = -1; - var current = obj; +/** + * Get the node's current index from `node.parent.nodes`. + * This should always be correct, even when the parent adds nodes. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * var baz = new Node({type: 'baz'}); + * var qux = new Node({type: 'qux'}); + * foo.push(bar); + * foo.push(baz); + * foo.unshift(qux); + * + * console.log(bar.index) // 1 + * console.log(baz.index) // 2 + * console.log(qux.index) // 0 + * ``` + * @return {Number} + * @api public + */ - while (++idx < len) { - var key = keys[idx]; - if (idx !== len - 1) { - if (!isObject(current[key])) { - current[key] = {}; - } - current = current[key]; - continue; +Object.defineProperty(Node.prototype, 'index', { + set: function(index) { + define(this, 'idx', index); + }, + get: function() { + if (!Array.isArray(this.siblings)) { + return -1; } - - if (isPlainObject(current[key]) && isPlainObject(val)) { - current[key] = extend({}, current[key], val); - } else { - current[key] = val; + var tok = this.idx !== -1 ? this.siblings[this.idx] : null; + if (tok !== this) { + this.idx = this.siblings.indexOf(this); } + return this.idx; } +}); - return obj; -}; - -function isValidKey(key) { - return key !== '__proto__' && key !== 'constructor' && key !== 'prototype'; -} - - -/***/ }), -/* 679 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; +/** + * Get the previous node from the siblings array or `null`. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * var baz = new Node({type: 'baz'}); + * foo.push(bar); + * foo.push(baz); + * + * console.log(baz.prev.type) // 'bar' + * ``` + * @return {Object} + * @api public + */ +Object.defineProperty(Node.prototype, 'prev', { + set: function() { + throw new Error('node.prev is a getter and cannot be defined'); + }, + get: function() { + if (Array.isArray(this.siblings)) { + return this.siblings[this.index - 1] || this.parent.prev; + } + return null; + } +}); -var isExtendable = __webpack_require__(680); -var forIn = __webpack_require__(681); +/** + * Get the siblings array, or `null` if it doesn't exist. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * var baz = new Node({type: 'baz'}); + * foo.push(bar); + * foo.push(baz); + * + * console.log(bar.siblings.length) // 2 + * console.log(baz.siblings.length) // 2 + * ``` + * @return {Object} + * @api public + */ -function mixinDeep(target, objects) { - var len = arguments.length, i = 0; - while (++i < len) { - var obj = arguments[i]; - if (isObject(obj)) { - forIn(obj, copy, target); +Object.defineProperty(Node.prototype, 'next', { + set: function() { + throw new Error('node.next is a getter and cannot be defined'); + }, + get: function() { + if (Array.isArray(this.siblings)) { + return this.siblings[this.index + 1] || this.parent.next; } + return null; } - return target; -} +}); /** - * Copy properties from the source object to the - * target object. + * Get the first node from `node.nodes`. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * var baz = new Node({type: 'baz'}); + * var qux = new Node({type: 'qux'}); + * foo.push(bar); + * foo.push(baz); + * foo.push(qux); * - * @param {*} `val` - * @param {String} `key` + * console.log(foo.first.type) // 'bar' + * ``` + * @return {Object} The first node, or undefiend + * @api public */ -function copy(val, key) { - if (!isValidKey(key)) { - return; - } - - var obj = this[key]; - if (isObject(val) && isObject(obj)) { - mixinDeep(obj, val); - } else { - this[key] = val; +Object.defineProperty(Node.prototype, 'first', { + get: function() { + return this.nodes ? this.nodes[0] : null; } -} +}); /** - * Returns true if `val` is an object or function. + * Get the last node from `node.nodes`. * - * @param {any} val - * @return {Boolean} + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * var baz = new Node({type: 'baz'}); + * var qux = new Node({type: 'qux'}); + * foo.push(bar); + * foo.push(baz); + * foo.push(qux); + * + * console.log(foo.last.type) // 'qux' + * ``` + * @return {Object} The last node, or undefiend + * @api public */ -function isObject(val) { - return isExtendable(val) && !Array.isArray(val); -} +Object.defineProperty(Node.prototype, 'last', { + get: function() { + return this.nodes ? utils.last(this.nodes) : null; + } +}); /** - * Returns true if `key` is a valid key to use when extending objects. + * Get the last node from `node.nodes`. * - * @param {String} `key` - * @return {Boolean} + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * var baz = new Node({type: 'baz'}); + * var qux = new Node({type: 'qux'}); + * foo.push(bar); + * foo.push(baz); + * foo.push(qux); + * + * console.log(foo.last.type) // 'qux' + * ``` + * @return {Object} The last node, or undefiend + * @api public */ -function isValidKey(key) { - return key !== '__proto__' && key !== 'constructor' && key !== 'prototype'; -}; +Object.defineProperty(Node.prototype, 'scope', { + get: function() { + if (this.isScope !== true) { + return this.parent ? this.parent.scope : this; + } + return this; + } +}); /** - * Expose `mixinDeep` + * Get own property names from Node prototype, but only the + * first time `Node` is instantiated */ -module.exports = mixinDeep; - - -/***/ }), -/* 680 */ -/***/ (function(module, exports, __webpack_require__) { +function lazyKeys() { + if (!ownNames) { + ownNames = Object.getOwnPropertyNames(Node.prototype); + } +} -"use strict"; -/*! - * is-extendable - * - * Copyright (c) 2015-2017, Jon Schlinkert. - * Released under the MIT License. +/** + * Simplified assertion. Throws an error is `val` is falsey. */ +function assert(val, message) { + if (!val) throw new Error(message); +} +/** + * Expose `Node` + */ -var isPlainObject = __webpack_require__(625); - -module.exports = function isExtendable(val) { - return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); -}; +exports = module.exports = Node; /***/ }), -/* 681 */ +/* 688 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /*! - * for-in + * define-property * - * Copyright (c) 2014-2017, Jon Schlinkert. + * Copyright (c) 2015, 2017, Jon Schlinkert. * Released under the MIT License. */ -module.exports = function forIn(obj, fn, thisArg) { - for (var key in obj) { - if (fn.call(thisArg, obj[key], key, obj) === false) { - break; - } - } -}; - +var isDescriptor = __webpack_require__(657); -/***/ }), -/* 682 */ -/***/ (function(module, exports) { +module.exports = function defineProperty(obj, prop, val) { + if (typeof obj !== 'object' && typeof obj !== 'function') { + throw new TypeError('expected an object or function.'); + } -/*! - * pascalcase - * - * Copyright (c) 2015, Jon Schlinkert. - * Licensed under the MIT License. - */ + if (typeof prop !== 'string') { + throw new TypeError('expected `prop` to be a string.'); + } -function pascalcase(str) { - if (typeof str !== 'string') { - throw new TypeError('expected a string.'); + if (isDescriptor(val) && ('set' in val || 'get' in val)) { + return Object.defineProperty(obj, prop, val); } - str = str.replace(/([A-Z])/g, ' $1'); - if (str.length === 1) { return str.toUpperCase(); } - str = str.replace(/^[\W_]+|[\W_]+$/g, '').toLowerCase(); - str = str.charAt(0).toUpperCase() + str.slice(1); - return str.replace(/[\W_]+(\w|$)/g, function (_, ch) { - return ch.toUpperCase(); - }); -} -module.exports = pascalcase; + return Object.defineProperty(obj, prop, { + configurable: true, + enumerable: false, + writable: true, + value: val + }); +}; /***/ }), -/* 683 */ +/* 689 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var util = __webpack_require__(234); -var utils = __webpack_require__(684); - -/** - * Expose class utils - */ - -var cu = module.exports; - -/** - * Expose class utils: `cu` - */ - -cu.isObject = function isObject(val) { - return utils.isObj(val) || typeof val === 'function'; -}; +var typeOf = __webpack_require__(690); +var utils = module.exports; /** - * Returns true if an array has any of the given elements, or an - * object has any of the give keys. + * Returns true if the given value is a node. * * ```js - * cu.has(['a', 'b', 'c'], 'c'); - * //=> true - * - * cu.has(['a', 'b', 'c'], ['c', 'z']); - * //=> true - * - * cu.has({a: 'b', c: 'd'}, ['c', 'z']); - * //=> true + * var Node = require('snapdragon-node'); + * var node = new Node({type: 'foo'}); + * console.log(utils.isNode(node)); //=> true + * console.log(utils.isNode({})); //=> false * ``` - * @param {Object} `obj` - * @param {String|Array} `val` - * @return {Boolean} + * @param {Object} `node` Instance of [snapdragon-node][] + * @returns {Boolean} * @api public */ -cu.has = function has(obj, val) { - val = cu.arrayify(val); - var len = val.length; - - if (cu.isObject(obj)) { - for (var key in obj) { - if (val.indexOf(key) > -1) { - return true; - } - } - - var keys = cu.nativeKeys(obj); - return cu.has(keys, val); - } - - if (Array.isArray(obj)) { - var arr = obj; - while (len--) { - if (arr.indexOf(val[len]) > -1) { - return true; - } - } - return false; - } - - throw new TypeError('expected an array or object.'); +utils.isNode = function(node) { + return typeOf(node) === 'object' && node.isNode === true; }; /** - * Returns true if an array or object has all of the given values. + * Emit an empty string for the given `node`. * * ```js - * cu.hasAll(['a', 'b', 'c'], 'c'); - * //=> true - * - * cu.hasAll(['a', 'b', 'c'], ['c', 'z']); - * //=> false - * - * cu.hasAll({a: 'b', c: 'd'}, ['c', 'z']); - * //=> false + * // do nothing for beginning-of-string + * snapdragon.compiler.set('bos', utils.noop); * ``` - * @param {Object|Array} `val` - * @param {String|Array} `values` - * @return {Boolean} + * @param {Object} `node` Instance of [snapdragon-node][] + * @returns {undefined} * @api public */ -cu.hasAll = function hasAll(val, values) { - values = cu.arrayify(values); - var len = values.length; - while (len--) { - if (!cu.has(val, values[len])) { - return false; - } - } - return true; +utils.noop = function(node) { + append(this, '', node); }; /** - * Cast the given value to an array. + * Appdend `node.val` to `compiler.output`, exactly as it was created + * by the parser. * * ```js - * cu.arrayify('foo'); - * //=> ['foo'] - * - * cu.arrayify(['foo']); - * //=> ['foo'] + * snapdragon.compiler.set('text', utils.identity); * ``` - * - * @param {String|Array} `val` - * @return {Array} + * @param {Object} `node` Instance of [snapdragon-node][] + * @returns {undefined} * @api public */ -cu.arrayify = function arrayify(val) { - return val ? (Array.isArray(val) ? val : [val]) : []; -}; - -/** - * Noop - */ - -cu.noop = function noop() { - return; +utils.identity = function(node) { + append(this, node.val, node); }; /** - * Returns the first argument passed to the function. + * Previously named `.emit`, this method appends the given `val` + * to `compiler.output` for the given node. Useful when you know + * what value should be appended advance, regardless of the actual + * value of `node.val`. + * + * ```js + * snapdragon.compiler + * .set('i', function(node) { + * this.mapVisit(node); + * }) + * .set('i.open', utils.append('')) + * .set('i.close', utils.append('')) + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @returns {Function} Returns a compiler middleware function. + * @api public */ -cu.identity = function identity(val) { - return val; +utils.append = function(val) { + return function(node) { + append(this, val, node); + }; }; /** - * Returns true if a value has a `contructor` + * Used in compiler middleware, this onverts an AST node into + * an empty `text` node and deletes `node.nodes` if it exists. + * The advantage of this method is that, as opposed to completely + * removing the node, indices will not need to be re-calculated + * in sibling nodes, and nothing is appended to the output. * * ```js - * cu.hasConstructor({}); - * //=> true - * - * cu.hasConstructor(Object.create(null)); - * //=> false + * utils.toNoop(node); + * // convert `node.nodes` to the given value instead of deleting it + * utils.toNoop(node, []); * ``` - * @param {Object} `value` - * @return {Boolean} + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {Array} `nodes` Optionally pass a new `nodes` value, to replace the existing `node.nodes` array. * @api public */ -cu.hasConstructor = function hasConstructor(val) { - return cu.isObject(val) && typeof val.constructor !== 'undefined'; +utils.toNoop = function(node, nodes) { + if (nodes) { + node.nodes = nodes; + } else { + delete node.nodes; + node.type = 'text'; + node.val = ''; + } }; /** - * Get the native `ownPropertyNames` from the constructor of the - * given `object`. An empty array is returned if the object does - * not have a constructor. + * Visit `node` with the given `fn`. The built-in `.visit` method in snapdragon + * automatically calls registered compilers, this allows you to pass a visitor + * function. * * ```js - * cu.nativeKeys({a: 'b', b: 'c', c: 'd'}) - * //=> ['a', 'b', 'c'] - * - * cu.nativeKeys(function(){}) - * //=> ['length', 'caller'] + * snapdragon.compiler.set('i', function(node) { + * utils.visit(node, function(childNode) { + * // do stuff with "childNode" + * return childNode; + * }); + * }); * ``` - * - * @param {Object} `obj` Object that has a `constructor`. - * @return {Array} Array of keys. + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {Function} `fn` + * @return {Object} returns the node after recursively visiting all child nodes. * @api public */ -cu.nativeKeys = function nativeKeys(val) { - if (!cu.hasConstructor(val)) return []; - return Object.getOwnPropertyNames(val); +utils.visit = function(node, fn) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + assert(isFunction(fn), 'expected a visitor function'); + fn(node); + return node.nodes ? utils.mapVisit(node, fn) : node; }; /** - * Returns property descriptor `key` if it's an "own" property - * of the given object. + * Map [visit](#visit) the given `fn` over `node.nodes`. This is called by + * [visit](#visit), use this method if you do not want `fn` to be called on + * the first node. * * ```js - * function App() {} - * Object.defineProperty(App.prototype, 'count', { - * get: function() { - * return Object.keys(this).length; - * } + * snapdragon.compiler.set('i', function(node) { + * utils.mapVisit(node, function(childNode) { + * // do stuff with "childNode" + * return childNode; + * }); * }); - * cu.getDescriptor(App.prototype, 'count'); - * // returns: - * // { - * // get: [Function], - * // set: undefined, - * // enumerable: false, - * // configurable: false - * // } * ``` - * - * @param {Object} `obj` - * @param {String} `key` - * @return {Object} Returns descriptor `key` + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {Object} `options` + * @param {Function} `fn` + * @return {Object} returns the node * @api public */ -cu.getDescriptor = function getDescriptor(obj, key) { - if (!cu.isObject(obj)) { - throw new TypeError('expected an object.'); - } - if (typeof key !== 'string') { - throw new TypeError('expected key to be a string.'); +utils.mapVisit = function(node, fn) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + assert(isArray(node.nodes), 'expected node.nodes to be an array'); + assert(isFunction(fn), 'expected a visitor function'); + + for (var i = 0; i < node.nodes.length; i++) { + utils.visit(node.nodes[i], fn); } - return Object.getOwnPropertyDescriptor(obj, key); + return node; }; /** - * Copy a descriptor from one object to another. + * Unshift an `*.open` node onto `node.nodes`. * * ```js - * function App() {} - * Object.defineProperty(App.prototype, 'count', { - * get: function() { - * return Object.keys(this).length; + * var Node = require('snapdragon-node'); + * snapdragon.parser.set('brace', function(node) { + * var match = this.match(/^{/); + * if (match) { + * var parent = new Node({type: 'brace'}); + * utils.addOpen(parent, Node); + * console.log(parent.nodes[0]): + * // { type: 'brace.open', val: '' }; + * + * // push the parent "brace" node onto the stack + * this.push(parent); + * + * // return the parent node, so it's also added to the AST + * return brace; * } * }); - * var obj = {}; - * cu.copyDescriptor(obj, App.prototype, 'count'); * ``` - * @param {Object} `receiver` - * @param {Object} `provider` - * @param {String} `name` - * @return {Object} + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][]. + * @param {Function} `filter` Optionaly specify a filter function to exclude the node. + * @return {Object} Returns the created opening node. * @api public */ -cu.copyDescriptor = function copyDescriptor(receiver, provider, name) { - if (!cu.isObject(receiver)) { - throw new TypeError('expected receiving object to be an object.'); - } - if (!cu.isObject(provider)) { - throw new TypeError('expected providing object to be an object.'); - } - if (typeof name !== 'string') { - throw new TypeError('expected name to be a string.'); +utils.addOpen = function(node, Node, val, filter) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + assert(isFunction(Node), 'expected Node to be a constructor function'); + + if (typeof val === 'function') { + filter = val; + val = ''; } - var val = cu.getDescriptor(provider, name); - if (val) Object.defineProperty(receiver, name, val); + if (typeof filter === 'function' && !filter(node)) return; + var open = new Node({ type: node.type + '.open', val: val}); + var unshift = node.unshift || node.unshiftNode; + if (typeof unshift === 'function') { + unshift.call(node, open); + } else { + utils.unshiftNode(node, open); + } + return open; }; /** - * Copy static properties, prototype properties, and descriptors - * from one object to another. + * Push a `*.close` node onto `node.nodes`. * - * @param {Object} `receiver` - * @param {Object} `provider` - * @param {String|Array} `omit` One or more properties to omit - * @return {Object} + * ```js + * var Node = require('snapdragon-node'); + * snapdragon.parser.set('brace', function(node) { + * var match = this.match(/^}/); + * if (match) { + * var parent = this.parent(); + * if (parent.type !== 'brace') { + * throw new Error('missing opening: ' + '}'); + * } + * + * utils.addClose(parent, Node); + * console.log(parent.nodes[parent.nodes.length - 1]): + * // { type: 'brace.close', val: '' }; + * + * // no need to return a node, since the parent + * // was already added to the AST + * return; + * } + * }); + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][]. + * @param {Function} `filter` Optionaly specify a filter function to exclude the node. + * @return {Object} Returns the created closing node. * @api public */ -cu.copy = function copy(receiver, provider, omit) { - if (!cu.isObject(receiver)) { - throw new TypeError('expected receiving object to be an object.'); - } - if (!cu.isObject(provider)) { - throw new TypeError('expected providing object to be an object.'); - } - var props = Object.getOwnPropertyNames(provider); - var keys = Object.keys(provider); - var len = props.length, - key; - omit = cu.arrayify(omit); +utils.addClose = function(node, Node, val, filter) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + assert(isFunction(Node), 'expected Node to be a constructor function'); - while (len--) { - key = props[len]; + if (typeof val === 'function') { + filter = val; + val = ''; + } - if (cu.has(keys, key)) { - utils.define(receiver, key, provider[key]); - } else if (!(key in receiver) && !cu.has(omit, key)) { - cu.copyDescriptor(receiver, provider, key); - } + if (typeof filter === 'function' && !filter(node)) return; + var close = new Node({ type: node.type + '.close', val: val}); + var push = node.push || node.pushNode; + if (typeof push === 'function') { + push.call(node, close); + } else { + utils.pushNode(node, close); } + return close; }; /** - * Inherit the static properties, prototype properties, and descriptors - * from of an object. + * Wraps the given `node` with `*.open` and `*.close` nodes. * - * @param {Object} `receiver` - * @param {Object} `provider` - * @param {String|Array} `omit` One or more properties to omit - * @return {Object} + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][]. + * @param {Function} `filter` Optionaly specify a filter function to exclude the node. + * @return {Object} Returns the node * @api public */ -cu.inherit = function inherit(receiver, provider, omit) { - if (!cu.isObject(receiver)) { - throw new TypeError('expected receiving object to be an object.'); - } - if (!cu.isObject(provider)) { - throw new TypeError('expected providing object to be an object.'); - } - - var keys = []; - for (var key in provider) { - keys.push(key); - receiver[key] = provider[key]; - } - - keys = keys.concat(cu.arrayify(omit)); +utils.wrapNodes = function(node, Node, filter) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + assert(isFunction(Node), 'expected Node to be a constructor function'); - var a = provider.prototype || provider; - var b = receiver.prototype || receiver; - cu.copy(b, a, keys); + utils.addOpen(node, Node, filter); + utils.addClose(node, Node, filter); + return node; }; /** - * Returns a function for extending the static properties, - * prototype properties, and descriptors from the `Parent` - * constructor onto `Child` constructors. + * Push the given `node` onto `parent.nodes`, and set `parent` as `node.parent. * * ```js - * var extend = cu.extend(Parent); - * Parent.extend(Child); - * - * // optional methods - * Parent.extend(Child, { - * foo: function() {}, - * bar: function() {} - * }); + * var parent = new Node({type: 'foo'}); + * var node = new Node({type: 'bar'}); + * utils.pushNode(parent, node); + * console.log(parent.nodes[0].type) // 'bar' + * console.log(node.parent.type) // 'foo' * ``` - * @param {Function} `Parent` Parent ctor - * @param {Function} `extend` Optional extend function to handle custom extensions. Useful when updating methods that require a specific prototype. - * @param {Function} `Child` Child ctor - * @param {Object} `proto` Optionally pass additional prototype properties to inherit. - * @return {Object} + * @param {Object} `parent` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Object} Returns the child node * @api public */ -cu.extend = function() { - // keep it lazy, instead of assigning to `cu.extend` - return utils.staticExtend.apply(null, arguments); +utils.pushNode = function(parent, node) { + assert(utils.isNode(parent), 'expected parent node to be an instance of Node'); + assert(utils.isNode(node), 'expected node to be an instance of Node'); + + node.define('parent', parent); + parent.nodes = parent.nodes || []; + parent.nodes.push(node); + return node; }; /** - * Bubble up events emitted from static methods on the Parent ctor. + * Unshift `node` onto `parent.nodes`, and set `parent` as `node.parent. * - * @param {Object} `Parent` - * @param {Array} `events` Event names to bubble up + * ```js + * var parent = new Node({type: 'foo'}); + * var node = new Node({type: 'bar'}); + * utils.unshiftNode(parent, node); + * console.log(parent.nodes[0].type) // 'bar' + * console.log(node.parent.type) // 'foo' + * ``` + * @param {Object} `parent` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {undefined} * @api public */ -cu.bubble = function(Parent, events) { - events = events || []; - Parent.bubble = function(Child, arr) { - if (Array.isArray(arr)) { - events = utils.union([], events, arr); - } - var len = events.length; - var idx = -1; - while (++idx < len) { - var name = events[idx]; - Parent.on(name, Child.emit.bind(Child, name)); - } - cu.bubble(Child, events); - }; -}; - - -/***/ }), -/* 684 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var utils = {}; - +utils.unshiftNode = function(parent, node) { + assert(utils.isNode(parent), 'expected parent node to be an instance of Node'); + assert(utils.isNode(node), 'expected node to be an instance of Node'); + node.define('parent', parent); + parent.nodes = parent.nodes || []; + parent.nodes.unshift(node); +}; /** - * Lazily required module dependencies + * Pop the last `node` off of `parent.nodes`. The advantage of + * using this method is that it checks for `node.nodes` and works + * with any version of `snapdragon-node`. + * + * ```js + * var parent = new Node({type: 'foo'}); + * utils.pushNode(parent, new Node({type: 'foo'})); + * utils.pushNode(parent, new Node({type: 'bar'})); + * utils.pushNode(parent, new Node({type: 'baz'})); + * console.log(parent.nodes.length); //=> 3 + * utils.popNode(parent); + * console.log(parent.nodes.length); //=> 2 + * ``` + * @param {Object} `parent` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Number|Undefined} Returns the length of `node.nodes` or undefined. + * @api public */ -utils.union = __webpack_require__(666); -utils.define = __webpack_require__(685); -utils.isObj = __webpack_require__(618); -utils.staticExtend = __webpack_require__(692); - +utils.popNode = function(node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + if (typeof node.pop === 'function') { + return node.pop(); + } + return node.nodes && node.nodes.pop(); +}; /** - * Expose `utils` + * Shift the first `node` off of `parent.nodes`. The advantage of + * using this method is that it checks for `node.nodes` and works + * with any version of `snapdragon-node`. + * + * ```js + * var parent = new Node({type: 'foo'}); + * utils.pushNode(parent, new Node({type: 'foo'})); + * utils.pushNode(parent, new Node({type: 'bar'})); + * utils.pushNode(parent, new Node({type: 'baz'})); + * console.log(parent.nodes.length); //=> 3 + * utils.shiftNode(parent); + * console.log(parent.nodes.length); //=> 2 + * ``` + * @param {Object} `parent` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Number|Undefined} Returns the length of `node.nodes` or undefined. + * @api public */ -module.exports = utils; - - -/***/ }), -/* 685 */ -/***/ (function(module, exports, __webpack_require__) { +utils.shiftNode = function(node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + if (typeof node.shift === 'function') { + return node.shift(); + } + return node.nodes && node.nodes.shift(); +}; -"use strict"; -/*! - * define-property +/** + * Remove the specified `node` from `parent.nodes`. * - * Copyright (c) 2015, Jon Schlinkert. - * Licensed under the MIT License. + * ```js + * var parent = new Node({type: 'abc'}); + * var foo = new Node({type: 'foo'}); + * utils.pushNode(parent, foo); + * utils.pushNode(parent, new Node({type: 'bar'})); + * utils.pushNode(parent, new Node({type: 'baz'})); + * console.log(parent.nodes.length); //=> 3 + * utils.removeNode(parent, foo); + * console.log(parent.nodes.length); //=> 2 + * ``` + * @param {Object} `parent` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Object|undefined} Returns the removed node, if successful, or undefined if it does not exist on `parent.nodes`. + * @api public */ +utils.removeNode = function(parent, node) { + assert(utils.isNode(parent), 'expected parent.node to be an instance of Node'); + assert(utils.isNode(node), 'expected node to be an instance of Node'); - -var isDescriptor = __webpack_require__(686); - -module.exports = function defineProperty(obj, prop, val) { - if (typeof obj !== 'object' && typeof obj !== 'function') { - throw new TypeError('expected an object or function.'); + if (!parent.nodes) { + return null; } - if (typeof prop !== 'string') { - throw new TypeError('expected `prop` to be a string.'); + if (typeof parent.remove === 'function') { + return parent.remove(node); } - if (isDescriptor(val) && ('set' in val || 'get' in val)) { - return Object.defineProperty(obj, prop, val); + var idx = parent.nodes.indexOf(node); + if (idx !== -1) { + return parent.nodes.splice(idx, 1); } - - return Object.defineProperty(obj, prop, { - configurable: true, - enumerable: false, - writable: true, - value: val - }); }; - -/***/ }), -/* 686 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/*! - * is-descriptor +/** + * Returns true if `node.type` matches the given `type`. Throws a + * `TypeError` if `node` is not an instance of `Node`. * - * Copyright (c) 2015-2017, Jon Schlinkert. - * Released under the MIT License. + * ```js + * var Node = require('snapdragon-node'); + * var node = new Node({type: 'foo'}); + * console.log(utils.isType(node, 'foo')); // false + * console.log(utils.isType(node, 'bar')); // true + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {String} `type` + * @return {Boolean} + * @api public */ - - -var typeOf = __webpack_require__(687); -var isAccessor = __webpack_require__(688); -var isData = __webpack_require__(690); - -module.exports = function isDescriptor(obj, key) { - if (typeOf(obj) !== 'object') { - return false; - } - if ('get' in obj) { - return isAccessor(obj, key); +utils.isType = function(node, type) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + switch (typeOf(type)) { + case 'array': + var types = type.slice(); + for (var i = 0; i < types.length; i++) { + if (utils.isType(node, types[i])) { + return true; + } + } + return false; + case 'string': + return node.type === type; + case 'regexp': + return type.test(node.type); + default: { + throw new TypeError('expected "type" to be an array, string or regexp'); + } } - return isData(obj, key); }; - -/***/ }), -/* 687 */ -/***/ (function(module, exports) { - -var toString = Object.prototype.toString; - /** - * Get the native `typeof` a value. + * Returns true if the given `node` has the given `type` in `node.nodes`. + * Throws a `TypeError` if `node` is not an instance of `Node`. * - * @param {*} `val` - * @return {*} Native javascript type + * ```js + * var Node = require('snapdragon-node'); + * var node = new Node({ + * type: 'foo', + * nodes: [ + * new Node({type: 'bar'}), + * new Node({type: 'baz'}) + * ] + * }); + * console.log(utils.hasType(node, 'xyz')); // false + * console.log(utils.hasType(node, 'baz')); // true + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {String} `type` + * @return {Boolean} + * @api public */ -module.exports = function kindOf(val) { - var type = typeof val; - - // primitivies - if (type === 'undefined') { - return 'undefined'; - } - if (val === null) { - return 'null'; - } - if (val === true || val === false || val instanceof Boolean) { - return 'boolean'; - } - if (type === 'string' || val instanceof String) { - return 'string'; - } - if (type === 'number' || val instanceof Number) { - return 'number'; - } - - // functions - if (type === 'function' || val instanceof Function) { - if (typeof val.constructor.name !== 'undefined' && val.constructor.name.slice(0, 9) === 'Generator') { - return 'generatorfunction'; +utils.hasType = function(node, type) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + if (!Array.isArray(node.nodes)) return false; + for (var i = 0; i < node.nodes.length; i++) { + if (utils.isType(node.nodes[i], type)) { + return true; } - return 'function'; } + return false; +}; - // array - if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { - return 'array'; - } +/** + * Returns the first node from `node.nodes` of the given `type` + * + * ```js + * var node = new Node({ + * type: 'foo', + * nodes: [ + * new Node({type: 'text', val: 'abc'}), + * new Node({type: 'text', val: 'xyz'}) + * ] + * }); + * + * var textNode = utils.firstOfType(node.nodes, 'text'); + * console.log(textNode.val); + * //=> 'abc' + * ``` + * @param {Array} `nodes` + * @param {String} `type` + * @return {Object|undefined} Returns the first matching node or undefined. + * @api public + */ - // check for instances of RegExp and Date before calling `toString` - if (val instanceof RegExp) { - return 'regexp'; - } - if (val instanceof Date) { - return 'date'; +utils.firstOfType = function(nodes, type) { + for (var i = 0; i < nodes.length; i++) { + var node = nodes[i]; + if (utils.isType(node, type)) { + return node; + } } +}; - // other objects - type = toString.call(val); +/** + * Returns the node at the specified index, or the first node of the + * given `type` from `node.nodes`. + * + * ```js + * var node = new Node({ + * type: 'foo', + * nodes: [ + * new Node({type: 'text', val: 'abc'}), + * new Node({type: 'text', val: 'xyz'}) + * ] + * }); + * + * var nodeOne = utils.findNode(node.nodes, 'text'); + * console.log(nodeOne.val); + * //=> 'abc' + * + * var nodeTwo = utils.findNode(node.nodes, 1); + * console.log(nodeTwo.val); + * //=> 'xyz' + * ``` + * + * @param {Array} `nodes` + * @param {String|Number} `type` Node type or index. + * @return {Object} Returns a node or undefined. + * @api public + */ - if (type === '[object RegExp]') { - return 'regexp'; - } - if (type === '[object Date]') { - return 'date'; - } - if (type === '[object Arguments]') { - return 'arguments'; - } - if (type === '[object Error]') { - return 'error'; - } - if (type === '[object Promise]') { - return 'promise'; +utils.findNode = function(nodes, type) { + if (!Array.isArray(nodes)) { + return null; } - - // buffer - if (isBuffer(val)) { - return 'buffer'; + if (typeof type === 'number') { + return nodes[type]; } + return utils.firstOfType(nodes, type); +}; - // es6: Map, WeakMap, Set, WeakSet - if (type === '[object Set]') { - return 'set'; - } - if (type === '[object WeakSet]') { - return 'weakset'; - } - if (type === '[object Map]') { - return 'map'; - } - if (type === '[object WeakMap]') { - return 'weakmap'; - } - if (type === '[object Symbol]') { - return 'symbol'; - } - - if (type === '[object Map Iterator]') { - return 'mapiterator'; - } - if (type === '[object Set Iterator]') { - return 'setiterator'; - } - if (type === '[object String Iterator]') { - return 'stringiterator'; - } - if (type === '[object Array Iterator]') { - return 'arrayiterator'; - } - - // typed arrays - if (type === '[object Int8Array]') { - return 'int8array'; - } - if (type === '[object Uint8Array]') { - return 'uint8array'; - } - if (type === '[object Uint8ClampedArray]') { - return 'uint8clampedarray'; - } - if (type === '[object Int16Array]') { - return 'int16array'; - } - if (type === '[object Uint16Array]') { - return 'uint16array'; - } - if (type === '[object Int32Array]') { - return 'int32array'; - } - if (type === '[object Uint32Array]') { - return 'uint32array'; - } - if (type === '[object Float32Array]') { - return 'float32array'; - } - if (type === '[object Float64Array]') { - return 'float64array'; - } +/** + * Returns true if the given node is an "*.open" node. + * + * ```js + * var Node = require('snapdragon-node'); + * var brace = new Node({type: 'brace'}); + * var open = new Node({type: 'brace.open'}); + * var close = new Node({type: 'brace.close'}); + * + * console.log(utils.isOpen(brace)); // false + * console.log(utils.isOpen(open)); // true + * console.log(utils.isOpen(close)); // false + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Boolean} + * @api public + */ - // must be a plain object - return 'object'; +utils.isOpen = function(node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + return node.type.slice(-5) === '.open'; }; /** - * If you need to support Safari 5-7 (8-10 yr-old browser), - * take a look at https://github.com/feross/is-buffer + * Returns true if the given node is a "*.close" node. + * + * ```js + * var Node = require('snapdragon-node'); + * var brace = new Node({type: 'brace'}); + * var open = new Node({type: 'brace.open'}); + * var close = new Node({type: 'brace.close'}); + * + * console.log(utils.isClose(brace)); // false + * console.log(utils.isClose(open)); // false + * console.log(utils.isClose(close)); // true + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Boolean} + * @api public */ -function isBuffer(val) { - return val.constructor - && typeof val.constructor.isBuffer === 'function' - && val.constructor.isBuffer(val); -} +utils.isClose = function(node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + return node.type.slice(-6) === '.close'; +}; +/** + * Returns true if `node.nodes` **has** an `.open` node + * + * ```js + * var Node = require('snapdragon-node'); + * var brace = new Node({ + * type: 'brace', + * nodes: [] + * }); + * + * var open = new Node({type: 'brace.open'}); + * console.log(utils.hasOpen(brace)); // false + * + * brace.pushNode(open); + * console.log(utils.hasOpen(brace)); // true + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Boolean} + * @api public + */ -/***/ }), -/* 688 */ -/***/ (function(module, exports, __webpack_require__) { +utils.hasOpen = function(node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + var first = node.first || node.nodes ? node.nodes[0] : null; + if (utils.isNode(first)) { + return first.type === node.type + '.open'; + } + return false; +}; -"use strict"; -/*! - * is-accessor-descriptor +/** + * Returns true if `node.nodes` **has** a `.close` node * - * Copyright (c) 2015, Jon Schlinkert. - * Licensed under the MIT License. + * ```js + * var Node = require('snapdragon-node'); + * var brace = new Node({ + * type: 'brace', + * nodes: [] + * }); + * + * var close = new Node({type: 'brace.close'}); + * console.log(utils.hasClose(brace)); // false + * + * brace.pushNode(close); + * console.log(utils.hasClose(brace)); // true + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Boolean} + * @api public */ +utils.hasClose = function(node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + var last = node.last || node.nodes ? node.nodes[node.nodes.length - 1] : null; + if (utils.isNode(last)) { + return last.type === node.type + '.close'; + } + return false; +}; +/** + * Returns true if `node.nodes` has both `.open` and `.close` nodes + * + * ```js + * var Node = require('snapdragon-node'); + * var brace = new Node({ + * type: 'brace', + * nodes: [] + * }); + * + * var open = new Node({type: 'brace.open'}); + * var close = new Node({type: 'brace.close'}); + * console.log(utils.hasOpen(brace)); // false + * console.log(utils.hasClose(brace)); // false + * + * brace.pushNode(open); + * brace.pushNode(close); + * console.log(utils.hasOpen(brace)); // true + * console.log(utils.hasClose(brace)); // true + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Boolean} + * @api public + */ -var typeOf = __webpack_require__(689); - -// accessor descriptor properties -var accessor = { - get: 'function', - set: 'function', - configurable: 'boolean', - enumerable: 'boolean' +utils.hasOpenAndClose = function(node) { + return utils.hasOpen(node) && utils.hasClose(node); }; -function isAccessorDescriptor(obj, prop) { - if (typeof prop === 'string') { - var val = Object.getOwnPropertyDescriptor(obj, prop); - return typeof val !== 'undefined'; - } +/** + * Push the given `node` onto the `state.inside` array for the + * given type. This array is used as a specialized "stack" for + * only the given `node.type`. + * + * ```js + * var state = { inside: {}}; + * var node = new Node({type: 'brace'}); + * utils.addType(state, node); + * console.log(state.inside); + * //=> { brace: [{type: 'brace'}] } + * ``` + * @param {Object} `state` The `compiler.state` object or custom state object. + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Array} Returns the `state.inside` stack for the given type. + * @api public + */ - if (typeOf(obj) !== 'object') { - return false; - } +utils.addType = function(state, node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + assert(isObject(state), 'expected state to be an object'); - if (has(obj, 'value') || has(obj, 'writable')) { - return false; - } + var type = node.parent + ? node.parent.type + : node.type.replace(/\.open$/, ''); - if (!has(obj, 'get') || typeof obj.get !== 'function') { - return false; + if (!state.hasOwnProperty('inside')) { + state.inside = {}; + } + if (!state.inside.hasOwnProperty(type)) { + state.inside[type] = []; } - // tldr: it's valid to have "set" be undefined - // "set" might be undefined if `Object.getOwnPropertyDescriptor` - // was used to get the value, and only `get` was defined by the user - if (has(obj, 'set') && typeof obj[key] !== 'function' && typeof obj[key] !== 'undefined') { - return false; + var arr = state.inside[type]; + arr.push(node); + return arr; +}; + +/** + * Remove the given `node` from the `state.inside` array for the + * given type. This array is used as a specialized "stack" for + * only the given `node.type`. + * + * ```js + * var state = { inside: {}}; + * var node = new Node({type: 'brace'}); + * utils.addType(state, node); + * console.log(state.inside); + * //=> { brace: [{type: 'brace'}] } + * utils.removeType(state, node); + * //=> { brace: [] } + * ``` + * @param {Object} `state` The `compiler.state` object or custom state object. + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Array} Returns the `state.inside` stack for the given type. + * @api public + */ + +utils.removeType = function(state, node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + assert(isObject(state), 'expected state to be an object'); + + var type = node.parent + ? node.parent.type + : node.type.replace(/\.close$/, ''); + + if (state.inside.hasOwnProperty(type)) { + return state.inside[type].pop(); } +}; - for (var key in obj) { - if (!accessor.hasOwnProperty(key)) { - continue; +/** + * Returns true if `node.val` is an empty string, or `node.nodes` does + * not contain any non-empty text nodes. + * + * ```js + * var node = new Node({type: 'text'}); + * utils.isEmpty(node); //=> true + * node.val = 'foo'; + * utils.isEmpty(node); //=> false + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {Function} `fn` + * @return {Boolean} + * @api public + */ + +utils.isEmpty = function(node, fn) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + + if (!Array.isArray(node.nodes)) { + if (node.type !== 'text') { + return true; + } + if (typeof fn === 'function') { + return fn(node, node.parent); } + return !utils.trim(node.val); + } - if (typeOf(obj[key]) === accessor[key]) { + for (var i = 0; i < node.nodes.length; i++) { + var child = node.nodes[i]; + if (utils.isOpen(child) || utils.isClose(child)) { continue; } - - if (typeof obj[key] !== 'undefined') { + if (!utils.isEmpty(child, fn)) { return false; } } - return true; -} -function has(obj, key) { - return {}.hasOwnProperty.call(obj, key); -} + return true; +}; /** - * Expose `isAccessorDescriptor` + * Returns true if the `state.inside` stack for the given type exists + * and has one or more nodes on it. + * + * ```js + * var state = { inside: {}}; + * var node = new Node({type: 'brace'}); + * console.log(utils.isInsideType(state, 'brace')); //=> false + * utils.addType(state, node); + * console.log(utils.isInsideType(state, 'brace')); //=> true + * utils.removeType(state, node); + * console.log(utils.isInsideType(state, 'brace')); //=> false + * ``` + * @param {Object} `state` + * @param {String} `type` + * @return {Boolean} + * @api public */ -module.exports = isAccessorDescriptor; +utils.isInsideType = function(state, type) { + assert(isObject(state), 'expected state to be an object'); + assert(isString(type), 'expected type to be a string'); + if (!state.hasOwnProperty('inside')) { + return false; + } -/***/ }), -/* 689 */ -/***/ (function(module, exports, __webpack_require__) { + if (!state.inside.hasOwnProperty(type)) { + return false; + } -var isBuffer = __webpack_require__(642); -var toString = Object.prototype.toString; + return state.inside[type].length > 0; +}; /** - * Get the native `typeof` a value. + * Returns true if `node` is either a child or grand-child of the given `type`, + * or `state.inside[type]` is a non-empty array. * - * @param {*} `val` - * @return {*} Native javascript type + * ```js + * var state = { inside: {}}; + * var node = new Node({type: 'brace'}); + * var open = new Node({type: 'brace.open'}); + * console.log(utils.isInside(state, open, 'brace')); //=> false + * utils.pushNode(node, open); + * console.log(utils.isInside(state, open, 'brace')); //=> true + * ``` + * @param {Object} `state` Either the `compiler.state` object, if it exists, or a user-supplied state object. + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {String} `type` The `node.type` to check for. + * @return {Boolean} + * @api public */ -module.exports = function kindOf(val) { - // primitivies - if (typeof val === 'undefined') { - return 'undefined'; - } - if (val === null) { - return 'null'; - } - if (val === true || val === false || val instanceof Boolean) { - return 'boolean'; - } - if (typeof val === 'string' || val instanceof String) { - return 'string'; - } - if (typeof val === 'number' || val instanceof Number) { - return 'number'; - } +utils.isInside = function(state, node, type) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + assert(isObject(state), 'expected state to be an object'); - // functions - if (typeof val === 'function' || val instanceof Function) { - return 'function'; + if (Array.isArray(type)) { + for (var i = 0; i < type.length; i++) { + if (utils.isInside(state, node, type[i])) { + return true; + } + } + return false; } - // array - if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { - return 'array'; + var parent = node.parent; + if (typeof type === 'string') { + return (parent && parent.type === type) || utils.isInsideType(state, type); } - // check for instances of RegExp and Date before calling `toString` - if (val instanceof RegExp) { - return 'regexp'; - } - if (val instanceof Date) { - return 'date'; - } + if (typeOf(type) === 'regexp') { + if (parent && parent.type && type.test(parent.type)) { + return true; + } - // other objects - var type = toString.call(val); + var keys = Object.keys(state.inside); + var len = keys.length; + var idx = -1; + while (++idx < len) { + var key = keys[idx]; + var val = state.inside[key]; - if (type === '[object RegExp]') { - return 'regexp'; - } - if (type === '[object Date]') { - return 'date'; - } - if (type === '[object Arguments]') { - return 'arguments'; - } - if (type === '[object Error]') { - return 'error'; + if (Array.isArray(val) && val.length !== 0 && type.test(key)) { + return true; + } + } } + return false; +}; - // buffer - if (isBuffer(val)) { - return 'buffer'; - } +/** + * Get the last `n` element from the given `array`. Used for getting + * a node from `node.nodes.` + * + * @param {Array} `array` + * @param {Number} `n` + * @return {undefined} + * @api public + */ - // es6: Map, WeakMap, Set, WeakSet - if (type === '[object Set]') { - return 'set'; - } - if (type === '[object WeakSet]') { - return 'weakset'; - } - if (type === '[object Map]') { - return 'map'; - } - if (type === '[object WeakMap]') { - return 'weakmap'; - } - if (type === '[object Symbol]') { - return 'symbol'; - } +utils.last = function(arr, n) { + return arr[arr.length - (n || 1)]; +}; - // typed arrays - if (type === '[object Int8Array]') { - return 'int8array'; - } - if (type === '[object Uint8Array]') { - return 'uint8array'; - } - if (type === '[object Uint8ClampedArray]') { - return 'uint8clampedarray'; - } - if (type === '[object Int16Array]') { - return 'int16array'; - } - if (type === '[object Uint16Array]') { - return 'uint16array'; - } - if (type === '[object Int32Array]') { - return 'int32array'; - } - if (type === '[object Uint32Array]') { - return 'uint32array'; - } - if (type === '[object Float32Array]') { - return 'float32array'; +/** + * Cast the given `val` to an array. + * + * ```js + * console.log(utils.arrayify('')); + * //=> [] + * console.log(utils.arrayify('foo')); + * //=> ['foo'] + * console.log(utils.arrayify(['foo'])); + * //=> ['foo'] + * ``` + * @param {any} `val` + * @return {Array} + * @api public + */ + +utils.arrayify = function(val) { + if (typeof val === 'string' && val !== '') { + return [val]; } - if (type === '[object Float64Array]') { - return 'float64array'; + if (!Array.isArray(val)) { + return []; } - - // must be a plain object - return 'object'; + return val; }; +/** + * Convert the given `val` to a string by joining with `,`. Useful + * for creating a cheerio/CSS/DOM-style selector from a list of strings. + * + * @param {any} `val` + * @return {Array} + * @api public + */ -/***/ }), -/* 690 */ -/***/ (function(module, exports, __webpack_require__) { +utils.stringify = function(val) { + return utils.arrayify(val).join(','); +}; -"use strict"; -/*! - * is-data-descriptor +/** + * Ensure that the given value is a string and call `.trim()` on it, + * or return an empty string. * - * Copyright (c) 2015, Jon Schlinkert. - * Licensed under the MIT License. + * @param {String} `str` + * @return {String} + * @api public */ +utils.trim = function(str) { + return typeof str === 'string' ? str.trim() : ''; +}; +/** + * Return true if val is an object + */ -var typeOf = __webpack_require__(691); +function isObject(val) { + return typeOf(val) === 'object'; +} -// data descriptor properties -var data = { - configurable: 'boolean', - enumerable: 'boolean', - writable: 'boolean' -}; +/** + * Return true if val is a string + */ -function isDataDescriptor(obj, prop) { - if (typeOf(obj) !== 'object') { - return false; - } +function isString(val) { + return typeof val === 'string'; +} - if (typeof prop === 'string') { - var val = Object.getOwnPropertyDescriptor(obj, prop); - return typeof val !== 'undefined'; - } +/** + * Return true if val is a function + */ - if (!('value' in obj) && !('writable' in obj)) { - return false; - } +function isFunction(val) { + return typeof val === 'function'; +} - for (var key in obj) { - if (key === 'value') continue; +/** + * Return true if val is an array + */ - if (!data.hasOwnProperty(key)) { - continue; - } +function isArray(val) { + return Array.isArray(val); +} - if (typeOf(obj[key]) === data[key]) { - continue; - } +/** + * Shim to ensure the `.append` methods work with any version of snapdragon + */ - if (typeof obj[key] !== 'undefined') { - return false; - } +function append(compiler, val, node) { + if (typeof compiler.append !== 'function') { + return compiler.emit(val, node); } - return true; + return compiler.append(val, node); } /** - * Expose `isDataDescriptor` + * Simplified assertion. Throws an error is `val` is falsey. */ -module.exports = isDataDescriptor; +function assert(val, message) { + if (!val) throw new Error(message); +} /***/ }), -/* 691 */ +/* 690 */ /***/ (function(module, exports, __webpack_require__) { -var isBuffer = __webpack_require__(642); +var isBuffer = __webpack_require__(680); var toString = Object.prototype.toString; /** @@ -70940,684 +70061,1258 @@ module.exports = function kindOf(val) { /***/ }), -/* 692 */ +/* 691 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/*! - * static-extend - * - * Copyright (c) 2016, Jon Schlinkert. - * Licensed under the MIT License. - */ +var extend = __webpack_require__(669); +var Snapdragon = __webpack_require__(692); +var compilers = __webpack_require__(671); +var parsers = __webpack_require__(686); +var utils = __webpack_require__(672); -var copy = __webpack_require__(693); -var define = __webpack_require__(685); -var util = __webpack_require__(234); +/** + * Customize Snapdragon parser and renderer + */ + +function Braces(options) { + this.options = extend({}, options); +} /** - * Returns a function for extending the static properties, - * prototype properties, and descriptors from the `Parent` - * constructor onto `Child` constructors. - * - * ```js - * var extend = require('static-extend'); - * Parent.extend = extend(Parent); - * - * // optionally pass a custom merge function as the second arg - * Parent.extend = extend(Parent, function(Child) { - * Child.prototype.mixin = function(key, val) { - * Child.prototype[key] = val; - * }; - * }); - * - * // extend "child" constructors - * Parent.extend(Child); - * - * // optionally define prototype methods as the second arg - * Parent.extend(Child, { - * foo: function() {}, - * bar: function() {} - * }); - * ``` - * @param {Function} `Parent` Parent ctor - * @param {Function} `extendFn` Optional extend function for handling any necessary custom merging. Useful when updating methods that require a specific prototype. - * @param {Function} `Child` Child ctor - * @param {Object} `proto` Optionally pass additional prototype properties to inherit. - * @return {Object} - * @api public + * Initialize braces */ -function extend(Parent, extendFn) { - if (typeof Parent !== 'function') { - throw new TypeError('expected Parent to be a function.'); - } +Braces.prototype.init = function(options) { + if (this.isInitialized) return; + this.isInitialized = true; + var opts = utils.createOptions({}, this.options, options); + this.snapdragon = this.options.snapdragon || new Snapdragon(opts); + this.compiler = this.snapdragon.compiler; + this.parser = this.snapdragon.parser; - return function(Ctor, proto) { - if (typeof Ctor !== 'function') { - throw new TypeError('expected Ctor to be a function.'); - } + compilers(this.snapdragon, opts); + parsers(this.snapdragon, opts); - util.inherits(Ctor, Parent); - copy(Ctor, Parent); + /** + * Call Snapdragon `.parse` method. When AST is returned, we check to + * see if any unclosed braces are left on the stack and, if so, we iterate + * over the stack and correct the AST so that compilers are called in the correct + * order and unbalance braces are properly escaped. + */ - // proto can be null or a plain object - if (typeof proto === 'object') { - var obj = Object.create(proto); + utils.define(this.snapdragon, 'parse', function(pattern, options) { + var parsed = Snapdragon.prototype.parse.apply(this, arguments); + this.parser.ast.input = pattern; - for (var k in obj) { - Ctor.prototype[k] = obj[k]; - } + var stack = this.parser.stack; + while (stack.length) { + addParent({type: 'brace.close', val: ''}, stack.pop()); } - // keep a reference to the parent prototype - define(Ctor.prototype, '_parent_', { - configurable: true, - set: function() {}, - get: function() { - return Parent.prototype; - } - }); - - if (typeof extendFn === 'function') { - extendFn(Ctor, Parent); + function addParent(node, parent) { + utils.define(node, 'parent', parent); + parent.nodes.push(node); } - Ctor.extend = extend(Ctor, extendFn); - }; + // add non-enumerable parser reference + utils.define(parsed, 'parser', this.parser); + return parsed; + }); }; /** - * Expose `extend` + * Decorate `.parse` method */ -module.exports = extend; +Braces.prototype.parse = function(ast, options) { + if (ast && typeof ast === 'object' && ast.nodes) return ast; + this.init(options); + return this.snapdragon.parse(ast, options); +}; + +/** + * Decorate `.compile` method + */ + +Braces.prototype.compile = function(ast, options) { + if (typeof ast === 'string') { + ast = this.parse(ast, options); + } else { + this.init(options); + } + return this.snapdragon.compile(ast, options); +}; + +/** + * Expand + */ + +Braces.prototype.expand = function(pattern) { + var ast = this.parse(pattern, {expand: true}); + return this.compile(ast, {expand: true}); +}; + +/** + * Optimize + */ + +Braces.prototype.optimize = function(pattern) { + var ast = this.parse(pattern, {optimize: true}); + return this.compile(ast, {optimize: true}); +}; + +/** + * Expose `Braces` + */ + +module.exports = Braces; /***/ }), -/* 693 */ +/* 692 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var typeOf = __webpack_require__(694); -var copyDescriptor = __webpack_require__(695); -var define = __webpack_require__(685); +var Base = __webpack_require__(693); +var define = __webpack_require__(723); +var Compiler = __webpack_require__(734); +var Parser = __webpack_require__(757); +var utils = __webpack_require__(737); +var regexCache = {}; +var cache = {}; /** - * Copy static properties, prototype properties, and descriptors from one object to another. + * Create a new instance of `Snapdragon` with the given `options`. * * ```js - * function App() {} - * var proto = App.prototype; - * App.prototype.set = function() {}; - * App.prototype.get = function() {}; - * - * var obj = {}; - * copy(obj, proto); + * var snapdragon = new Snapdragon(); * ``` - * @param {Object} `receiver` - * @param {Object} `provider` - * @param {String|Array} `omit` One or more properties to omit - * @return {Object} + * + * @param {Object} `options` * @api public */ -function copy(receiver, provider, omit) { - if (!isObject(receiver)) { - throw new TypeError('expected receiving object to be an object.'); - } - if (!isObject(provider)) { - throw new TypeError('expected providing object to be an object.'); - } +function Snapdragon(options) { + Base.call(this, null, options); + this.options = utils.extend({source: 'string'}, this.options); + this.compiler = new Compiler(this.options); + this.parser = new Parser(this.options); - var props = nativeKeys(provider); - var keys = Object.keys(provider); - var len = props.length; - omit = arrayify(omit); + Object.defineProperty(this, 'compilers', { + get: function() { + return this.compiler.compilers; + } + }); - while (len--) { - var key = props[len]; + Object.defineProperty(this, 'parsers', { + get: function() { + return this.parser.parsers; + } + }); - if (has(keys, key)) { - define(receiver, key, provider[key]); - } else if (!(key in receiver) && !has(omit, key)) { - copyDescriptor(receiver, provider, key); + Object.defineProperty(this, 'regex', { + get: function() { + return this.parser.regex; } - } + }); +} + +/** + * Inherit Base + */ + +Base.extend(Snapdragon); + +/** + * Add a parser to `snapdragon.parsers` for capturing the given `type` using + * the specified regex or parser function. A function is useful if you need + * to customize how the token is created and/or have access to the parser + * instance to check options, etc. + * + * ```js + * snapdragon + * .capture('slash', /^\//) + * .capture('dot', function() { + * var pos = this.position(); + * var m = this.match(/^\./); + * if (!m) return; + * return pos({ + * type: 'dot', + * val: m[0] + * }); + * }); + * ``` + * @param {String} `type` + * @param {RegExp|Function} `regex` + * @return {Object} Returns the parser instance for chaining + * @api public + */ + +Snapdragon.prototype.capture = function() { + return this.parser.capture.apply(this.parser, arguments); }; /** - * Return true if the given value is an object or function + * Register a plugin `fn`. + * + * ```js + * var snapdragon = new Snapdgragon([options]); + * snapdragon.use(function() { + * console.log(this); //<= snapdragon instance + * console.log(this.parser); //<= parser instance + * console.log(this.compiler); //<= compiler instance + * }); + * ``` + * @param {Object} `fn` + * @api public */ -function isObject(val) { - return typeOf(val) === 'object' || typeof val === 'function'; -} +Snapdragon.prototype.use = function(fn) { + fn.call(this, this); + return this; +}; /** - * Returns true if an array has any of the given elements, or an - * object has any of the give keys. + * Parse the given `str`. * * ```js - * has(['a', 'b', 'c'], 'c'); - * //=> true + * var snapdragon = new Snapdgragon([options]); + * // register parsers + * snapdragon.parser.use(function() {}); * - * has(['a', 'b', 'c'], ['c', 'z']); - * //=> true + * // parse + * var ast = snapdragon.parse('foo/bar'); + * console.log(ast); + * ``` + * @param {String} `str` + * @param {Object} `options` Set `options.sourcemap` to true to enable source maps. + * @return {Object} Returns an AST. + * @api public + */ + +Snapdragon.prototype.parse = function(str, options) { + this.options = utils.extend({}, this.options, options); + var parsed = this.parser.parse(str, this.options); + + // add non-enumerable parser reference + define(parsed, 'parser', this.parser); + return parsed; +}; + +/** + * Compile the given `AST`. * - * has({a: 'b', c: 'd'}, ['c', 'z']); - * //=> true + * ```js + * var snapdragon = new Snapdgragon([options]); + * // register plugins + * snapdragon.use(function() {}); + * // register parser plugins + * snapdragon.parser.use(function() {}); + * // register compiler plugins + * snapdragon.compiler.use(function() {}); + * + * // parse + * var ast = snapdragon.parse('foo/bar'); + * + * // compile + * var res = snapdragon.compile(ast); + * console.log(res.output); * ``` - * @param {Object} `obj` - * @param {String|Array} `val` - * @return {Boolean} + * @param {Object} `ast` + * @param {Object} `options` + * @return {Object} Returns an object with an `output` property with the rendered string. + * @api public */ -function has(obj, val) { - val = arrayify(val); - var len = val.length; +Snapdragon.prototype.compile = function(ast, options) { + this.options = utils.extend({}, this.options, options); + var compiled = this.compiler.compile(ast, this.options); + + // add non-enumerable compiler reference + define(compiled, 'compiler', this.compiler); + return compiled; +}; + +/** + * Expose `Snapdragon` + */ + +module.exports = Snapdragon; + +/** + * Expose `Parser` and `Compiler` + */ + +module.exports.Compiler = Compiler; +module.exports.Parser = Parser; + + +/***/ }), +/* 693 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var util = __webpack_require__(234); +var define = __webpack_require__(694); +var CacheBase = __webpack_require__(695); +var Emitter = __webpack_require__(696); +var isObject = __webpack_require__(656); +var merge = __webpack_require__(717); +var pascal = __webpack_require__(720); +var cu = __webpack_require__(721); + +/** + * Optionally define a custom `cache` namespace to use. + */ + +function namespace(name) { + var Cache = name ? CacheBase.namespace(name) : CacheBase; + var fns = []; + + /** + * Create an instance of `Base` with the given `config` and `options`. + * + * ```js + * // initialize with `config` and `options` + * var app = new Base({isApp: true}, {abc: true}); + * app.set('foo', 'bar'); + * + * // values defined with the given `config` object will be on the root of the instance + * console.log(app.baz); //=> undefined + * console.log(app.foo); //=> 'bar' + * // or use `.get` + * console.log(app.get('isApp')); //=> true + * console.log(app.get('foo')); //=> 'bar' + * + * // values defined with the given `options` object will be on `app.options + * console.log(app.options.abc); //=> true + * ``` + * + * @param {Object} `config` If supplied, this object is passed to [cache-base][] to merge onto the the instance upon instantiation. + * @param {Object} `options` If supplied, this object is used to initialize the `base.options` object. + * @api public + */ + + function Base(config, options) { + if (!(this instanceof Base)) { + return new Base(config, options); + } + Cache.call(this, config); + this.is('base'); + this.initBase(config, options); + } + + /** + * Inherit cache-base + */ + + util.inherits(Base, Cache); + + /** + * Add static emitter methods + */ + + Emitter(Base); + + /** + * Initialize `Base` defaults with the given `config` object + */ + + Base.prototype.initBase = function(config, options) { + this.options = merge({}, this.options, options); + this.cache = this.cache || {}; + this.define('registered', {}); + if (name) this[name] = {}; + + // make `app._callbacks` non-enumerable + this.define('_callbacks', this._callbacks); + if (isObject(config)) { + this.visit('set', config); + } + Base.run(this, 'use', fns); + }; + + /** + * Set the given `name` on `app._name` and `app.is*` properties. Used for doing + * lookups in plugins. + * + * ```js + * app.is('foo'); + * console.log(app._name); + * //=> 'foo' + * console.log(app.isFoo); + * //=> true + * app.is('bar'); + * console.log(app.isFoo); + * //=> true + * console.log(app.isBar); + * //=> true + * console.log(app._name); + * //=> 'bar' + * ``` + * @name .is + * @param {String} `name` + * @return {Boolean} + * @api public + */ + + Base.prototype.is = function(name) { + if (typeof name !== 'string') { + throw new TypeError('expected name to be a string'); + } + this.define('is' + pascal(name), true); + this.define('_name', name); + this.define('_appname', name); + return this; + }; + + /** + * Returns true if a plugin has already been registered on an instance. + * + * Plugin implementors are encouraged to use this first thing in a plugin + * to prevent the plugin from being called more than once on the same + * instance. + * + * ```js + * var base = new Base(); + * base.use(function(app) { + * if (app.isRegistered('myPlugin')) return; + * // do stuff to `app` + * }); + * + * // to also record the plugin as being registered + * base.use(function(app) { + * if (app.isRegistered('myPlugin', true)) return; + * // do stuff to `app` + * }); + * ``` + * @name .isRegistered + * @emits `plugin` Emits the name of the plugin being registered. Useful for unit tests, to ensure plugins are only registered once. + * @param {String} `name` The plugin name. + * @param {Boolean} `register` If the plugin if not already registered, to record it as being registered pass `true` as the second argument. + * @return {Boolean} Returns true if a plugin is already registered. + * @api public + */ - if (isObject(obj)) { - for (var key in obj) { - if (val.indexOf(key) > -1) { - return true; - } + Base.prototype.isRegistered = function(name, register) { + if (this.registered.hasOwnProperty(name)) { + return true; } - - var keys = nativeKeys(obj); - return has(keys, val); - } - - if (Array.isArray(obj)) { - var arr = obj; - while (len--) { - if (arr.indexOf(val[len]) > -1) { - return true; - } + if (register !== false) { + this.registered[name] = true; + this.emit('plugin', name); } return false; - } + }; - throw new TypeError('expected an array or object.'); -} + /** + * Define a plugin function to be called immediately upon init. Plugins are chainable + * and expose the following arguments to the plugin function: + * + * - `app`: the current instance of `Base` + * - `base`: the [first ancestor instance](#base) of `Base` + * + * ```js + * var app = new Base() + * .use(foo) + * .use(bar) + * .use(baz) + * ``` + * @name .use + * @param {Function} `fn` plugin function to call + * @return {Object} Returns the item instance for chaining. + * @api public + */ -/** - * Cast the given value to an array. - * - * ```js - * arrayify('foo'); - * //=> ['foo'] - * - * arrayify(['foo']); - * //=> ['foo'] - * ``` - * - * @param {String|Array} `val` - * @return {Array} - */ + Base.prototype.use = function(fn) { + fn.call(this, this); + return this; + }; -function arrayify(val) { - return val ? (Array.isArray(val) ? val : [val]) : []; -} + /** + * The `.define` method is used for adding non-enumerable property on the instance. + * Dot-notation is **not supported** with `define`. + * + * ```js + * // arbitrary `render` function using lodash `template` + * app.define('render', function(str, locals) { + * return _.template(str)(locals); + * }); + * ``` + * @name .define + * @param {String} `key` The name of the property to define. + * @param {any} `value` + * @return {Object} Returns the instance for chaining. + * @api public + */ -/** - * Returns true if a value has a `contructor` - * - * ```js - * hasConstructor({}); - * //=> true - * - * hasConstructor(Object.create(null)); - * //=> false - * ``` - * @param {Object} `value` - * @return {Boolean} - */ + Base.prototype.define = function(key, val) { + if (isObject(key)) { + return this.visit('define', key); + } + define(this, key, val); + return this; + }; -function hasConstructor(val) { - return isObject(val) && typeof val.constructor !== 'undefined'; -} + /** + * Mix property `key` onto the Base prototype. If base is inherited using + * `Base.extend` this method will be overridden by a new `mixin` method that will + * only add properties to the prototype of the inheriting application. + * + * ```js + * app.mixin('foo', function() { + * // do stuff + * }); + * ``` + * @name .mixin + * @param {String} `key` + * @param {Object|Array} `val` + * @return {Object} Returns the `base` instance for chaining. + * @api public + */ -/** - * Get the native `ownPropertyNames` from the constructor of the - * given `object`. An empty array is returned if the object does - * not have a constructor. - * - * ```js - * nativeKeys({a: 'b', b: 'c', c: 'd'}) - * //=> ['a', 'b', 'c'] - * - * nativeKeys(function(){}) - * //=> ['length', 'caller'] - * ``` - * - * @param {Object} `obj` Object that has a `constructor`. - * @return {Array} Array of keys. - */ + Base.prototype.mixin = function(key, val) { + Base.prototype[key] = val; + return this; + }; -function nativeKeys(val) { - if (!hasConstructor(val)) return []; - return Object.getOwnPropertyNames(val); -} + /** + * Non-enumberable mixin array, used by the static [Base.mixin]() method. + */ -/** - * Expose `copy` - */ + Base.prototype.mixins = Base.prototype.mixins || []; -module.exports = copy; + /** + * Getter/setter used when creating nested instances of `Base`, for storing a reference + * to the first ancestor instance. This works by setting an instance of `Base` on the `parent` + * property of a "child" instance. The `base` property defaults to the current instance if + * no `parent` property is defined. + * + * ```js + * // create an instance of `Base`, this is our first ("base") instance + * var first = new Base(); + * first.foo = 'bar'; // arbitrary property, to make it easier to see what's happening later + * + * // create another instance + * var second = new Base(); + * // create a reference to the first instance (`first`) + * second.parent = first; + * + * // create another instance + * var third = new Base(); + * // create a reference to the previous instance (`second`) + * // repeat this pattern every time a "child" instance is created + * third.parent = second; + * + * // we can always access the first instance using the `base` property + * console.log(first.base.foo); + * //=> 'bar' + * console.log(second.base.foo); + * //=> 'bar' + * console.log(third.base.foo); + * //=> 'bar' + * // and now you know how to get to third base ;) + * ``` + * @name .base + * @api public + */ -/** - * Expose `copy.has` for tests - */ + Object.defineProperty(Base.prototype, 'base', { + configurable: true, + get: function() { + return this.parent ? this.parent.base : this; + } + }); -module.exports.has = has; + /** + * Static method for adding global plugin functions that will + * be added to an instance when created. + * + * ```js + * Base.use(function(app) { + * app.foo = 'bar'; + * }); + * var app = new Base(); + * console.log(app.foo); + * //=> 'bar' + * ``` + * @name #use + * @param {Function} `fn` Plugin function to use on each instance. + * @return {Object} Returns the `Base` constructor for chaining + * @api public + */ + define(Base, 'use', function(fn) { + fns.push(fn); + return Base; + }); -/***/ }), -/* 694 */ -/***/ (function(module, exports, __webpack_require__) { + /** + * Run an array of functions by passing each function + * to a method on the given object specified by the given property. + * + * @param {Object} `obj` Object containing method to use. + * @param {String} `prop` Name of the method on the object to use. + * @param {Array} `arr` Array of functions to pass to the method. + */ -var isBuffer = __webpack_require__(642); -var toString = Object.prototype.toString; + define(Base, 'run', function(obj, prop, arr) { + var len = arr.length, i = 0; + while (len--) { + obj[prop](arr[i++]); + } + return Base; + }); -/** - * Get the native `typeof` a value. - * - * @param {*} `val` - * @return {*} Native javascript type - */ + /** + * Static method for inheriting the prototype and static methods of the `Base` class. + * This method greatly simplifies the process of creating inheritance-based applications. + * See [static-extend][] for more details. + * + * ```js + * var extend = cu.extend(Parent); + * Parent.extend(Child); + * + * // optional methods + * Parent.extend(Child, { + * foo: function() {}, + * bar: function() {} + * }); + * ``` + * @name #extend + * @param {Function} `Ctor` constructor to extend + * @param {Object} `methods` Optional prototype properties to mix in. + * @return {Object} Returns the `Base` constructor for chaining + * @api public + */ -module.exports = function kindOf(val) { - // primitivies - if (typeof val === 'undefined') { - return 'undefined'; - } - if (val === null) { - return 'null'; - } - if (val === true || val === false || val instanceof Boolean) { - return 'boolean'; - } - if (typeof val === 'string' || val instanceof String) { - return 'string'; - } - if (typeof val === 'number' || val instanceof Number) { - return 'number'; - } + define(Base, 'extend', cu.extend(Base, function(Ctor, Parent) { + Ctor.prototype.mixins = Ctor.prototype.mixins || []; - // functions - if (typeof val === 'function' || val instanceof Function) { - return 'function'; - } + define(Ctor, 'mixin', function(fn) { + var mixin = fn(Ctor.prototype, Ctor); + if (typeof mixin === 'function') { + Ctor.prototype.mixins.push(mixin); + } + return Ctor; + }); - // array - if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { - return 'array'; - } + define(Ctor, 'mixins', function(Child) { + Base.run(Child, 'mixin', Ctor.prototype.mixins); + return Ctor; + }); - // check for instances of RegExp and Date before calling `toString` - if (val instanceof RegExp) { - return 'regexp'; - } - if (val instanceof Date) { - return 'date'; - } + Ctor.prototype.mixin = function(key, value) { + Ctor.prototype[key] = value; + return this; + }; + return Base; + })); - // other objects - var type = toString.call(val); + /** + * Used for adding methods to the `Base` prototype, and/or to the prototype of child instances. + * When a mixin function returns a function, the returned function is pushed onto the `.mixins` + * array, making it available to be used on inheriting classes whenever `Base.mixins()` is + * called (e.g. `Base.mixins(Child)`). + * + * ```js + * Base.mixin(function(proto) { + * proto.foo = function(msg) { + * return 'foo ' + msg; + * }; + * }); + * ``` + * @name #mixin + * @param {Function} `fn` Function to call + * @return {Object} Returns the `Base` constructor for chaining + * @api public + */ - if (type === '[object RegExp]') { - return 'regexp'; - } - if (type === '[object Date]') { - return 'date'; - } - if (type === '[object Arguments]') { - return 'arguments'; - } - if (type === '[object Error]') { - return 'error'; - } + define(Base, 'mixin', function(fn) { + var mixin = fn(Base.prototype, Base); + if (typeof mixin === 'function') { + Base.prototype.mixins.push(mixin); + } + return Base; + }); - // buffer - if (isBuffer(val)) { - return 'buffer'; - } + /** + * Static method for running global mixin functions against a child constructor. + * Mixins must be registered before calling this method. + * + * ```js + * Base.extend(Child); + * Base.mixins(Child); + * ``` + * @name #mixins + * @param {Function} `Child` Constructor function of a child class + * @return {Object} Returns the `Base` constructor for chaining + * @api public + */ - // es6: Map, WeakMap, Set, WeakSet - if (type === '[object Set]') { - return 'set'; - } - if (type === '[object WeakSet]') { - return 'weakset'; - } - if (type === '[object Map]') { - return 'map'; - } - if (type === '[object WeakMap]') { - return 'weakmap'; - } - if (type === '[object Symbol]') { - return 'symbol'; - } + define(Base, 'mixins', function(Child) { + Base.run(Child, 'mixin', Base.prototype.mixins); + return Base; + }); - // typed arrays - if (type === '[object Int8Array]') { - return 'int8array'; - } - if (type === '[object Uint8Array]') { - return 'uint8array'; - } - if (type === '[object Uint8ClampedArray]') { - return 'uint8clampedarray'; - } - if (type === '[object Int16Array]') { - return 'int16array'; - } - if (type === '[object Uint16Array]') { - return 'uint16array'; - } - if (type === '[object Int32Array]') { - return 'int32array'; - } - if (type === '[object Uint32Array]') { - return 'uint32array'; - } - if (type === '[object Float32Array]') { - return 'float32array'; - } - if (type === '[object Float64Array]') { - return 'float64array'; - } + /** + * Similar to `util.inherit`, but copies all static properties, prototype properties, and + * getters/setters from `Provider` to `Receiver`. See [class-utils][]{#inherit} for more details. + * + * ```js + * Base.inherit(Foo, Bar); + * ``` + * @name #inherit + * @param {Function} `Receiver` Receiving (child) constructor + * @param {Function} `Provider` Providing (parent) constructor + * @return {Object} Returns the `Base` constructor for chaining + * @api public + */ - // must be a plain object - return 'object'; -}; + define(Base, 'inherit', cu.inherit); + define(Base, 'bubble', cu.bubble); + return Base; +} +/** + * Expose `Base` with default settings + */ -/***/ }), -/* 695 */ -/***/ (function(module, exports, __webpack_require__) { +module.exports = namespace(); -"use strict"; -/*! - * copy-descriptor - * - * Copyright (c) 2015, Jon Schlinkert. - * Licensed under the MIT License. +/** + * Allow users to define a namespace */ +module.exports.namespace = namespace; -/** - * Copy a descriptor from one object to another. - * - * ```js - * function App() { - * this.cache = {}; - * } - * App.prototype.set = function(key, val) { - * this.cache[key] = val; - * return this; - * }; - * Object.defineProperty(App.prototype, 'count', { - * get: function() { - * return Object.keys(this.cache).length; - * } - * }); - * - * copy(App.prototype, 'count', 'len'); - * - * // create an instance - * var app = new App(); - * - * app.set('a', true); - * app.set('b', true); - * app.set('c', true); - * - * console.log(app.count); - * //=> 3 - * console.log(app.len); - * //=> 3 - * ``` - * @name copy - * @param {Object} `receiver` The target object - * @param {Object} `provider` The provider object - * @param {String} `from` The key to copy on provider. - * @param {String} `to` Optionally specify a new key name to use. - * @return {Object} - * @api public +/***/ }), +/* 694 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * define-property + * + * Copyright (c) 2015, 2017, Jon Schlinkert. + * Released under the MIT License. */ -module.exports = function copyDescriptor(receiver, provider, from, to) { - if (!isObject(provider) && typeof provider !== 'function') { - to = from; - from = provider; - provider = receiver; - } - if (!isObject(receiver) && typeof receiver !== 'function') { - throw new TypeError('expected the first argument to be an object'); - } - if (!isObject(provider) && typeof provider !== 'function') { - throw new TypeError('expected provider to be an object'); - } - if (typeof to !== 'string') { - to = from; + +var isDescriptor = __webpack_require__(657); + +module.exports = function defineProperty(obj, prop, val) { + if (typeof obj !== 'object' && typeof obj !== 'function') { + throw new TypeError('expected an object or function.'); } - if (typeof from !== 'string') { - throw new TypeError('expected key to be a string'); + + if (typeof prop !== 'string') { + throw new TypeError('expected `prop` to be a string.'); } - if (!(from in provider)) { - throw new Error('property "' + from + '" does not exist'); + if (isDescriptor(val) && ('set' in val || 'get' in val)) { + return Object.defineProperty(obj, prop, val); } - var val = Object.getOwnPropertyDescriptor(provider, from); - if (val) Object.defineProperty(receiver, to, val); + return Object.defineProperty(obj, prop, { + configurable: true, + enumerable: false, + writable: true, + value: val + }); }; -function isObject(val) { - return {}.toString.call(val) === '[object Object]'; -} - - /***/ }), -/* 696 */ +/* 695 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var use = __webpack_require__(697); -var define = __webpack_require__(685); -var debug = __webpack_require__(326)('snapdragon:compiler'); -var utils = __webpack_require__(699); +var isObject = __webpack_require__(656); +var Emitter = __webpack_require__(696); +var visit = __webpack_require__(697); +var toPath = __webpack_require__(700); +var union = __webpack_require__(702); +var del = __webpack_require__(708); +var get = __webpack_require__(705); +var has = __webpack_require__(713); +var set = __webpack_require__(716); /** - * Create a new `Compiler` with the given `options`. - * @param {Object} `options` + * Create a `Cache` constructor that when instantiated will + * store values on the given `prop`. + * + * ```js + * var Cache = require('cache-base').namespace('data'); + * var cache = new Cache(); + * + * cache.set('foo', 'bar'); + * //=> {data: {foo: 'bar'}} + * ``` + * @param {String} `prop` The property name to use for storing values. + * @return {Function} Returns a custom `Cache` constructor + * @api public */ -function Compiler(options, state) { - debug('initializing', __filename); - this.options = utils.extend({source: 'string'}, options); - this.state = state || {}; - this.compilers = {}; - this.output = ''; - this.set('eos', function(node) { - return this.emit(node.val, node); - }); - this.set('noop', function(node) { - return this.emit(node.val, node); - }); - this.set('bos', function(node) { - return this.emit(node.val, node); - }); - use(this); -} +function namespace(prop) { -/** - * Prototype methods - */ + /** + * Create a new `Cache`. Internally the `Cache` constructor is created using + * the `namespace` function, with `cache` defined as the storage object. + * + * ```js + * var app = new Cache(); + * ``` + * @param {Object} `cache` Optionally pass an object to initialize with. + * @constructor + * @api public + */ -Compiler.prototype = { + function Cache(cache) { + if (prop) { + this[prop] = {}; + } + if (cache) { + this.set(cache); + } + } /** - * Throw an error message with details including the cursor position. - * @param {String} `msg` Message to use in the Error. + * Inherit Emitter */ - error: function(msg, node) { - var pos = node.position || {start: {column: 0}}; - var message = this.options.source + ' column:' + pos.start.column + ': ' + msg; + Emitter(Cache.prototype); - var err = new Error(message); - err.reason = msg; - err.column = pos.start.column; - err.source = this.pattern; + /** + * Assign `value` to `key`. Also emits `set` with + * the key and value. + * + * ```js + * app.on('set', function(key, val) { + * // do something when `set` is emitted + * }); + * + * app.set(key, value); + * + * // also takes an object or array + * app.set({name: 'Halle'}); + * app.set([{foo: 'bar'}, {baz: 'quux'}]); + * console.log(app); + * //=> {name: 'Halle', foo: 'bar', baz: 'quux'} + * ``` + * + * @name .set + * @emits `set` with `key` and `value` as arguments. + * @param {String} `key` + * @param {any} `value` + * @return {Object} Returns the instance for chaining. + * @api public + */ - if (this.options.silent) { - this.errors.push(err); + Cache.prototype.set = function(key, val) { + if (Array.isArray(key) && arguments.length === 2) { + key = toPath(key); + } + if (isObject(key) || Array.isArray(key)) { + this.visit('set', key); } else { - throw err; + set(prop ? this[prop] : this, key, val); + this.emit('set', key, val); } - }, + return this; + }; /** - * Define a non-enumberable property on the `Compiler` instance. + * Union `array` to `key`. Also emits `set` with + * the key and value. * * ```js - * compiler.define('foo', 'bar'); + * app.union('a.b', ['foo']); + * app.union('a.b', ['bar']); + * console.log(app.get('a')); + * //=> {b: ['foo', 'bar']} * ``` - * @name .define - * @param {String} `key` propery name - * @param {any} `val` property value - * @return {Object} Returns the Compiler instance for chaining. + * @name .union + * @param {String} `key` + * @param {any} `value` + * @return {Object} Returns the instance for chaining. * @api public */ - define: function(key, val) { - define(this, key, val); + Cache.prototype.union = function(key, val) { + if (Array.isArray(key) && arguments.length === 2) { + key = toPath(key); + } + var ctx = prop ? this[prop] : this; + union(ctx, key, arrayify(val)); + this.emit('union', val); return this; - }, + }; /** - * Emit `node.val` + * Return the value of `key`. Dot notation may be used + * to get [nested property values][get-value]. + * + * ```js + * app.set('a.b.c', 'd'); + * app.get('a.b'); + * //=> {c: 'd'} + * + * app.get(['a', 'b']); + * //=> {c: 'd'} + * ``` + * + * @name .get + * @emits `get` with `key` and `value` as arguments. + * @param {String} `key` The name of the property to get. Dot-notation may be used. + * @return {any} Returns the value of `key` + * @api public */ - emit: function(str, node) { - this.output += str; - return str; - }, + Cache.prototype.get = function(key) { + key = toPath(arguments); - /** - * Add a compiler `fn` with the given `name` - */ + var ctx = prop ? this[prop] : this; + var val = get(ctx, key); - set: function(name, fn) { - this.compilers[name] = fn; - return this; - }, + this.emit('get', key, val); + return val; + }; /** - * Get compiler `name`. + * Return true if app has a stored value for `key`, + * false only if value is `undefined`. + * + * ```js + * app.set('foo', 'bar'); + * app.has('foo'); + * //=> true + * ``` + * + * @name .has + * @emits `has` with `key` and true or false as arguments. + * @param {String} `key` + * @return {Boolean} + * @api public */ - get: function(name) { - return this.compilers[name]; - }, + Cache.prototype.has = function(key) { + key = toPath(arguments); - /** - * Get the previous AST node. - */ + var ctx = prop ? this[prop] : this; + var val = get(ctx, key); - prev: function(n) { - return this.ast.nodes[this.idx - (n || 1)] || { type: 'bos', val: '' }; - }, + var has = typeof val !== 'undefined'; + this.emit('has', key, has); + return has; + }; /** - * Get the next AST node. + * Delete one or more properties from the instance. + * + * ```js + * app.del(); // delete all + * // or + * app.del('foo'); + * // or + * app.del(['foo', 'bar']); + * ``` + * @name .del + * @emits `del` with the `key` as the only argument. + * @param {String|Array} `key` Property name or array of property names. + * @return {Object} Returns the instance for chaining. + * @api public */ - next: function(n) { - return this.ast.nodes[this.idx + (n || 1)] || { type: 'eos', val: '' }; - }, + Cache.prototype.del = function(key) { + if (Array.isArray(key)) { + this.visit('del', key); + } else { + del(prop ? this[prop] : this, key); + this.emit('del', key); + } + return this; + }; /** - * Visit `node`. + * Reset the entire cache to an empty object. + * + * ```js + * app.clear(); + * ``` + * @api public */ - visit: function(node, nodes, i) { - var fn = this.compilers[node.type]; - this.idx = i; - - if (typeof fn !== 'function') { - throw this.error('compiler "' + node.type + '" is not registered', node); + Cache.prototype.clear = function() { + if (prop) { + this[prop] = {}; } - return fn.call(this, node, nodes, i); - }, + }; /** - * Map visit over array of `nodes`. + * Visit `method` over the properties in the given object, or map + * visit over the object-elements in an array. + * + * @name .visit + * @param {String} `method` The name of the `base` method to call. + * @param {Object|Array} `val` The object or array to iterate over. + * @return {Object} Returns the instance for chaining. + * @api public */ - mapVisit: function(nodes) { - if (!Array.isArray(nodes)) { - throw new TypeError('expected an array'); - } - var len = nodes.length; - var idx = -1; - while (++idx < len) { - this.visit(nodes[idx], nodes, idx); - } - return this; - }, + Cache.prototype.visit = function(method, val) { + visit(this, method, val); + return this; + }; + + return Cache; +} + +/** + * Cast val to an array + */ + +function arrayify(val) { + return val ? (Array.isArray(val) ? val : [val]) : []; +} + +/** + * Expose `Cache` + */ + +module.exports = namespace(); + +/** + * Expose `Cache.namespace` + */ + +module.exports.namespace = namespace; + + +/***/ }), +/* 696 */ +/***/ (function(module, exports, __webpack_require__) { + + +/** + * Expose `Emitter`. + */ + +if (true) { + module.exports = Emitter; +} + +/** + * Initialize a new `Emitter`. + * + * @api public + */ + +function Emitter(obj) { + if (obj) return mixin(obj); +}; + +/** + * Mixin the emitter properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ + +function mixin(obj) { + for (var key in Emitter.prototype) { + obj[key] = Emitter.prototype[key]; + } + return obj; +} + +/** + * Listen on the given `event` with `fn`. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.on = +Emitter.prototype.addEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + (this._callbacks['$' + event] = this._callbacks['$' + event] || []) + .push(fn); + return this; +}; + +/** + * Adds an `event` listener that will be invoked a single + * time then automatically removed. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.once = function(event, fn){ + function on() { + this.off(event, on); + fn.apply(this, arguments); + } + + on.fn = fn; + this.on(event, on); + return this; +}; + +/** + * Remove the given callback for `event` or all + * registered callbacks. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.off = +Emitter.prototype.removeListener = +Emitter.prototype.removeAllListeners = +Emitter.prototype.removeEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + + // all + if (0 == arguments.length) { + this._callbacks = {}; + return this; + } + + // specific event + var callbacks = this._callbacks['$' + event]; + if (!callbacks) return this; + + // remove all handlers + if (1 == arguments.length) { + delete this._callbacks['$' + event]; + return this; + } + + // remove specific handler + var cb; + for (var i = 0; i < callbacks.length; i++) { + cb = callbacks[i]; + if (cb === fn || cb.fn === fn) { + callbacks.splice(i, 1); + break; + } + } + return this; +}; + +/** + * Emit `event` with the given args. + * + * @param {String} event + * @param {Mixed} ... + * @return {Emitter} + */ + +Emitter.prototype.emit = function(event){ + this._callbacks = this._callbacks || {}; + var args = [].slice.call(arguments, 1) + , callbacks = this._callbacks['$' + event]; + + if (callbacks) { + callbacks = callbacks.slice(0); + for (var i = 0, len = callbacks.length; i < len; ++i) { + callbacks[i].apply(this, args); + } + } + + return this; +}; + +/** + * Return array of callbacks for `event`. + * + * @param {String} event + * @return {Array} + * @api public + */ + +Emitter.prototype.listeners = function(event){ + this._callbacks = this._callbacks || {}; + return this._callbacks['$' + event] || []; +}; + +/** + * Check if this emitter has `event` handlers. + * + * @param {String} event + * @return {Boolean} + * @api public + */ + +Emitter.prototype.hasListeners = function(event){ + return !! this.listeners(event).length; +}; + + +/***/ }), +/* 697 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * collection-visit + * + * Copyright (c) 2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ - /** - * Compile `ast`. - */ - compile: function(ast, options) { - var opts = utils.extend({}, this.options, options); - this.ast = ast; - this.parsingErrors = this.ast.errors; - this.output = ''; - // source map support - if (opts.sourcemap) { - var sourcemaps = __webpack_require__(718); - sourcemaps(this); - this.mapVisit(this.ast.nodes); - this.applySourceMaps(); - this.map = opts.sourcemap === 'generator' ? this.map : this.map.toJSON(); - return this; - } +var visit = __webpack_require__(698); +var mapVisit = __webpack_require__(699); - this.mapVisit(this.ast.nodes); - return this; +module.exports = function(collection, method, val) { + var result; + + if (typeof val === 'string' && (method in collection)) { + var args = [].slice.call(arguments, 2); + result = collection[method].apply(collection, args); + } else if (Array.isArray(val)) { + result = mapVisit.apply(null, arguments); + } else { + result = visit.apply(null, arguments); } -}; -/** - * Expose `Compiler` - */ + if (typeof result !== 'undefined') { + return result; + } -module.exports = Compiler; + return collection; +}; /***/ }), -/* 697 */ +/* 698 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /*! - * use + * object-visit * * Copyright (c) 2015, 2017, Jon Schlinkert. * Released under the MIT License. @@ -71625,7583 +71320,8594 @@ module.exports = Compiler; -var utils = __webpack_require__(698); +var isObject = __webpack_require__(656); -module.exports = function base(app, opts) { - if (!utils.isObject(app) && typeof app !== 'function') { - throw new TypeError('use: expect `app` be an object or function'); +module.exports = function visit(thisArg, method, target, val) { + if (!isObject(thisArg) && typeof thisArg !== 'function') { + throw new Error('object-visit expects `thisArg` to be an object.'); } - if (!utils.isObject(opts)) { - opts = {}; + if (typeof method !== 'string') { + throw new Error('object-visit expects `method` name to be a string'); } - var prop = utils.isString(opts.prop) ? opts.prop : 'fns'; - if (!Array.isArray(app[prop])) { - utils.define(app, prop, []); + if (typeof thisArg[method] !== 'function') { + return thisArg; } - /** - * Define a plugin function to be passed to use. The only - * parameter exposed to the plugin is `app`, the object or function. - * passed to `use(app)`. `app` is also exposed as `this` in plugins. - * - * Additionally, **if a plugin returns a function, the function will - * be pushed onto the `fns` array**, allowing the plugin to be - * called at a later point by the `run` method. - * - * ```js - * var use = require('use'); - * - * // define a plugin - * function foo(app) { - * // do stuff - * } - * - * var app = function(){}; - * use(app); - * - * // register plugins - * app.use(foo); - * app.use(bar); - * app.use(baz); - * ``` - * @name .use - * @param {Function} `fn` plugin function to call - * @api public - */ + var args = [].slice.call(arguments, 3); + target = target || {}; - utils.define(app, 'use', use); + for (var key in target) { + var arr = [key, target[key]].concat(args); + thisArg[method].apply(thisArg, arr); + } + return thisArg; +}; - /** - * Run all plugins on `fns`. Any plugin that returns a function - * when called by `use` is pushed onto the `fns` array. - * - * ```js - * var config = {}; - * app.run(config); - * ``` - * @name .run - * @param {Object} `value` Object to be modified by plugins. - * @return {Object} Returns the object passed to `run` - * @api public - */ - utils.define(app, 'run', function(val) { - if (!utils.isObject(val)) return; - decorate(val); +/***/ }), +/* 699 */ +/***/ (function(module, exports, __webpack_require__) { - var self = this || app; - var fns = self[prop]; - var len = fns.length; - var idx = -1; +"use strict"; - while (++idx < len) { - val.use(fns[idx]); - } - return val; - }); - /** - * Call plugin `fn`. If a function is returned push it into the - * `fns` array to be called by the `run` method. - */ +var util = __webpack_require__(234); +var visit = __webpack_require__(698); - function use(fn, options) { - if (typeof fn !== 'function') { - throw new TypeError('.use expects `fn` be a function'); - } +/** + * Map `visit` over an array of objects. + * + * @param {Object} `collection` The context in which to invoke `method` + * @param {String} `method` Name of the method to call on `collection` + * @param {Object} `arr` Array of objects. + */ - var self = this || app; - if (typeof opts.fn === 'function') { - opts.fn.call(self, self, options); - } +module.exports = function mapVisit(collection, method, val) { + if (isObject(val)) { + return visit.apply(null, arguments); + } - var plugin = fn.call(self, self); - if (typeof plugin === 'function') { - var fns = self[prop]; - fns.push(plugin); - } - return self; + if (!Array.isArray(val)) { + throw new TypeError('expected an array: ' + util.inspect(val)); } - /** - * Ensure the `.use` method exists on `val` - */ + var args = [].slice.call(arguments, 3); - function decorate(val) { - if (!val.use || !val.run) { - base(val); + for (var i = 0; i < val.length; i++) { + var ele = val[i]; + if (isObject(ele)) { + visit.apply(null, [collection, method, ele].concat(args)); + } else { + collection[method].apply(collection, [ele].concat(args)); } } - - return app; }; +function isObject(val) { + return val && (typeof val === 'function' || (!Array.isArray(val) && typeof val === 'object')); +} + /***/ }), -/* 698 */ +/* 700 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; - - -var utils = {}; - - - -/** - * Lazily required module dependencies +/*! + * to-object-path + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. */ -utils.define = __webpack_require__(685); -utils.isObject = __webpack_require__(618); -utils.isString = function(val) { - return val && typeof val === 'string'; +var typeOf = __webpack_require__(701); + +module.exports = function toPath(args) { + if (typeOf(args) !== 'arguments') { + args = arguments; + } + return filter(args).join('.'); }; -/** - * Expose `utils` modules - */ +function filter(arr) { + var len = arr.length; + var idx = -1; + var res = []; -module.exports = utils; + while (++idx < len) { + var ele = arr[idx]; + if (typeOf(ele) === 'arguments' || Array.isArray(ele)) { + res.push.apply(res, filter(ele)); + } else if (typeof ele === 'string') { + res.push(ele); + } + } + return res; +} /***/ }), -/* 699 */ +/* 701 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; - +var isBuffer = __webpack_require__(680); +var toString = Object.prototype.toString; /** - * Module dependencies + * Get the native `typeof` a value. + * + * @param {*} `val` + * @return {*} Native javascript type */ -exports.extend = __webpack_require__(669); -exports.SourceMap = __webpack_require__(700); -exports.sourceMapResolve = __webpack_require__(711); +module.exports = function kindOf(val) { + // primitivies + if (typeof val === 'undefined') { + return 'undefined'; + } + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (typeof val === 'string' || val instanceof String) { + return 'string'; + } + if (typeof val === 'number' || val instanceof Number) { + return 'number'; + } + + // functions + if (typeof val === 'function' || val instanceof Function) { + return 'function'; + } -/** - * Convert backslash in the given string to forward slashes - */ + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; + } -exports.unixify = function(fp) { - return fp.split(/\\+/).join('/'); -}; + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; + } -/** - * Return true if `val` is a non-empty string - * - * @param {String} `str` - * @return {Boolean} - */ + // other objects + var type = toString.call(val); -exports.isString = function(str) { - return str && typeof str === 'string'; -}; + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; + } -/** - * Cast `val` to an array - * @return {Array} - */ + // buffer + if (isBuffer(val)) { + return 'buffer'; + } -exports.arrayify = function(val) { - if (typeof val === 'string') return [val]; - return val ? (Array.isArray(val) ? val : [val]) : []; -}; + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; + } -/** - * Get the last `n` element from the given `array` - * @param {Array} `array` - * @return {*} - */ + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } -exports.last = function(arr, n) { - return arr[arr.length - (n || 1)]; + // must be a plain object + return 'object'; }; /***/ }), -/* 700 */ +/* 702 */ /***/ (function(module, exports, __webpack_require__) { -/* - * Copyright 2009-2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE.txt or: - * http://opensource.org/licenses/BSD-3-Clause - */ -exports.SourceMapGenerator = __webpack_require__(701).SourceMapGenerator; -exports.SourceMapConsumer = __webpack_require__(707).SourceMapConsumer; -exports.SourceNode = __webpack_require__(710).SourceNode; +"use strict"; -/***/ }), -/* 701 */ -/***/ (function(module, exports, __webpack_require__) { +var isObject = __webpack_require__(703); +var union = __webpack_require__(704); +var get = __webpack_require__(705); +var set = __webpack_require__(706); -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ +module.exports = function unionValue(obj, prop, value) { + if (!isObject(obj)) { + throw new TypeError('union-value expects the first argument to be an object.'); + } -var base64VLQ = __webpack_require__(702); -var util = __webpack_require__(704); -var ArraySet = __webpack_require__(705).ArraySet; -var MappingList = __webpack_require__(706).MappingList; + if (typeof prop !== 'string') { + throw new TypeError('union-value expects `prop` to be a string.'); + } -/** - * An instance of the SourceMapGenerator represents a source map which is - * being built incrementally. You may pass an object with the following - * properties: - * - * - file: The filename of the generated source. - * - sourceRoot: A root for all relative URLs in this source map. - */ -function SourceMapGenerator(aArgs) { - if (!aArgs) { - aArgs = {}; + var arr = arrayify(get(obj, prop)); + set(obj, prop, union(arr, arrayify(value))); + return obj; +}; + +function arrayify(val) { + if (val === null || typeof val === 'undefined') { + return []; } - this._file = util.getArg(aArgs, 'file', null); - this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); - this._skipValidation = util.getArg(aArgs, 'skipValidation', false); - this._sources = new ArraySet(); - this._names = new ArraySet(); - this._mappings = new MappingList(); - this._sourcesContents = null; + if (Array.isArray(val)) { + return val; + } + return [val]; } -SourceMapGenerator.prototype._version = 3; -/** - * Creates a new SourceMapGenerator based on a SourceMapConsumer +/***/ }), +/* 703 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * is-extendable * - * @param aSourceMapConsumer The SourceMap. + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. */ -SourceMapGenerator.fromSourceMap = - function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { - var sourceRoot = aSourceMapConsumer.sourceRoot; - var generator = new SourceMapGenerator({ - file: aSourceMapConsumer.file, - sourceRoot: sourceRoot - }); - aSourceMapConsumer.eachMapping(function (mapping) { - var newMapping = { - generated: { - line: mapping.generatedLine, - column: mapping.generatedColumn - } - }; - if (mapping.source != null) { - newMapping.source = mapping.source; - if (sourceRoot != null) { - newMapping.source = util.relative(sourceRoot, newMapping.source); - } - newMapping.original = { - line: mapping.originalLine, - column: mapping.originalColumn - }; - if (mapping.name != null) { - newMapping.name = mapping.name; - } - } +module.exports = function isExtendable(val) { + return typeof val !== 'undefined' && val !== null + && (typeof val === 'object' || typeof val === 'function'); +}; - generator.addMapping(newMapping); - }); - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - generator.setSourceContent(sourceFile, content); - } - }); - return generator; - }; -/** - * Add a single mapping from original source line and column to the generated - * source's line and column for this source map being created. The mapping - * object should have the following properties: - * - * - generated: An object with the generated line and column positions. - * - original: An object with the original line and column positions. - * - source: The original source file (relative to the sourceRoot). - * - name: An optional original token name for this mapping. - */ -SourceMapGenerator.prototype.addMapping = - function SourceMapGenerator_addMapping(aArgs) { - var generated = util.getArg(aArgs, 'generated'); - var original = util.getArg(aArgs, 'original', null); - var source = util.getArg(aArgs, 'source', null); - var name = util.getArg(aArgs, 'name', null); +/***/ }), +/* 704 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = function union(init) { + if (!Array.isArray(init)) { + throw new TypeError('arr-union expects the first argument to be an array.'); + } + + var len = arguments.length; + var i = 0; + + while (++i < len) { + var arg = arguments[i]; + if (!arg) continue; - if (!this._skipValidation) { - this._validateMapping(generated, original, source, name); + if (!Array.isArray(arg)) { + arg = [arg]; } - if (source != null) { - source = String(source); - if (!this._sources.has(source)) { - this._sources.add(source); - } - } + for (var j = 0; j < arg.length; j++) { + var ele = arg[j]; - if (name != null) { - name = String(name); - if (!this._names.has(name)) { - this._names.add(name); + if (init.indexOf(ele) >= 0) { + continue; } + init.push(ele); } + } + return init; +}; - this._mappings.add({ - generatedLine: generated.line, - generatedColumn: generated.column, - originalLine: original != null && original.line, - originalColumn: original != null && original.column, - source: source, - name: name - }); - }; - -/** - * Set the source content for a source file. - */ -SourceMapGenerator.prototype.setSourceContent = - function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { - var source = aSourceFile; - if (this._sourceRoot != null) { - source = util.relative(this._sourceRoot, source); - } - if (aSourceContent != null) { - // Add the source content to the _sourcesContents map. - // Create a new _sourcesContents map if the property is null. - if (!this._sourcesContents) { - this._sourcesContents = Object.create(null); - } - this._sourcesContents[util.toSetString(source)] = aSourceContent; - } else if (this._sourcesContents) { - // Remove the source file from the _sourcesContents map. - // If the _sourcesContents map is empty, set the property to null. - delete this._sourcesContents[util.toSetString(source)]; - if (Object.keys(this._sourcesContents).length === 0) { - this._sourcesContents = null; - } - } - }; +/***/ }), +/* 705 */ +/***/ (function(module, exports) { -/** - * Applies the mappings of a sub-source-map for a specific source file to the - * source map being generated. Each mapping to the supplied source file is - * rewritten using the supplied source map. Note: The resolution for the - * resulting mappings is the minimium of this map and the supplied map. +/*! + * get-value * - * @param aSourceMapConsumer The source map to be applied. - * @param aSourceFile Optional. The filename of the source file. - * If omitted, SourceMapConsumer's file property will be used. - * @param aSourceMapPath Optional. The dirname of the path to the source map - * to be applied. If relative, it is relative to the SourceMapConsumer. - * This parameter is needed when the two source maps aren't in the same - * directory, and the source map to be applied contains relative source - * paths. If so, those relative source paths need to be rewritten - * relative to the SourceMapGenerator. + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. */ -SourceMapGenerator.prototype.applySourceMap = - function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { - var sourceFile = aSourceFile; - // If aSourceFile is omitted, we will use the file property of the SourceMap - if (aSourceFile == null) { - if (aSourceMapConsumer.file == null) { - throw new Error( - 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + - 'or the source map\'s "file" property. Both were omitted.' - ); - } - sourceFile = aSourceMapConsumer.file; - } - var sourceRoot = this._sourceRoot; - // Make "sourceFile" relative if an absolute Url is passed. - if (sourceRoot != null) { - sourceFile = util.relative(sourceRoot, sourceFile); - } - // Applying the SourceMap can add and remove items from the sources and - // the names array. - var newSources = new ArraySet(); - var newNames = new ArraySet(); - // Find mappings for the "sourceFile" - this._mappings.unsortedForEach(function (mapping) { - if (mapping.source === sourceFile && mapping.originalLine != null) { - // Check if it can be mapped by the source map, then update the mapping. - var original = aSourceMapConsumer.originalPositionFor({ - line: mapping.originalLine, - column: mapping.originalColumn - }); - if (original.source != null) { - // Copy mapping - mapping.source = original.source; - if (aSourceMapPath != null) { - mapping.source = util.join(aSourceMapPath, mapping.source) - } - if (sourceRoot != null) { - mapping.source = util.relative(sourceRoot, mapping.source); - } - mapping.originalLine = original.line; - mapping.originalColumn = original.column; - if (original.name != null) { - mapping.name = original.name; - } - } - } +module.exports = function(obj, prop, a, b, c) { + if (!isObject(obj) || !prop) { + return obj; + } - var source = mapping.source; - if (source != null && !newSources.has(source)) { - newSources.add(source); - } + prop = toString(prop); - var name = mapping.name; - if (name != null && !newNames.has(name)) { - newNames.add(name); - } + // allowing for multiple properties to be passed as + // a string or array, but much faster (3-4x) than doing + // `[].slice.call(arguments)` + if (a) prop += '.' + toString(a); + if (b) prop += '.' + toString(b); + if (c) prop += '.' + toString(c); - }, this); - this._sources = newSources; - this._names = newNames; + if (prop in obj) { + return obj[prop]; + } - // Copy sourcesContents of applied map. - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - if (aSourceMapPath != null) { - sourceFile = util.join(aSourceMapPath, sourceFile); - } - if (sourceRoot != null) { - sourceFile = util.relative(sourceRoot, sourceFile); - } - this.setSourceContent(sourceFile, content); - } - }, this); - }; + var segs = prop.split('.'); + var len = segs.length; + var i = -1; -/** - * A mapping can have one of the three levels of data: - * - * 1. Just the generated position. - * 2. The Generated position, original position, and original source. - * 3. Generated and original position, original source, as well as a name - * token. - * - * To maintain consistency, we validate that any new mapping being added falls - * in to one of these categories. - */ -SourceMapGenerator.prototype._validateMapping = - function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, - aName) { - // When aOriginal is truthy but has empty values for .line and .column, - // it is most likely a programmer error. In this case we throw a very - // specific error message to try to guide them the right way. - // For example: https://github.com/Polymer/polymer-bundler/pull/519 - if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { - throw new Error( - 'original.line and original.column are not numbers -- you probably meant to omit ' + - 'the original mapping entirely and only map the generated position. If so, pass ' + - 'null for the original mapping instead of an object with empty or null values.' - ); + while (obj && (++i < len)) { + var key = segs[i]; + while (key[key.length - 1] === '\\') { + key = key.slice(0, -1) + '.' + segs[++i]; } + obj = obj[key]; + } + return obj; +}; - if (aGenerated && 'line' in aGenerated && 'column' in aGenerated - && aGenerated.line > 0 && aGenerated.column >= 0 - && !aOriginal && !aSource && !aName) { - // Case 1. - return; - } - else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated - && aOriginal && 'line' in aOriginal && 'column' in aOriginal - && aGenerated.line > 0 && aGenerated.column >= 0 - && aOriginal.line > 0 && aOriginal.column >= 0 - && aSource) { - // Cases 2 and 3. - return; - } - else { - throw new Error('Invalid mapping: ' + JSON.stringify({ - generated: aGenerated, - source: aSource, - original: aOriginal, - name: aName - })); - } - }; +function isObject(val) { + return val !== null && (typeof val === 'object' || typeof val === 'function'); +} -/** - * Serialize the accumulated mappings in to the stream of base 64 VLQs - * specified by the source map format. +function toString(val) { + if (!val) return ''; + if (Array.isArray(val)) { + return val.join('.'); + } + return val; +} + + +/***/ }), +/* 706 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * set-value + * + * Copyright (c) 2014-2015, 2017, Jon Schlinkert. + * Released under the MIT License. */ -SourceMapGenerator.prototype._serializeMappings = - function SourceMapGenerator_serializeMappings() { - var previousGeneratedColumn = 0; - var previousGeneratedLine = 1; - var previousOriginalColumn = 0; - var previousOriginalLine = 0; - var previousName = 0; - var previousSource = 0; - var result = ''; - var next; - var mapping; - var nameIdx; - var sourceIdx; - var mappings = this._mappings.toArray(); - for (var i = 0, len = mappings.length; i < len; i++) { - mapping = mappings[i]; - next = '' - if (mapping.generatedLine !== previousGeneratedLine) { - previousGeneratedColumn = 0; - while (mapping.generatedLine !== previousGeneratedLine) { - next += ';'; - previousGeneratedLine++; - } - } - else { - if (i > 0) { - if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { - continue; - } - next += ','; - } - } - next += base64VLQ.encode(mapping.generatedColumn - - previousGeneratedColumn); - previousGeneratedColumn = mapping.generatedColumn; +var split = __webpack_require__(673); +var extend = __webpack_require__(707); +var isPlainObject = __webpack_require__(663); +var isObject = __webpack_require__(703); - if (mapping.source != null) { - sourceIdx = this._sources.indexOf(mapping.source); - next += base64VLQ.encode(sourceIdx - previousSource); - previousSource = sourceIdx; +module.exports = function(obj, prop, val) { + if (!isObject(obj)) { + return obj; + } - // lines are stored 0-based in SourceMap spec version 3 - next += base64VLQ.encode(mapping.originalLine - 1 - - previousOriginalLine); - previousOriginalLine = mapping.originalLine - 1; + if (Array.isArray(prop)) { + prop = [].concat.apply([], prop).join('.'); + } - next += base64VLQ.encode(mapping.originalColumn - - previousOriginalColumn); - previousOriginalColumn = mapping.originalColumn; + if (typeof prop !== 'string') { + return obj; + } - if (mapping.name != null) { - nameIdx = this._names.indexOf(mapping.name); - next += base64VLQ.encode(nameIdx - previousName); - previousName = nameIdx; - } + var keys = split(prop, {sep: '.', brackets: true}).filter(isValidKey); + var len = keys.length; + var idx = -1; + var current = obj; + + while (++idx < len) { + var key = keys[idx]; + if (idx !== len - 1) { + if (!isObject(current[key])) { + current[key] = {}; } + current = current[key]; + continue; + } - result += next; + if (isPlainObject(current[key]) && isPlainObject(val)) { + current[key] = extend({}, current[key], val); + } else { + current[key] = val; } + } - return result; - }; + return obj; +}; -SourceMapGenerator.prototype._generateSourcesContent = - function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { - return aSources.map(function (source) { - if (!this._sourcesContents) { - return null; - } - if (aSourceRoot != null) { - source = util.relative(aSourceRoot, source); - } - var key = util.toSetString(source); - return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) - ? this._sourcesContents[key] - : null; - }, this); - }; +function isValidKey(key) { + return key !== '__proto__' && key !== 'constructor' && key !== 'prototype'; +} -/** - * Externalize the source map. - */ -SourceMapGenerator.prototype.toJSON = - function SourceMapGenerator_toJSON() { - var map = { - version: this._version, - sources: this._sources.toArray(), - names: this._names.toArray(), - mappings: this._serializeMappings() - }; - if (this._file != null) { - map.file = this._file; - } - if (this._sourceRoot != null) { - map.sourceRoot = this._sourceRoot; - } - if (this._sourcesContents) { - map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + +/***/ }), +/* 707 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var isObject = __webpack_require__(703); + +module.exports = function extend(o/*, objects*/) { + if (!isObject(o)) { o = {}; } + + var len = arguments.length; + for (var i = 1; i < len; i++) { + var obj = arguments[i]; + + if (isObject(obj)) { + assign(o, obj); } + } + return o; +}; - return map; - }; +function assign(a, b) { + for (var key in b) { + if (hasOwn(b, key)) { + a[key] = b[key]; + } + } +} /** - * Render the source map being generated to a string. + * Returns true if the given `key` is an own property of `obj`. */ -SourceMapGenerator.prototype.toString = - function SourceMapGenerator_toString() { - return JSON.stringify(this.toJSON()); - }; -exports.SourceMapGenerator = SourceMapGenerator; +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} /***/ }), -/* 702 */ +/* 708 */ /***/ (function(module, exports, __webpack_require__) { -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - * - * Based on the Base 64 VLQ implementation in Closure Compiler: - * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java - * - * Copyright 2011 The Closure Compiler Authors. All rights reserved. - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. +"use strict"; +/*! + * unset-value * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * Copyright (c) 2015, 2017, Jon Schlinkert. + * Released under the MIT License. */ -var base64 = __webpack_require__(703); - -// A single base 64 digit can contain 6 bits of data. For the base 64 variable -// length quantities we use in the source map spec, the first bit is the sign, -// the next four bits are the actual value, and the 6th bit is the -// continuation bit. The continuation bit tells us whether there are more -// digits in this value following this digit. -// -// Continuation -// | Sign -// | | -// V V -// 101011 - -var VLQ_BASE_SHIFT = 5; -// binary: 100000 -var VLQ_BASE = 1 << VLQ_BASE_SHIFT; -// binary: 011111 -var VLQ_BASE_MASK = VLQ_BASE - 1; +var isObject = __webpack_require__(656); +var has = __webpack_require__(709); -// binary: 100000 -var VLQ_CONTINUATION_BIT = VLQ_BASE; +module.exports = function unset(obj, prop) { + if (!isObject(obj)) { + throw new TypeError('expected an object.'); + } + if (obj.hasOwnProperty(prop)) { + delete obj[prop]; + return true; + } -/** - * Converts from a two-complement value to a value where the sign bit is - * placed in the least significant bit. For example, as decimals: - * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) - * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) - */ -function toVLQSigned(aValue) { - return aValue < 0 - ? ((-aValue) << 1) + 1 - : (aValue << 1) + 0; -} + if (has(obj, prop)) { + var segs = prop.split('.'); + var last = segs.pop(); + while (segs.length && segs[segs.length - 1].slice(-1) === '\\') { + last = segs.pop().slice(0, -1) + '.' + last; + } + while (segs.length) obj = obj[prop = segs.shift()]; + return (delete obj[last]); + } + return true; +}; -/** - * Converts to a two-complement value from a value where the sign bit is - * placed in the least significant bit. For example, as decimals: - * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 - * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 - */ -function fromVLQSigned(aValue) { - var isNegative = (aValue & 1) === 1; - var shifted = aValue >> 1; - return isNegative - ? -shifted - : shifted; -} -/** - * Returns the base 64 VLQ encoded value. +/***/ }), +/* 709 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * has-value + * + * Copyright (c) 2014-2016, Jon Schlinkert. + * Licensed under the MIT License. */ -exports.encode = function base64VLQ_encode(aValue) { - var encoded = ""; - var digit; - var vlq = toVLQSigned(aValue); - do { - digit = vlq & VLQ_BASE_MASK; - vlq >>>= VLQ_BASE_SHIFT; - if (vlq > 0) { - // There are still more digits in this value, so we must make sure the - // continuation bit is marked. - digit |= VLQ_CONTINUATION_BIT; - } - encoded += base64.encode(digit); - } while (vlq > 0); - return encoded; +var isObject = __webpack_require__(710); +var hasValues = __webpack_require__(712); +var get = __webpack_require__(705); + +module.exports = function(obj, prop, noZero) { + if (isObject(obj)) { + return hasValues(get(obj, prop), noZero); + } + return hasValues(obj, prop); }; -/** - * Decodes the next base 64 VLQ value from the given string and returns the - * value and the rest of the string via the out parameter. + +/***/ }), +/* 710 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * isobject + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. */ -exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { - var strLen = aStr.length; - var result = 0; - var shift = 0; - var continuation, digit; - do { - if (aIndex >= strLen) { - throw new Error("Expected more digits in base 64 VLQ value."); - } - digit = base64.decode(aStr.charCodeAt(aIndex++)); - if (digit === -1) { - throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); - } - continuation = !!(digit & VLQ_CONTINUATION_BIT); - digit &= VLQ_BASE_MASK; - result = result + (digit << shift); - shift += VLQ_BASE_SHIFT; - } while (continuation); +var isArray = __webpack_require__(711); - aOutParam.value = fromVLQSigned(result); - aOutParam.rest = aIndex; +module.exports = function isObject(val) { + return val != null && typeof val === 'object' && isArray(val) === false; }; /***/ }), -/* 703 */ +/* 711 */ /***/ (function(module, exports) { -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); +var toString = {}.toString; -/** - * Encode an integer in the range of 0 to 63 to a single base 64 digit. - */ -exports.encode = function (number) { - if (0 <= number && number < intToCharMap.length) { - return intToCharMap[number]; - } - throw new TypeError("Must be between 0 and 63: " + number); +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; }; -/** - * Decode a single base 64 character code digit to an integer. Returns -1 on - * failure. - */ -exports.decode = function (charCode) { - var bigA = 65; // 'A' - var bigZ = 90; // 'Z' - var littleA = 97; // 'a' - var littleZ = 122; // 'z' +/***/ }), +/* 712 */ +/***/ (function(module, exports, __webpack_require__) { - var zero = 48; // '0' - var nine = 57; // '9' +"use strict"; +/*! + * has-values + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. + */ - var plus = 43; // '+' - var slash = 47; // '/' - var littleOffset = 26; - var numberOffset = 52; - // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ - if (bigA <= charCode && charCode <= bigZ) { - return (charCode - bigA); +module.exports = function hasValue(o, noZero) { + if (o === null || o === undefined) { + return false; } - // 26 - 51: abcdefghijklmnopqrstuvwxyz - if (littleA <= charCode && charCode <= littleZ) { - return (charCode - littleA + littleOffset); + if (typeof o === 'boolean') { + return true; } - // 52 - 61: 0123456789 - if (zero <= charCode && charCode <= nine) { - return (charCode - zero + numberOffset); + if (typeof o === 'number') { + if (o === 0 && noZero === true) { + return false; + } + return true; } - // 62: + - if (charCode == plus) { - return 62; + if (o.length !== undefined) { + return o.length !== 0; } - // 63: / - if (charCode == slash) { - return 63; + for (var key in o) { + if (o.hasOwnProperty(key)) { + return true; + } } - - // Invalid base64 digit. - return -1; + return false; }; /***/ }), -/* 704 */ -/***/ (function(module, exports) { - -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ +/* 713 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * This is a helper function for getting values from parameter/options - * objects. +"use strict"; +/*! + * has-value * - * @param args The object we are extracting values from - * @param name The name of the property we are getting. - * @param defaultValue An optional value to return if the property is missing - * from the object. If this is not specified and the property is missing, an - * error will be thrown. + * Copyright (c) 2014-2017, Jon Schlinkert. + * Licensed under the MIT License. */ -function getArg(aArgs, aName, aDefaultValue) { - if (aName in aArgs) { - return aArgs[aName]; - } else if (arguments.length === 3) { - return aDefaultValue; - } else { - throw new Error('"' + aName + '" is a required argument.'); - } -} -exports.getArg = getArg; -var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/; -var dataUrlRegexp = /^data:.+\,.+$/; -function urlParse(aUrl) { - var match = aUrl.match(urlRegexp); - if (!match) { - return null; - } - return { - scheme: match[1], - auth: match[2], - host: match[3], - port: match[4], - path: match[5] - }; -} -exports.urlParse = urlParse; -function urlGenerate(aParsedUrl) { - var url = ''; - if (aParsedUrl.scheme) { - url += aParsedUrl.scheme + ':'; - } - url += '//'; - if (aParsedUrl.auth) { - url += aParsedUrl.auth + '@'; - } - if (aParsedUrl.host) { - url += aParsedUrl.host; - } - if (aParsedUrl.port) { - url += ":" + aParsedUrl.port - } - if (aParsedUrl.path) { - url += aParsedUrl.path; - } - return url; -} -exports.urlGenerate = urlGenerate; +var isObject = __webpack_require__(656); +var hasValues = __webpack_require__(714); +var get = __webpack_require__(705); -/** - * Normalizes a path, or the path portion of a URL: - * - * - Replaces consecutive slashes with one slash. - * - Removes unnecessary '.' parts. - * - Removes unnecessary '/..' parts. - * - * Based on code in the Node.js 'path' core module. +module.exports = function(val, prop) { + return hasValues(isObject(val) && prop ? get(val, prop) : val); +}; + + +/***/ }), +/* 714 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * has-values * - * @param aPath The path or url to normalize. + * Copyright (c) 2014-2015, 2017, Jon Schlinkert. + * Released under the MIT License. */ -function normalize(aPath) { - var path = aPath; - var url = urlParse(aPath); - if (url) { - if (!url.path) { - return aPath; - } - path = url.path; + + + +var typeOf = __webpack_require__(715); +var isNumber = __webpack_require__(678); + +module.exports = function hasValue(val) { + // is-number checks for NaN and other edge cases + if (isNumber(val)) { + return true; } - var isAbsolute = exports.isAbsolute(path); - var parts = path.split(/\/+/); - for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { - part = parts[i]; - if (part === '.') { - parts.splice(i, 1); - } else if (part === '..') { - up++; - } else if (up > 0) { - if (part === '') { - // The first part is blank if the path is absolute. Trying to go - // above the root is a no-op. Therefore we can remove all '..' parts - // directly after the root. - parts.splice(i + 1, up); - up = 0; - } else { - parts.splice(i, 2); - up--; + switch (typeOf(val)) { + case 'null': + case 'boolean': + case 'function': + return true; + case 'string': + case 'arguments': + return val.length !== 0; + case 'error': + return val.message !== ''; + case 'array': + var len = val.length; + if (len === 0) { + return false; + } + for (var i = 0; i < len; i++) { + if (hasValue(val[i])) { + return true; + } + } + return false; + case 'file': + case 'map': + case 'set': + return val.size !== 0; + case 'object': + var keys = Object.keys(val); + if (keys.length === 0) { + return false; + } + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + if (hasValue(val[key])) { + return true; + } } + return false; + default: { + return false; } } - path = parts.join('/'); +}; - if (path === '') { - path = isAbsolute ? '/' : '.'; - } - if (url) { - url.path = path; - return urlGenerate(url); - } - return path; -} -exports.normalize = normalize; +/***/ }), +/* 715 */ +/***/ (function(module, exports, __webpack_require__) { + +var isBuffer = __webpack_require__(680); +var toString = Object.prototype.toString; /** - * Joins two paths/URLs. - * - * @param aRoot The root path or URL. - * @param aPath The path or URL to be joined with the root. + * Get the native `typeof` a value. * - * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a - * scheme-relative URL: Then the scheme of aRoot, if any, is prepended - * first. - * - Otherwise aPath is a path. If aRoot is a URL, then its path portion - * is updated with the result and aRoot is returned. Otherwise the result - * is returned. - * - If aPath is absolute, the result is aPath. - * - Otherwise the two paths are joined with a slash. - * - Joining for example 'http://' and 'www.example.com' is also supported. + * @param {*} `val` + * @return {*} Native javascript type */ -function join(aRoot, aPath) { - if (aRoot === "") { - aRoot = "."; + +module.exports = function kindOf(val) { + // primitivies + if (typeof val === 'undefined') { + return 'undefined'; } - if (aPath === "") { - aPath = "."; + if (val === null) { + return 'null'; } - var aPathUrl = urlParse(aPath); - var aRootUrl = urlParse(aRoot); - if (aRootUrl) { - aRoot = aRootUrl.path || '/'; + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (typeof val === 'string' || val instanceof String) { + return 'string'; + } + if (typeof val === 'number' || val instanceof Number) { + return 'number'; } - // `join(foo, '//www.example.org')` - if (aPathUrl && !aPathUrl.scheme) { - if (aRootUrl) { - aPathUrl.scheme = aRootUrl.scheme; - } - return urlGenerate(aPathUrl); + // functions + if (typeof val === 'function' || val instanceof Function) { + return 'function'; } - if (aPathUrl || aPath.match(dataUrlRegexp)) { - return aPath; + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; } - // `join('http://', 'www.example.com')` - if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { - aRootUrl.host = aPath; - return urlGenerate(aRootUrl); + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; } - var joined = aPath.charAt(0) === '/' - ? aPath - : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + // other objects + var type = toString.call(val); - if (aRootUrl) { - aRootUrl.path = joined; - return urlGenerate(aRootUrl); + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; + } + if (type === '[object Promise]') { + return 'promise'; } - return joined; -} -exports.join = join; -exports.isAbsolute = function (aPath) { - return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp); -}; + // buffer + if (isBuffer(val)) { + return 'buffer'; + } -/** - * Make a path relative to a URL or another path. - * - * @param aRoot The root path or URL. - * @param aPath The path or URL to be made relative to aRoot. - */ -function relative(aRoot, aPath) { - if (aRoot === "") { - aRoot = "."; + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; } - aRoot = aRoot.replace(/\/$/, ''); + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } - // It is possible for the path to be above the root. In this case, simply - // checking whether the root is a prefix of the path won't work. Instead, we - // need to remove components from the root one by one, until either we find - // a prefix that fits, or we run out of components to remove. - var level = 0; - while (aPath.indexOf(aRoot + '/') !== 0) { - var index = aRoot.lastIndexOf("/"); - if (index < 0) { - return aPath; - } + // must be a plain object + return 'object'; +}; - // If the only part of the root that is left is the scheme (i.e. http://, - // file:///, etc.), one or more slashes (/), or simply nothing at all, we - // have exhausted all components, so the path is not relative to the root. - aRoot = aRoot.slice(0, index); - if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { - return aPath; - } - ++level; - } +/***/ }), +/* 716 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * set-value + * + * Copyright (c) 2014-2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ + - // Make sure we add a "../" for each component we removed from the root. - return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); -} -exports.relative = relative; -var supportsNullProto = (function () { - var obj = Object.create(null); - return !('__proto__' in obj); -}()); +var split = __webpack_require__(673); +var extend = __webpack_require__(707); +var isPlainObject = __webpack_require__(663); +var isObject = __webpack_require__(703); -function identity (s) { - return s; -} +module.exports = function(obj, prop, val) { + if (!isObject(obj)) { + return obj; + } -/** - * Because behavior goes wacky when you set `__proto__` on objects, we - * have to prefix all the strings in our set with an arbitrary character. - * - * See https://github.com/mozilla/source-map/pull/31 and - * https://github.com/mozilla/source-map/issues/30 - * - * @param String aStr - */ -function toSetString(aStr) { - if (isProtoString(aStr)) { - return '$' + aStr; + if (Array.isArray(prop)) { + prop = [].concat.apply([], prop).join('.'); } - return aStr; -} -exports.toSetString = supportsNullProto ? identity : toSetString; + if (typeof prop !== 'string') { + return obj; + } -function fromSetString(aStr) { - if (isProtoString(aStr)) { - return aStr.slice(1); + var keys = split(prop, {sep: '.', brackets: true}).filter(isValidKey); + var len = keys.length; + var idx = -1; + var current = obj; + + while (++idx < len) { + var key = keys[idx]; + if (idx !== len - 1) { + if (!isObject(current[key])) { + current[key] = {}; + } + current = current[key]; + continue; + } + + if (isPlainObject(current[key]) && isPlainObject(val)) { + current[key] = extend({}, current[key], val); + } else { + current[key] = val; + } } - return aStr; + return obj; +}; + +function isValidKey(key) { + return key !== '__proto__' && key !== 'constructor' && key !== 'prototype'; } -exports.fromSetString = supportsNullProto ? identity : fromSetString; -function isProtoString(s) { - if (!s) { - return false; - } - var length = s.length; +/***/ }), +/* 717 */ +/***/ (function(module, exports, __webpack_require__) { - if (length < 9 /* "__proto__".length */) { - return false; - } +"use strict"; - if (s.charCodeAt(length - 1) !== 95 /* '_' */ || - s.charCodeAt(length - 2) !== 95 /* '_' */ || - s.charCodeAt(length - 3) !== 111 /* 'o' */ || - s.charCodeAt(length - 4) !== 116 /* 't' */ || - s.charCodeAt(length - 5) !== 111 /* 'o' */ || - s.charCodeAt(length - 6) !== 114 /* 'r' */ || - s.charCodeAt(length - 7) !== 112 /* 'p' */ || - s.charCodeAt(length - 8) !== 95 /* '_' */ || - s.charCodeAt(length - 9) !== 95 /* '_' */) { - return false; - } - for (var i = length - 10; i >= 0; i--) { - if (s.charCodeAt(i) !== 36 /* '$' */) { - return false; +var isExtendable = __webpack_require__(718); +var forIn = __webpack_require__(719); + +function mixinDeep(target, objects) { + var len = arguments.length, i = 0; + while (++i < len) { + var obj = arguments[i]; + if (isObject(obj)) { + forIn(obj, copy, target); } } - - return true; + return target; } /** - * Comparator between two mappings where the original positions are compared. + * Copy properties from the source object to the + * target object. * - * Optionally pass in `true` as `onlyCompareGenerated` to consider two - * mappings with the same original source/line/column, but different generated - * line and column the same. Useful when searching for a mapping with a - * stubbed out mapping. + * @param {*} `val` + * @param {String} `key` */ -function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { - var cmp = mappingA.source - mappingB.source; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0 || onlyCompareOriginal) { - return cmp; +function copy(val, key) { + if (!isValidKey(key)) { + return; } - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0) { - return cmp; + var obj = this[key]; + if (isObject(val) && isObject(obj)) { + mixinDeep(obj, val); + } else { + this[key] = val; } +} - cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } +/** + * Returns true if `val` is an object or function. + * + * @param {any} val + * @return {Boolean} + */ - return mappingA.name - mappingB.name; +function isObject(val) { + return isExtendable(val) && !Array.isArray(val); } -exports.compareByOriginalPositions = compareByOriginalPositions; /** - * Comparator between two mappings with deflated source and name indices where - * the generated positions are compared. + * Returns true if `key` is a valid key to use when extending objects. * - * Optionally pass in `true` as `onlyCompareGenerated` to consider two - * mappings with the same generated line and column, but different - * source/name/original line and column the same. Useful when searching for a - * mapping with a stubbed out mapping. + * @param {String} `key` + * @return {Boolean} */ -function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { - var cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0 || onlyCompareGenerated) { - return cmp; - } +function isValidKey(key) { + return key !== '__proto__' && key !== 'constructor' && key !== 'prototype'; +}; - cmp = mappingA.source - mappingB.source; - if (cmp !== 0) { - return cmp; - } +/** + * Expose `mixinDeep` + */ - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } +module.exports = mixinDeep; - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0) { - return cmp; - } - return mappingA.name - mappingB.name; -} -exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; +/***/ }), +/* 718 */ +/***/ (function(module, exports, __webpack_require__) { -function strcmp(aStr1, aStr2) { - if (aStr1 === aStr2) { - return 0; - } +"use strict"; +/*! + * is-extendable + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ - if (aStr1 > aStr2) { - return 1; - } - return -1; -} -/** - * Comparator between two mappings with inflated source and name strings where - * the generated positions are compared. +var isPlainObject = __webpack_require__(663); + +module.exports = function isExtendable(val) { + return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); +}; + + +/***/ }), +/* 719 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * for-in + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. */ -function compareByGeneratedPositionsInflated(mappingA, mappingB) { - var cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0) { - return cmp; - } - cmp = strcmp(mappingA.source, mappingB.source); - if (cmp !== 0) { - return cmp; - } - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; +module.exports = function forIn(obj, fn, thisArg) { + for (var key in obj) { + if (fn.call(thisArg, obj[key], key, obj) === false) { + break; + } } +}; - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0) { - return cmp; - } - return strcmp(mappingA.name, mappingB.name); +/***/ }), +/* 720 */ +/***/ (function(module, exports) { + +/*! + * pascalcase + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + +function pascalcase(str) { + if (typeof str !== 'string') { + throw new TypeError('expected a string.'); + } + str = str.replace(/([A-Z])/g, ' $1'); + if (str.length === 1) { return str.toUpperCase(); } + str = str.replace(/^[\W_]+|[\W_]+$/g, '').toLowerCase(); + str = str.charAt(0).toUpperCase() + str.slice(1); + return str.replace(/[\W_]+(\w|$)/g, function (_, ch) { + return ch.toUpperCase(); + }); } -exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + +module.exports = pascalcase; /***/ }), -/* 705 */ +/* 721 */ /***/ (function(module, exports, __webpack_require__) { -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ +"use strict"; -var util = __webpack_require__(704); -var has = Object.prototype.hasOwnProperty; -var hasNativeMap = typeof Map !== "undefined"; -/** - * A data structure which is a combination of an array and a set. Adding a new - * member is O(1), testing for membership is O(1), and finding the index of an - * element is O(1). Removing elements from the set is not supported. Only - * strings are supported for membership. - */ -function ArraySet() { - this._array = []; - this._set = hasNativeMap ? new Map() : Object.create(null); -} +var util = __webpack_require__(234); +var utils = __webpack_require__(722); /** - * Static method for creating ArraySet instances from an existing array. + * Expose class utils */ -ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { - var set = new ArraySet(); - for (var i = 0, len = aArray.length; i < len; i++) { - set.add(aArray[i], aAllowDuplicates); - } - return set; -}; + +var cu = module.exports; /** - * Return how many unique items are in this ArraySet. If duplicates have been - * added, than those do not count towards the size. - * - * @returns Number + * Expose class utils: `cu` */ -ArraySet.prototype.size = function ArraySet_size() { - return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; + +cu.isObject = function isObject(val) { + return utils.isObj(val) || typeof val === 'function'; }; /** - * Add the given string to this set. + * Returns true if an array has any of the given elements, or an + * object has any of the give keys. * - * @param String aStr + * ```js + * cu.has(['a', 'b', 'c'], 'c'); + * //=> true + * + * cu.has(['a', 'b', 'c'], ['c', 'z']); + * //=> true + * + * cu.has({a: 'b', c: 'd'}, ['c', 'z']); + * //=> true + * ``` + * @param {Object} `obj` + * @param {String|Array} `val` + * @return {Boolean} + * @api public */ -ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { - var sStr = hasNativeMap ? aStr : util.toSetString(aStr); - var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); - var idx = this._array.length; - if (!isDuplicate || aAllowDuplicates) { - this._array.push(aStr); - } - if (!isDuplicate) { - if (hasNativeMap) { - this._set.set(aStr, idx); - } else { - this._set[sStr] = idx; + +cu.has = function has(obj, val) { + val = cu.arrayify(val); + var len = val.length; + + if (cu.isObject(obj)) { + for (var key in obj) { + if (val.indexOf(key) > -1) { + return true; + } } + + var keys = cu.nativeKeys(obj); + return cu.has(keys, val); } -}; -/** - * Is the given string a member of this set? - * - * @param String aStr - */ -ArraySet.prototype.has = function ArraySet_has(aStr) { - if (hasNativeMap) { - return this._set.has(aStr); - } else { - var sStr = util.toSetString(aStr); - return has.call(this._set, sStr); + if (Array.isArray(obj)) { + var arr = obj; + while (len--) { + if (arr.indexOf(val[len]) > -1) { + return true; + } + } + return false; } + + throw new TypeError('expected an array or object.'); }; /** - * What is the index of the given string in the array? + * Returns true if an array or object has all of the given values. * - * @param String aStr + * ```js + * cu.hasAll(['a', 'b', 'c'], 'c'); + * //=> true + * + * cu.hasAll(['a', 'b', 'c'], ['c', 'z']); + * //=> false + * + * cu.hasAll({a: 'b', c: 'd'}, ['c', 'z']); + * //=> false + * ``` + * @param {Object|Array} `val` + * @param {String|Array} `values` + * @return {Boolean} + * @api public */ -ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { - if (hasNativeMap) { - var idx = this._set.get(aStr); - if (idx >= 0) { - return idx; - } - } else { - var sStr = util.toSetString(aStr); - if (has.call(this._set, sStr)) { - return this._set[sStr]; + +cu.hasAll = function hasAll(val, values) { + values = cu.arrayify(values); + var len = values.length; + while (len--) { + if (!cu.has(val, values[len])) { + return false; } } - - throw new Error('"' + aStr + '" is not in the set.'); + return true; }; /** - * What is the element at the given index? + * Cast the given value to an array. * - * @param Number aIdx + * ```js + * cu.arrayify('foo'); + * //=> ['foo'] + * + * cu.arrayify(['foo']); + * //=> ['foo'] + * ``` + * + * @param {String|Array} `val` + * @return {Array} + * @api public */ -ArraySet.prototype.at = function ArraySet_at(aIdx) { - if (aIdx >= 0 && aIdx < this._array.length) { - return this._array[aIdx]; - } - throw new Error('No element indexed by ' + aIdx); + +cu.arrayify = function arrayify(val) { + return val ? (Array.isArray(val) ? val : [val]) : []; }; /** - * Returns the array representation of this set (which has the proper indices - * indicated by indexOf). Note that this is a copy of the internal array used - * for storing the members so that no one can mess with internal state. + * Noop */ -ArraySet.prototype.toArray = function ArraySet_toArray() { - return this._array.slice(); -}; - -exports.ArraySet = ArraySet; - -/***/ }), -/* 706 */ -/***/ (function(module, exports, __webpack_require__) { +cu.noop = function noop() { + return; +}; -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2014 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause +/** + * Returns the first argument passed to the function. */ -var util = __webpack_require__(704); +cu.identity = function identity(val) { + return val; +}; /** - * Determine whether mappingB is after mappingA with respect to generated - * position. + * Returns true if a value has a `contructor` + * + * ```js + * cu.hasConstructor({}); + * //=> true + * + * cu.hasConstructor(Object.create(null)); + * //=> false + * ``` + * @param {Object} `value` + * @return {Boolean} + * @api public */ -function generatedPositionAfter(mappingA, mappingB) { - // Optimized for most common case - var lineA = mappingA.generatedLine; - var lineB = mappingB.generatedLine; - var columnA = mappingA.generatedColumn; - var columnB = mappingB.generatedColumn; - return lineB > lineA || lineB == lineA && columnB >= columnA || - util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; -} -/** - * A data structure to provide a sorted view of accumulated mappings in a - * performance conscious manner. It trades a neglibable overhead in general - * case for a large speedup in case of mappings being added in order. - */ -function MappingList() { - this._array = []; - this._sorted = true; - // Serves as infimum - this._last = {generatedLine: -1, generatedColumn: 0}; -} +cu.hasConstructor = function hasConstructor(val) { + return cu.isObject(val) && typeof val.constructor !== 'undefined'; +}; /** - * Iterate through internal items. This method takes the same arguments that - * `Array.prototype.forEach` takes. + * Get the native `ownPropertyNames` from the constructor of the + * given `object`. An empty array is returned if the object does + * not have a constructor. * - * NOTE: The order of the mappings is NOT guaranteed. + * ```js + * cu.nativeKeys({a: 'b', b: 'c', c: 'd'}) + * //=> ['a', 'b', 'c'] + * + * cu.nativeKeys(function(){}) + * //=> ['length', 'caller'] + * ``` + * + * @param {Object} `obj` Object that has a `constructor`. + * @return {Array} Array of keys. + * @api public */ -MappingList.prototype.unsortedForEach = - function MappingList_forEach(aCallback, aThisArg) { - this._array.forEach(aCallback, aThisArg); - }; + +cu.nativeKeys = function nativeKeys(val) { + if (!cu.hasConstructor(val)) return []; + return Object.getOwnPropertyNames(val); +}; /** - * Add the given source mapping. + * Returns property descriptor `key` if it's an "own" property + * of the given object. * - * @param Object aMapping + * ```js + * function App() {} + * Object.defineProperty(App.prototype, 'count', { + * get: function() { + * return Object.keys(this).length; + * } + * }); + * cu.getDescriptor(App.prototype, 'count'); + * // returns: + * // { + * // get: [Function], + * // set: undefined, + * // enumerable: false, + * // configurable: false + * // } + * ``` + * + * @param {Object} `obj` + * @param {String} `key` + * @return {Object} Returns descriptor `key` + * @api public */ -MappingList.prototype.add = function MappingList_add(aMapping) { - if (generatedPositionAfter(this._last, aMapping)) { - this._last = aMapping; - this._array.push(aMapping); - } else { - this._sorted = false; - this._array.push(aMapping); + +cu.getDescriptor = function getDescriptor(obj, key) { + if (!cu.isObject(obj)) { + throw new TypeError('expected an object.'); + } + if (typeof key !== 'string') { + throw new TypeError('expected key to be a string.'); } + return Object.getOwnPropertyDescriptor(obj, key); }; /** - * Returns the flat, sorted array of mappings. The mappings are sorted by - * generated position. + * Copy a descriptor from one object to another. * - * WARNING: This method returns internal data without copying, for - * performance. The return value must NOT be mutated, and should be treated as - * an immutable borrow. If you want to take ownership, you must make your own - * copy. + * ```js + * function App() {} + * Object.defineProperty(App.prototype, 'count', { + * get: function() { + * return Object.keys(this).length; + * } + * }); + * var obj = {}; + * cu.copyDescriptor(obj, App.prototype, 'count'); + * ``` + * @param {Object} `receiver` + * @param {Object} `provider` + * @param {String} `name` + * @return {Object} + * @api public */ -MappingList.prototype.toArray = function MappingList_toArray() { - if (!this._sorted) { - this._array.sort(util.compareByGeneratedPositionsInflated); - this._sorted = true; - } - return this._array; -}; - -exports.MappingList = MappingList; +cu.copyDescriptor = function copyDescriptor(receiver, provider, name) { + if (!cu.isObject(receiver)) { + throw new TypeError('expected receiving object to be an object.'); + } + if (!cu.isObject(provider)) { + throw new TypeError('expected providing object to be an object.'); + } + if (typeof name !== 'string') { + throw new TypeError('expected name to be a string.'); + } -/***/ }), -/* 707 */ -/***/ (function(module, exports, __webpack_require__) { + var val = cu.getDescriptor(provider, name); + if (val) Object.defineProperty(receiver, name, val); +}; -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause +/** + * Copy static properties, prototype properties, and descriptors + * from one object to another. + * + * @param {Object} `receiver` + * @param {Object} `provider` + * @param {String|Array} `omit` One or more properties to omit + * @return {Object} + * @api public */ -var util = __webpack_require__(704); -var binarySearch = __webpack_require__(708); -var ArraySet = __webpack_require__(705).ArraySet; -var base64VLQ = __webpack_require__(702); -var quickSort = __webpack_require__(709).quickSort; - -function SourceMapConsumer(aSourceMap) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); +cu.copy = function copy(receiver, provider, omit) { + if (!cu.isObject(receiver)) { + throw new TypeError('expected receiving object to be an object.'); } + if (!cu.isObject(provider)) { + throw new TypeError('expected providing object to be an object.'); + } + var props = Object.getOwnPropertyNames(provider); + var keys = Object.keys(provider); + var len = props.length, + key; + omit = cu.arrayify(omit); - return sourceMap.sections != null - ? new IndexedSourceMapConsumer(sourceMap) - : new BasicSourceMapConsumer(sourceMap); -} + while (len--) { + key = props[len]; -SourceMapConsumer.fromSourceMap = function(aSourceMap) { - return BasicSourceMapConsumer.fromSourceMap(aSourceMap); -} + if (cu.has(keys, key)) { + utils.define(receiver, key, provider[key]); + } else if (!(key in receiver) && !cu.has(omit, key)) { + cu.copyDescriptor(receiver, provider, key); + } + } +}; /** - * The version of the source mapping spec that we are consuming. + * Inherit the static properties, prototype properties, and descriptors + * from of an object. + * + * @param {Object} `receiver` + * @param {Object} `provider` + * @param {String|Array} `omit` One or more properties to omit + * @return {Object} + * @api public */ -SourceMapConsumer.prototype._version = 3; - -// `__generatedMappings` and `__originalMappings` are arrays that hold the -// parsed mapping coordinates from the source map's "mappings" attribute. They -// are lazily instantiated, accessed via the `_generatedMappings` and -// `_originalMappings` getters respectively, and we only parse the mappings -// and create these arrays once queried for a source location. We jump through -// these hoops because there can be many thousands of mappings, and parsing -// them is expensive, so we only want to do it if we must. -// -// Each object in the arrays is of the form: -// -// { -// generatedLine: The line number in the generated code, -// generatedColumn: The column number in the generated code, -// source: The path to the original source file that generated this -// chunk of code, -// originalLine: The line number in the original source that -// corresponds to this chunk of generated code, -// originalColumn: The column number in the original source that -// corresponds to this chunk of generated code, -// name: The name of the original symbol which generated this chunk of -// code. -// } -// -// All properties except for `generatedLine` and `generatedColumn` can be -// `null`. -// -// `_generatedMappings` is ordered by the generated positions. -// -// `_originalMappings` is ordered by the original positions. -SourceMapConsumer.prototype.__generatedMappings = null; -Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { - get: function () { - if (!this.__generatedMappings) { - this._parseMappings(this._mappings, this.sourceRoot); - } - - return this.__generatedMappings; +cu.inherit = function inherit(receiver, provider, omit) { + if (!cu.isObject(receiver)) { + throw new TypeError('expected receiving object to be an object.'); } -}); - -SourceMapConsumer.prototype.__originalMappings = null; -Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { - get: function () { - if (!this.__originalMappings) { - this._parseMappings(this._mappings, this.sourceRoot); - } - - return this.__originalMappings; + if (!cu.isObject(provider)) { + throw new TypeError('expected providing object to be an object.'); } -}); -SourceMapConsumer.prototype._charIsMappingSeparator = - function SourceMapConsumer_charIsMappingSeparator(aStr, index) { - var c = aStr.charAt(index); - return c === ";" || c === ","; - }; - -/** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ -SourceMapConsumer.prototype._parseMappings = - function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { - throw new Error("Subclasses must implement _parseMappings"); - }; + var keys = []; + for (var key in provider) { + keys.push(key); + receiver[key] = provider[key]; + } -SourceMapConsumer.GENERATED_ORDER = 1; -SourceMapConsumer.ORIGINAL_ORDER = 2; + keys = keys.concat(cu.arrayify(omit)); -SourceMapConsumer.GREATEST_LOWER_BOUND = 1; -SourceMapConsumer.LEAST_UPPER_BOUND = 2; + var a = provider.prototype || provider; + var b = receiver.prototype || receiver; + cu.copy(b, a, keys); +}; /** - * Iterate over each mapping between an original source/line/column and a - * generated line/column in this source map. + * Returns a function for extending the static properties, + * prototype properties, and descriptors from the `Parent` + * constructor onto `Child` constructors. * - * @param Function aCallback - * The function that is called with each mapping. - * @param Object aContext - * Optional. If specified, this object will be the value of `this` every - * time that `aCallback` is called. - * @param aOrder - * Either `SourceMapConsumer.GENERATED_ORDER` or - * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to - * iterate over the mappings sorted by the generated file's line/column - * order or the original's source/line/column order, respectively. Defaults to - * `SourceMapConsumer.GENERATED_ORDER`. + * ```js + * var extend = cu.extend(Parent); + * Parent.extend(Child); + * + * // optional methods + * Parent.extend(Child, { + * foo: function() {}, + * bar: function() {} + * }); + * ``` + * @param {Function} `Parent` Parent ctor + * @param {Function} `extend` Optional extend function to handle custom extensions. Useful when updating methods that require a specific prototype. + * @param {Function} `Child` Child ctor + * @param {Object} `proto` Optionally pass additional prototype properties to inherit. + * @return {Object} + * @api public */ -SourceMapConsumer.prototype.eachMapping = - function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { - var context = aContext || null; - var order = aOrder || SourceMapConsumer.GENERATED_ORDER; - - var mappings; - switch (order) { - case SourceMapConsumer.GENERATED_ORDER: - mappings = this._generatedMappings; - break; - case SourceMapConsumer.ORIGINAL_ORDER: - mappings = this._originalMappings; - break; - default: - throw new Error("Unknown order of iteration."); - } - var sourceRoot = this.sourceRoot; - mappings.map(function (mapping) { - var source = mapping.source === null ? null : this._sources.at(mapping.source); - if (source != null && sourceRoot != null) { - source = util.join(sourceRoot, source); - } - return { - source: source, - generatedLine: mapping.generatedLine, - generatedColumn: mapping.generatedColumn, - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name: mapping.name === null ? null : this._names.at(mapping.name) - }; - }, this).forEach(aCallback, context); - }; +cu.extend = function() { + // keep it lazy, instead of assigning to `cu.extend` + return utils.staticExtend.apply(null, arguments); +}; /** - * Returns all generated line and column information for the original source, - * line, and column provided. If no column is provided, returns all mappings - * corresponding to a either the line we are searching for or the next - * closest line that has any mappings. Otherwise, returns all mappings - * corresponding to the given line and either the column we are searching for - * or the next closest column that has any offsets. - * - * The only argument is an object with the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. - * - column: Optional. the column number in the original source. - * - * and an array of objects is returned, each with the following properties: + * Bubble up events emitted from static methods on the Parent ctor. * - * - line: The line number in the generated source, or null. - * - column: The column number in the generated source, or null. + * @param {Object} `Parent` + * @param {Array} `events` Event names to bubble up + * @api public */ -SourceMapConsumer.prototype.allGeneratedPositionsFor = - function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { - var line = util.getArg(aArgs, 'line'); - - // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping - // returns the index of the closest mapping less than the needle. By - // setting needle.originalColumn to 0, we thus find the last mapping for - // the given line, provided such a mapping exists. - var needle = { - source: util.getArg(aArgs, 'source'), - originalLine: line, - originalColumn: util.getArg(aArgs, 'column', 0) - }; - if (this.sourceRoot != null) { - needle.source = util.relative(this.sourceRoot, needle.source); +cu.bubble = function(Parent, events) { + events = events || []; + Parent.bubble = function(Child, arr) { + if (Array.isArray(arr)) { + events = utils.union([], events, arr); } - if (!this._sources.has(needle.source)) { - return []; + var len = events.length; + var idx = -1; + while (++idx < len) { + var name = events[idx]; + Parent.on(name, Child.emit.bind(Child, name)); } - needle.source = this._sources.indexOf(needle.source); + cu.bubble(Child, events); + }; +}; - var mappings = []; - var index = this._findMapping(needle, - this._originalMappings, - "originalLine", - "originalColumn", - util.compareByOriginalPositions, - binarySearch.LEAST_UPPER_BOUND); - if (index >= 0) { - var mapping = this._originalMappings[index]; +/***/ }), +/* 722 */ +/***/ (function(module, exports, __webpack_require__) { - if (aArgs.column === undefined) { - var originalLine = mapping.originalLine; +"use strict"; - // Iterate until either we run out of mappings, or we run into - // a mapping for a different line than the one we found. Since - // mappings are sorted, this is guaranteed to find all mappings for - // the line we found. - while (mapping && mapping.originalLine === originalLine) { - mappings.push({ - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }); - mapping = this._originalMappings[++index]; - } - } else { - var originalColumn = mapping.originalColumn; +var utils = {}; - // Iterate until either we run out of mappings, or we run into - // a mapping for a different line than the one we were searching for. - // Since mappings are sorted, this is guaranteed to find all mappings for - // the line we are searching for. - while (mapping && - mapping.originalLine === line && - mapping.originalColumn == originalColumn) { - mappings.push({ - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }); - mapping = this._originalMappings[++index]; - } - } - } - return mappings; - }; +/** + * Lazily required module dependencies + */ + +utils.union = __webpack_require__(704); +utils.define = __webpack_require__(723); +utils.isObj = __webpack_require__(656); +utils.staticExtend = __webpack_require__(730); -exports.SourceMapConsumer = SourceMapConsumer; /** - * A BasicSourceMapConsumer instance represents a parsed source map which we can - * query for information about the original file positions by giving it a file - * position in the generated source. - * - * The only parameter is the raw source map (either as a JSON string, or - * already parsed to an object). According to the spec, source maps have the - * following attributes: - * - * - version: Which version of the source map spec this map is following. - * - sources: An array of URLs to the original source files. - * - names: An array of identifiers which can be referrenced by individual mappings. - * - sourceRoot: Optional. The URL root from which all sources are relative. - * - sourcesContent: Optional. An array of contents of the original source files. - * - mappings: A string of base64 VLQs which contain the actual mappings. - * - file: Optional. The generated file this source map is associated with. - * - * Here is an example source map, taken from the source map spec[0]: - * - * { - * version : 3, - * file: "out.js", - * sourceRoot : "", - * sources: ["foo.js", "bar.js"], - * names: ["src", "maps", "are", "fun"], - * mappings: "AA,AB;;ABCDE;" - * } + * Expose `utils` + */ + +module.exports = utils; + + +/***/ }), +/* 723 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * define-property * - * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. */ -function BasicSourceMapConsumer(aSourceMap) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); - } - var version = util.getArg(sourceMap, 'version'); - var sources = util.getArg(sourceMap, 'sources'); - // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which - // requires the array) to play nice here. - var names = util.getArg(sourceMap, 'names', []); - var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); - var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); - var mappings = util.getArg(sourceMap, 'mappings'); - var file = util.getArg(sourceMap, 'file', null); - // Once again, Sass deviates from the spec and supplies the version as a - // string rather than a number, so we use loose equality checking here. - if (version != this._version) { - throw new Error('Unsupported version: ' + version); + +var isDescriptor = __webpack_require__(724); + +module.exports = function defineProperty(obj, prop, val) { + if (typeof obj !== 'object' && typeof obj !== 'function') { + throw new TypeError('expected an object or function.'); } - sources = sources - .map(String) - // Some source maps produce relative source paths like "./foo.js" instead of - // "foo.js". Normalize these first so that future comparisons will succeed. - // See bugzil.la/1090768. - .map(util.normalize) - // Always ensure that absolute sources are internally stored relative to - // the source root, if the source root is absolute. Not doing this would - // be particularly problematic when the source root is a prefix of the - // source (valid, but why??). See github issue #199 and bugzil.la/1188982. - .map(function (source) { - return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) - ? util.relative(sourceRoot, source) - : source; - }); + if (typeof prop !== 'string') { + throw new TypeError('expected `prop` to be a string.'); + } + + if (isDescriptor(val) && ('set' in val || 'get' in val)) { + return Object.defineProperty(obj, prop, val); + } - // Pass `true` below to allow duplicate names and sources. While source maps - // are intended to be compressed and deduplicated, the TypeScript compiler - // sometimes generates source maps with duplicates in them. See Github issue - // #72 and bugzil.la/889492. - this._names = ArraySet.fromArray(names.map(String), true); - this._sources = ArraySet.fromArray(sources, true); + return Object.defineProperty(obj, prop, { + configurable: true, + enumerable: false, + writable: true, + value: val + }); +}; - this.sourceRoot = sourceRoot; - this.sourcesContent = sourcesContent; - this._mappings = mappings; - this.file = file; -} -BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); -BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; +/***/ }), +/* 724 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * Create a BasicSourceMapConsumer from a SourceMapGenerator. +"use strict"; +/*! + * is-descriptor * - * @param SourceMapGenerator aSourceMap - * The source map that will be consumed. - * @returns BasicSourceMapConsumer + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. */ -BasicSourceMapConsumer.fromSourceMap = - function SourceMapConsumer_fromSourceMap(aSourceMap) { - var smc = Object.create(BasicSourceMapConsumer.prototype); - var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); - var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); - smc.sourceRoot = aSourceMap._sourceRoot; - smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), - smc.sourceRoot); - smc.file = aSourceMap._file; - // Because we are modifying the entries (by converting string sources and - // names to indices into the sources and names ArraySets), we have to make - // a copy of the entry or else bad things happen. Shared mutable state - // strikes again! See github issue #191. - var generatedMappings = aSourceMap._mappings.toArray().slice(); - var destGeneratedMappings = smc.__generatedMappings = []; - var destOriginalMappings = smc.__originalMappings = []; +var typeOf = __webpack_require__(725); +var isAccessor = __webpack_require__(726); +var isData = __webpack_require__(728); - for (var i = 0, length = generatedMappings.length; i < length; i++) { - var srcMapping = generatedMappings[i]; - var destMapping = new Mapping; - destMapping.generatedLine = srcMapping.generatedLine; - destMapping.generatedColumn = srcMapping.generatedColumn; +module.exports = function isDescriptor(obj, key) { + if (typeOf(obj) !== 'object') { + return false; + } + if ('get' in obj) { + return isAccessor(obj, key); + } + return isData(obj, key); +}; - if (srcMapping.source) { - destMapping.source = sources.indexOf(srcMapping.source); - destMapping.originalLine = srcMapping.originalLine; - destMapping.originalColumn = srcMapping.originalColumn; - if (srcMapping.name) { - destMapping.name = names.indexOf(srcMapping.name); - } +/***/ }), +/* 725 */ +/***/ (function(module, exports) { - destOriginalMappings.push(destMapping); - } +var toString = Object.prototype.toString; - destGeneratedMappings.push(destMapping); +/** + * Get the native `typeof` a value. + * + * @param {*} `val` + * @return {*} Native javascript type + */ + +module.exports = function kindOf(val) { + var type = typeof val; + + // primitivies + if (type === 'undefined') { + return 'undefined'; + } + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (type === 'string' || val instanceof String) { + return 'string'; + } + if (type === 'number' || val instanceof Number) { + return 'number'; + } + + // functions + if (type === 'function' || val instanceof Function) { + if (typeof val.constructor.name !== 'undefined' && val.constructor.name.slice(0, 9) === 'Generator') { + return 'generatorfunction'; } + return 'function'; + } - quickSort(smc.__originalMappings, util.compareByOriginalPositions); + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; + } - return smc; - }; + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; + } -/** - * The version of the source mapping spec that we are consuming. - */ -BasicSourceMapConsumer.prototype._version = 3; + // other objects + type = toString.call(val); -/** - * The list of original sources. - */ -Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { - get: function () { - return this._sources.toArray().map(function (s) { - return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s; - }, this); + if (type === '[object RegExp]') { + return 'regexp'; } -}); + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; + } + if (type === '[object Promise]') { + return 'promise'; + } + + // buffer + if (isBuffer(val)) { + return 'buffer'; + } + + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; + } + + if (type === '[object Map Iterator]') { + return 'mapiterator'; + } + if (type === '[object Set Iterator]') { + return 'setiterator'; + } + if (type === '[object String Iterator]') { + return 'stringiterator'; + } + if (type === '[object Array Iterator]') { + return 'arrayiterator'; + } + + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } + + // must be a plain object + return 'object'; +}; /** - * Provide the JIT with a nice shape / hidden class. + * If you need to support Safari 5-7 (8-10 yr-old browser), + * take a look at https://github.com/feross/is-buffer */ -function Mapping() { - this.generatedLine = 0; - this.generatedColumn = 0; - this.source = null; - this.originalLine = null; - this.originalColumn = null; - this.name = null; + +function isBuffer(val) { + return val.constructor + && typeof val.constructor.isBuffer === 'function' + && val.constructor.isBuffer(val); } -/** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ -BasicSourceMapConsumer.prototype._parseMappings = - function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { - var generatedLine = 1; - var previousGeneratedColumn = 0; - var previousOriginalLine = 0; - var previousOriginalColumn = 0; - var previousSource = 0; - var previousName = 0; - var length = aStr.length; - var index = 0; - var cachedSegments = {}; - var temp = {}; - var originalMappings = []; - var generatedMappings = []; - var mapping, str, segment, end, value; - while (index < length) { - if (aStr.charAt(index) === ';') { - generatedLine++; - index++; - previousGeneratedColumn = 0; - } - else if (aStr.charAt(index) === ',') { - index++; - } - else { - mapping = new Mapping(); - mapping.generatedLine = generatedLine; +/***/ }), +/* 726 */ +/***/ (function(module, exports, __webpack_require__) { - // Because each offset is encoded relative to the previous one, - // many segments often have the same encoding. We can exploit this - // fact by caching the parsed variable length fields of each segment, - // allowing us to avoid a second parse if we encounter the same - // segment again. - for (end = index; end < length; end++) { - if (this._charIsMappingSeparator(aStr, end)) { - break; - } - } - str = aStr.slice(index, end); +"use strict"; +/*! + * is-accessor-descriptor + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ - segment = cachedSegments[str]; - if (segment) { - index += str.length; - } else { - segment = []; - while (index < end) { - base64VLQ.decode(aStr, index, temp); - value = temp.value; - index = temp.rest; - segment.push(value); - } - if (segment.length === 2) { - throw new Error('Found a source, but no line and column'); - } - if (segment.length === 3) { - throw new Error('Found a source and line, but no column'); - } +var typeOf = __webpack_require__(727); - cachedSegments[str] = segment; - } +// accessor descriptor properties +var accessor = { + get: 'function', + set: 'function', + configurable: 'boolean', + enumerable: 'boolean' +}; - // Generated column. - mapping.generatedColumn = previousGeneratedColumn + segment[0]; - previousGeneratedColumn = mapping.generatedColumn; +function isAccessorDescriptor(obj, prop) { + if (typeof prop === 'string') { + var val = Object.getOwnPropertyDescriptor(obj, prop); + return typeof val !== 'undefined'; + } - if (segment.length > 1) { - // Original source. - mapping.source = previousSource + segment[1]; - previousSource += segment[1]; + if (typeOf(obj) !== 'object') { + return false; + } - // Original line. - mapping.originalLine = previousOriginalLine + segment[2]; - previousOriginalLine = mapping.originalLine; - // Lines are stored 0-based - mapping.originalLine += 1; + if (has(obj, 'value') || has(obj, 'writable')) { + return false; + } - // Original column. - mapping.originalColumn = previousOriginalColumn + segment[3]; - previousOriginalColumn = mapping.originalColumn; + if (!has(obj, 'get') || typeof obj.get !== 'function') { + return false; + } - if (segment.length > 4) { - // Original name. - mapping.name = previousName + segment[4]; - previousName += segment[4]; - } - } + // tldr: it's valid to have "set" be undefined + // "set" might be undefined if `Object.getOwnPropertyDescriptor` + // was used to get the value, and only `get` was defined by the user + if (has(obj, 'set') && typeof obj[key] !== 'function' && typeof obj[key] !== 'undefined') { + return false; + } - generatedMappings.push(mapping); - if (typeof mapping.originalLine === 'number') { - originalMappings.push(mapping); - } - } + for (var key in obj) { + if (!accessor.hasOwnProperty(key)) { + continue; } - quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); - this.__generatedMappings = generatedMappings; + if (typeOf(obj[key]) === accessor[key]) { + continue; + } - quickSort(originalMappings, util.compareByOriginalPositions); - this.__originalMappings = originalMappings; - }; + if (typeof obj[key] !== 'undefined') { + return false; + } + } + return true; +} + +function has(obj, key) { + return {}.hasOwnProperty.call(obj, key); +} /** - * Find the mapping that best matches the hypothetical "needle" mapping that - * we are searching for in the given "haystack" of mappings. + * Expose `isAccessorDescriptor` */ -BasicSourceMapConsumer.prototype._findMapping = - function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, - aColumnName, aComparator, aBias) { - // To return the position we are searching for, we must first find the - // mapping for the given position and then return the opposite position it - // points to. Because the mappings are sorted, we can use binary search to - // find the best mapping. - if (aNeedle[aLineName] <= 0) { - throw new TypeError('Line must be greater than or equal to 1, got ' - + aNeedle[aLineName]); - } - if (aNeedle[aColumnName] < 0) { - throw new TypeError('Column must be greater than or equal to 0, got ' - + aNeedle[aColumnName]); - } +module.exports = isAccessorDescriptor; - return binarySearch.search(aNeedle, aMappings, aComparator, aBias); - }; + +/***/ }), +/* 727 */ +/***/ (function(module, exports, __webpack_require__) { + +var isBuffer = __webpack_require__(680); +var toString = Object.prototype.toString; /** - * Compute the last column for each generated mapping. The last column is - * inclusive. + * Get the native `typeof` a value. + * + * @param {*} `val` + * @return {*} Native javascript type */ -BasicSourceMapConsumer.prototype.computeColumnSpans = - function SourceMapConsumer_computeColumnSpans() { - for (var index = 0; index < this._generatedMappings.length; ++index) { - var mapping = this._generatedMappings[index]; - // Mappings do not contain a field for the last generated columnt. We - // can come up with an optimistic estimate, however, by assuming that - // mappings are contiguous (i.e. given two consecutive mappings, the - // first mapping ends where the second one starts). - if (index + 1 < this._generatedMappings.length) { - var nextMapping = this._generatedMappings[index + 1]; +module.exports = function kindOf(val) { + // primitivies + if (typeof val === 'undefined') { + return 'undefined'; + } + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (typeof val === 'string' || val instanceof String) { + return 'string'; + } + if (typeof val === 'number' || val instanceof Number) { + return 'number'; + } + + // functions + if (typeof val === 'function' || val instanceof Function) { + return 'function'; + } + + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; + } + + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; + } + + // other objects + var type = toString.call(val); + + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; + } + + // buffer + if (isBuffer(val)) { + return 'buffer'; + } + + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; + } + + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } + + // must be a plain object + return 'object'; +}; - if (mapping.generatedLine === nextMapping.generatedLine) { - mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; - continue; - } - } - // The last mapping for each line spans the entire line. - mapping.lastGeneratedColumn = Infinity; - } - }; +/***/ }), +/* 728 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * Returns the original source, line, and column information for the generated - * source's line and column positions provided. The only argument is an object - * with the following properties: - * - * - line: The line number in the generated source. - * - column: The column number in the generated source. - * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or - * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. - * - * and an object is returned with the following properties: +"use strict"; +/*! + * is-data-descriptor * - * - source: The original source file, or null. - * - line: The line number in the original source, or null. - * - column: The column number in the original source, or null. - * - name: The original identifier, or null. + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. */ -BasicSourceMapConsumer.prototype.originalPositionFor = - function SourceMapConsumer_originalPositionFor(aArgs) { - var needle = { - generatedLine: util.getArg(aArgs, 'line'), - generatedColumn: util.getArg(aArgs, 'column') - }; - - var index = this._findMapping( - needle, - this._generatedMappings, - "generatedLine", - "generatedColumn", - util.compareByGeneratedPositionsDeflated, - util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) - ); - if (index >= 0) { - var mapping = this._generatedMappings[index]; - if (mapping.generatedLine === needle.generatedLine) { - var source = util.getArg(mapping, 'source', null); - if (source !== null) { - source = this._sources.at(source); - if (this.sourceRoot != null) { - source = util.join(this.sourceRoot, source); - } - } - var name = util.getArg(mapping, 'name', null); - if (name !== null) { - name = this._names.at(name); - } - return { - source: source, - line: util.getArg(mapping, 'originalLine', null), - column: util.getArg(mapping, 'originalColumn', null), - name: name - }; - } - } - return { - source: null, - line: null, - column: null, - name: null - }; - }; +var typeOf = __webpack_require__(729); -/** - * Return true if we have the source content for every source in the source - * map, false otherwise. - */ -BasicSourceMapConsumer.prototype.hasContentsOfAllSources = - function BasicSourceMapConsumer_hasContentsOfAllSources() { - if (!this.sourcesContent) { - return false; - } - return this.sourcesContent.length >= this._sources.size() && - !this.sourcesContent.some(function (sc) { return sc == null; }); - }; +// data descriptor properties +var data = { + configurable: 'boolean', + enumerable: 'boolean', + writable: 'boolean' +}; -/** - * Returns the original source content. The only argument is the url of the - * original source file. Returns null if no original source content is - * available. - */ -BasicSourceMapConsumer.prototype.sourceContentFor = - function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { - if (!this.sourcesContent) { - return null; - } +function isDataDescriptor(obj, prop) { + if (typeOf(obj) !== 'object') { + return false; + } - if (this.sourceRoot != null) { - aSource = util.relative(this.sourceRoot, aSource); - } + if (typeof prop === 'string') { + var val = Object.getOwnPropertyDescriptor(obj, prop); + return typeof val !== 'undefined'; + } - if (this._sources.has(aSource)) { - return this.sourcesContent[this._sources.indexOf(aSource)]; - } + if (!('value' in obj) && !('writable' in obj)) { + return false; + } - var url; - if (this.sourceRoot != null - && (url = util.urlParse(this.sourceRoot))) { - // XXX: file:// URIs and absolute paths lead to unexpected behavior for - // many users. We can help them out when they expect file:// URIs to - // behave like it would if they were running a local HTTP server. See - // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. - var fileUriAbsPath = aSource.replace(/^file:\/\//, ""); - if (url.scheme == "file" - && this._sources.has(fileUriAbsPath)) { - return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] - } + for (var key in obj) { + if (key === 'value') continue; - if ((!url.path || url.path == "/") - && this._sources.has("/" + aSource)) { - return this.sourcesContent[this._sources.indexOf("/" + aSource)]; - } + if (!data.hasOwnProperty(key)) { + continue; } - // This function is used recursively from - // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we - // don't want to throw if we can't find the source - we just want to - // return null, so we provide a flag to exit gracefully. - if (nullOnMissing) { - return null; + if (typeOf(obj[key]) === data[key]) { + continue; } - else { - throw new Error('"' + aSource + '" is not in the SourceMap.'); + + if (typeof obj[key] !== 'undefined') { + return false; } - }; + } + return true; +} /** - * Returns the generated line and column information for the original source, - * line, and column positions provided. The only argument is an object with - * the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. - * - column: The column number in the original source. - * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or - * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. - * - * and an object is returned with the following properties: - * - * - line: The line number in the generated source, or null. - * - column: The column number in the generated source, or null. + * Expose `isDataDescriptor` */ -BasicSourceMapConsumer.prototype.generatedPositionFor = - function SourceMapConsumer_generatedPositionFor(aArgs) { - var source = util.getArg(aArgs, 'source'); - if (this.sourceRoot != null) { - source = util.relative(this.sourceRoot, source); - } - if (!this._sources.has(source)) { - return { - line: null, - column: null, - lastColumn: null - }; - } - source = this._sources.indexOf(source); - - var needle = { - source: source, - originalLine: util.getArg(aArgs, 'line'), - originalColumn: util.getArg(aArgs, 'column') - }; - - var index = this._findMapping( - needle, - this._originalMappings, - "originalLine", - "originalColumn", - util.compareByOriginalPositions, - util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) - ); - if (index >= 0) { - var mapping = this._originalMappings[index]; +module.exports = isDataDescriptor; - if (mapping.source === needle.source) { - return { - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }; - } - } - return { - line: null, - column: null, - lastColumn: null - }; - }; +/***/ }), +/* 729 */ +/***/ (function(module, exports, __webpack_require__) { -exports.BasicSourceMapConsumer = BasicSourceMapConsumer; +var isBuffer = __webpack_require__(680); +var toString = Object.prototype.toString; /** - * An IndexedSourceMapConsumer instance represents a parsed source map which - * we can query for information. It differs from BasicSourceMapConsumer in - * that it takes "indexed" source maps (i.e. ones with a "sections" field) as - * input. - * - * The only parameter is a raw source map (either as a JSON string, or already - * parsed to an object). According to the spec for indexed source maps, they - * have the following attributes: - * - * - version: Which version of the source map spec this map is following. - * - file: Optional. The generated file this source map is associated with. - * - sections: A list of section definitions. - * - * Each value under the "sections" field has two fields: - * - offset: The offset into the original specified at which this section - * begins to apply, defined as an object with a "line" and "column" - * field. - * - map: A source map definition. This source map could also be indexed, - * but doesn't have to be. - * - * Instead of the "map" field, it's also possible to have a "url" field - * specifying a URL to retrieve a source map from, but that's currently - * unsupported. - * - * Here's an example source map, taken from the source map spec[0], but - * modified to omit a section which uses the "url" field. - * - * { - * version : 3, - * file: "app.js", - * sections: [{ - * offset: {line:100, column:10}, - * map: { - * version : 3, - * file: "section.js", - * sources: ["foo.js", "bar.js"], - * names: ["src", "maps", "are", "fun"], - * mappings: "AAAA,E;;ABCDE;" - * } - * }], - * } + * Get the native `typeof` a value. * - * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + * @param {*} `val` + * @return {*} Native javascript type */ -function IndexedSourceMapConsumer(aSourceMap) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); - } - - var version = util.getArg(sourceMap, 'version'); - var sections = util.getArg(sourceMap, 'sections'); - if (version != this._version) { - throw new Error('Unsupported version: ' + version); +module.exports = function kindOf(val) { + // primitivies + if (typeof val === 'undefined') { + return 'undefined'; + } + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (typeof val === 'string' || val instanceof String) { + return 'string'; + } + if (typeof val === 'number' || val instanceof Number) { + return 'number'; } - this._sources = new ArraySet(); - this._names = new ArraySet(); - - var lastOffset = { - line: -1, - column: 0 - }; - this._sections = sections.map(function (s) { - if (s.url) { - // The url field will require support for asynchronicity. - // See https://github.com/mozilla/source-map/issues/16 - throw new Error('Support for url field in sections not implemented.'); - } - var offset = util.getArg(s, 'offset'); - var offsetLine = util.getArg(offset, 'line'); - var offsetColumn = util.getArg(offset, 'column'); - - if (offsetLine < lastOffset.line || - (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { - throw new Error('Section offsets must be ordered and non-overlapping.'); - } - lastOffset = offset; + // functions + if (typeof val === 'function' || val instanceof Function) { + return 'function'; + } - return { - generatedOffset: { - // The offset fields are 0-based, but we use 1-based indices when - // encoding/decoding from VLQ. - generatedLine: offsetLine + 1, - generatedColumn: offsetColumn + 1 - }, - consumer: new SourceMapConsumer(util.getArg(s, 'map')) - } - }); -} + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; + } -IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); -IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; + } -/** - * The version of the source mapping spec that we are consuming. - */ -IndexedSourceMapConsumer.prototype._version = 3; + // other objects + var type = toString.call(val); -/** - * The list of original sources. - */ -Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { - get: function () { - var sources = []; - for (var i = 0; i < this._sections.length; i++) { - for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { - sources.push(this._sections[i].consumer.sources[j]); - } - } - return sources; + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; } -}); -/** - * Returns the original source, line, and column information for the generated - * source's line and column positions provided. The only argument is an object - * with the following properties: - * - * - line: The line number in the generated source. - * - column: The column number in the generated source. - * - * and an object is returned with the following properties: - * - * - source: The original source file, or null. - * - line: The line number in the original source, or null. - * - column: The column number in the original source, or null. - * - name: The original identifier, or null. - */ -IndexedSourceMapConsumer.prototype.originalPositionFor = - function IndexedSourceMapConsumer_originalPositionFor(aArgs) { - var needle = { - generatedLine: util.getArg(aArgs, 'line'), - generatedColumn: util.getArg(aArgs, 'column') - }; + // buffer + if (isBuffer(val)) { + return 'buffer'; + } - // Find the section containing the generated position we're trying to map - // to an original position. - var sectionIndex = binarySearch.search(needle, this._sections, - function(needle, section) { - var cmp = needle.generatedLine - section.generatedOffset.generatedLine; - if (cmp) { - return cmp; - } + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; + } - return (needle.generatedColumn - - section.generatedOffset.generatedColumn); - }); - var section = this._sections[sectionIndex]; + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } - if (!section) { - return { - source: null, - line: null, - column: null, - name: null - }; - } + // must be a plain object + return 'object'; +}; - return section.consumer.originalPositionFor({ - line: needle.generatedLine - - (section.generatedOffset.generatedLine - 1), - column: needle.generatedColumn - - (section.generatedOffset.generatedLine === needle.generatedLine - ? section.generatedOffset.generatedColumn - 1 - : 0), - bias: aArgs.bias - }); - }; -/** - * Return true if we have the source content for every source in the source - * map, false otherwise. - */ -IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = - function IndexedSourceMapConsumer_hasContentsOfAllSources() { - return this._sections.every(function (s) { - return s.consumer.hasContentsOfAllSources(); - }); - }; +/***/ }), +/* 730 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * Returns the original source content. The only argument is the url of the - * original source file. Returns null if no original source content is - * available. +"use strict"; +/*! + * static-extend + * + * Copyright (c) 2016, Jon Schlinkert. + * Licensed under the MIT License. */ -IndexedSourceMapConsumer.prototype.sourceContentFor = - function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - var content = section.consumer.sourceContentFor(aSource, true); - if (content) { - return content; - } - } - if (nullOnMissing) { - return null; - } - else { - throw new Error('"' + aSource + '" is not in the SourceMap.'); - } - }; + + +var copy = __webpack_require__(731); +var define = __webpack_require__(723); +var util = __webpack_require__(234); /** - * Returns the generated line and column information for the original source, - * line, and column positions provided. The only argument is an object with - * the following properties: + * Returns a function for extending the static properties, + * prototype properties, and descriptors from the `Parent` + * constructor onto `Child` constructors. * - * - source: The filename of the original source. - * - line: The line number in the original source. - * - column: The column number in the original source. + * ```js + * var extend = require('static-extend'); + * Parent.extend = extend(Parent); * - * and an object is returned with the following properties: + * // optionally pass a custom merge function as the second arg + * Parent.extend = extend(Parent, function(Child) { + * Child.prototype.mixin = function(key, val) { + * Child.prototype[key] = val; + * }; + * }); * - * - line: The line number in the generated source, or null. - * - column: The column number in the generated source, or null. + * // extend "child" constructors + * Parent.extend(Child); + * + * // optionally define prototype methods as the second arg + * Parent.extend(Child, { + * foo: function() {}, + * bar: function() {} + * }); + * ``` + * @param {Function} `Parent` Parent ctor + * @param {Function} `extendFn` Optional extend function for handling any necessary custom merging. Useful when updating methods that require a specific prototype. + * @param {Function} `Child` Child ctor + * @param {Object} `proto` Optionally pass additional prototype properties to inherit. + * @return {Object} + * @api public */ -IndexedSourceMapConsumer.prototype.generatedPositionFor = - function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - - // Only consider this section if the requested source is in the list of - // sources of the consumer. - if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) { - continue; - } - var generatedPosition = section.consumer.generatedPositionFor(aArgs); - if (generatedPosition) { - var ret = { - line: generatedPosition.line + - (section.generatedOffset.generatedLine - 1), - column: generatedPosition.column + - (section.generatedOffset.generatedLine === generatedPosition.line - ? section.generatedOffset.generatedColumn - 1 - : 0) - }; - return ret; - } - } - return { - line: null, - column: null - }; - }; +function extend(Parent, extendFn) { + if (typeof Parent !== 'function') { + throw new TypeError('expected Parent to be a function.'); + } -/** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ -IndexedSourceMapConsumer.prototype._parseMappings = - function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { - this.__generatedMappings = []; - this.__originalMappings = []; - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - var sectionMappings = section.consumer._generatedMappings; - for (var j = 0; j < sectionMappings.length; j++) { - var mapping = sectionMappings[j]; + return function(Ctor, proto) { + if (typeof Ctor !== 'function') { + throw new TypeError('expected Ctor to be a function.'); + } - var source = section.consumer._sources.at(mapping.source); - if (section.consumer.sourceRoot !== null) { - source = util.join(section.consumer.sourceRoot, source); - } - this._sources.add(source); - source = this._sources.indexOf(source); + util.inherits(Ctor, Parent); + copy(Ctor, Parent); - var name = section.consumer._names.at(mapping.name); - this._names.add(name); - name = this._names.indexOf(name); + // proto can be null or a plain object + if (typeof proto === 'object') { + var obj = Object.create(proto); - // The mappings coming from the consumer for the section have - // generated positions relative to the start of the section, so we - // need to offset them to be relative to the start of the concatenated - // generated file. - var adjustedMapping = { - source: source, - generatedLine: mapping.generatedLine + - (section.generatedOffset.generatedLine - 1), - generatedColumn: mapping.generatedColumn + - (section.generatedOffset.generatedLine === mapping.generatedLine - ? section.generatedOffset.generatedColumn - 1 - : 0), - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name: name - }; + for (var k in obj) { + Ctor.prototype[k] = obj[k]; + } + } - this.__generatedMappings.push(adjustedMapping); - if (typeof adjustedMapping.originalLine === 'number') { - this.__originalMappings.push(adjustedMapping); - } + // keep a reference to the parent prototype + define(Ctor.prototype, '_parent_', { + configurable: true, + set: function() {}, + get: function() { + return Parent.prototype; } + }); + + if (typeof extendFn === 'function') { + extendFn(Ctor, Parent); } - quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); - quickSort(this.__originalMappings, util.compareByOriginalPositions); + Ctor.extend = extend(Ctor, extendFn); }; +}; -exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; +/** + * Expose `extend` + */ + +module.exports = extend; /***/ }), -/* 708 */ -/***/ (function(module, exports) { +/* 731 */ +/***/ (function(module, exports, __webpack_require__) { -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ +"use strict"; -exports.GREATEST_LOWER_BOUND = 1; -exports.LEAST_UPPER_BOUND = 2; + +var typeOf = __webpack_require__(732); +var copyDescriptor = __webpack_require__(733); +var define = __webpack_require__(723); /** - * Recursive implementation of binary search. + * Copy static properties, prototype properties, and descriptors from one object to another. * - * @param aLow Indices here and lower do not contain the needle. - * @param aHigh Indices here and higher do not contain the needle. - * @param aNeedle The element being searched for. - * @param aHaystack The non-empty array being searched. - * @param aCompare Function which takes two elements and returns -1, 0, or 1. - * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or - * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. + * ```js + * function App() {} + * var proto = App.prototype; + * App.prototype.set = function() {}; + * App.prototype.get = function() {}; + * + * var obj = {}; + * copy(obj, proto); + * ``` + * @param {Object} `receiver` + * @param {Object} `provider` + * @param {String|Array} `omit` One or more properties to omit + * @return {Object} + * @api public */ -function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { - // This function terminates when one of the following is true: - // - // 1. We find the exact element we are looking for. - // - // 2. We did not find the exact element, but we can return the index of - // the next-closest element. - // - // 3. We did not find the exact element, and there is no next-closest - // element than the one we are searching for, so we return -1. - var mid = Math.floor((aHigh - aLow) / 2) + aLow; - var cmp = aCompare(aNeedle, aHaystack[mid], true); - if (cmp === 0) { - // Found the element we are looking for. - return mid; - } - else if (cmp > 0) { - // Our needle is greater than aHaystack[mid]. - if (aHigh - mid > 1) { - // The element is in the upper half. - return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); - } - // The exact needle element was not found in this haystack. Determine if - // we are in termination case (3) or (2) and return the appropriate thing. - if (aBias == exports.LEAST_UPPER_BOUND) { - return aHigh < aHaystack.length ? aHigh : -1; - } else { - return mid; - } +function copy(receiver, provider, omit) { + if (!isObject(receiver)) { + throw new TypeError('expected receiving object to be an object.'); } - else { - // Our needle is less than aHaystack[mid]. - if (mid - aLow > 1) { - // The element is in the lower half. - return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); - } - - // we are in termination case (3) or (2) and return the appropriate thing. - if (aBias == exports.LEAST_UPPER_BOUND) { - return mid; - } else { - return aLow < 0 ? -1 : aLow; - } + if (!isObject(provider)) { + throw new TypeError('expected providing object to be an object.'); } -} -/** - * This is an implementation of binary search which will always try and return - * the index of the closest element if there is no exact hit. This is because - * mappings between original and generated line/col pairs are single points, - * and there is an implicit region between each of them, so a miss just means - * that you aren't on the very start of a region. - * - * @param aNeedle The element you are looking for. - * @param aHaystack The array that is being searched. - * @param aCompare A function which takes the needle and an element in the - * array and returns -1, 0, or 1 depending on whether the needle is less - * than, equal to, or greater than the element, respectively. - * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or - * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. - */ -exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { - if (aHaystack.length === 0) { - return -1; - } + var props = nativeKeys(provider); + var keys = Object.keys(provider); + var len = props.length; + omit = arrayify(omit); - var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, - aCompare, aBias || exports.GREATEST_LOWER_BOUND); - if (index < 0) { - return -1; - } + while (len--) { + var key = props[len]; - // We have found either the exact element, or the next-closest element than - // the one we are searching for. However, there may be more than one such - // element. Make sure we always return the smallest of these. - while (index - 1 >= 0) { - if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { - break; + if (has(keys, key)) { + define(receiver, key, provider[key]); + } else if (!(key in receiver) && !has(omit, key)) { + copyDescriptor(receiver, provider, key); } - --index; } - - return index; }; - -/***/ }), -/* 709 */ -/***/ (function(module, exports) { - -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -// It turns out that some (most?) JavaScript engines don't self-host -// `Array.prototype.sort`. This makes sense because C++ will likely remain -// faster than JS when doing raw CPU-intensive sorting. However, when using a -// custom comparator function, calling back and forth between the VM's C++ and -// JIT'd JS is rather slow *and* loses JIT type information, resulting in -// worse generated code for the comparator function than would be optimal. In -// fact, when sorting with a comparator, these costs outweigh the benefits of -// sorting in C++. By using our own JS-implemented Quick Sort (below), we get -// a ~3500ms mean speed-up in `bench/bench.html`. - /** - * Swap the elements indexed by `x` and `y` in the array `ary`. - * - * @param {Array} ary - * The array. - * @param {Number} x - * The index of the first item. - * @param {Number} y - * The index of the second item. + * Return true if the given value is an object or function */ -function swap(ary, x, y) { - var temp = ary[x]; - ary[x] = ary[y]; - ary[y] = temp; -} -/** - * Returns a random integer within the range `low .. high` inclusive. - * - * @param {Number} low - * The lower bound on the range. - * @param {Number} high - * The upper bound on the range. - */ -function randomIntInRange(low, high) { - return Math.round(low + (Math.random() * (high - low))); +function isObject(val) { + return typeOf(val) === 'object' || typeof val === 'function'; } /** - * The Quick Sort algorithm. + * Returns true if an array has any of the given elements, or an + * object has any of the give keys. * - * @param {Array} ary - * An array to sort. - * @param {function} comparator - * Function to use to compare two items. - * @param {Number} p - * Start index of the array - * @param {Number} r - * End index of the array + * ```js + * has(['a', 'b', 'c'], 'c'); + * //=> true + * + * has(['a', 'b', 'c'], ['c', 'z']); + * //=> true + * + * has({a: 'b', c: 'd'}, ['c', 'z']); + * //=> true + * ``` + * @param {Object} `obj` + * @param {String|Array} `val` + * @return {Boolean} */ -function doQuickSort(ary, comparator, p, r) { - // If our lower bound is less than our upper bound, we (1) partition the - // array into two pieces and (2) recurse on each half. If it is not, this is - // the empty array and our base case. - - if (p < r) { - // (1) Partitioning. - // - // The partitioning chooses a pivot between `p` and `r` and moves all - // elements that are less than or equal to the pivot to the before it, and - // all the elements that are greater than it after it. The effect is that - // once partition is done, the pivot is in the exact place it will be when - // the array is put in sorted order, and it will not need to be moved - // again. This runs in O(n) time. - - // Always choose a random pivot so that an input array which is reverse - // sorted does not cause O(n^2) running time. - var pivotIndex = randomIntInRange(p, r); - var i = p - 1; - swap(ary, pivotIndex, r); - var pivot = ary[r]; +function has(obj, val) { + val = arrayify(val); + var len = val.length; - // Immediately after `j` is incremented in this loop, the following hold - // true: - // - // * Every element in `ary[p .. i]` is less than or equal to the pivot. - // - // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. - for (var j = p; j < r; j++) { - if (comparator(ary[j], pivot) <= 0) { - i += 1; - swap(ary, i, j); + if (isObject(obj)) { + for (var key in obj) { + if (val.indexOf(key) > -1) { + return true; } } - swap(ary, i + 1, j); - var q = i + 1; - - // (2) Recurse on each half. + var keys = nativeKeys(obj); + return has(keys, val); + } - doQuickSort(ary, comparator, p, q - 1); - doQuickSort(ary, comparator, q + 1, r); + if (Array.isArray(obj)) { + var arr = obj; + while (len--) { + if (arr.indexOf(val[len]) > -1) { + return true; + } + } + return false; } + + throw new TypeError('expected an array or object.'); } /** - * Sort the given array in-place with the given comparator function. + * Cast the given value to an array. * - * @param {Array} ary - * An array to sort. - * @param {function} comparator - * Function to use to compare two items. - */ -exports.quickSort = function (ary, comparator) { - doQuickSort(ary, comparator, 0, ary.length - 1); -}; - - -/***/ }), -/* 710 */ -/***/ (function(module, exports, __webpack_require__) { - -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause + * ```js + * arrayify('foo'); + * //=> ['foo'] + * + * arrayify(['foo']); + * //=> ['foo'] + * ``` + * + * @param {String|Array} `val` + * @return {Array} */ -var SourceMapGenerator = __webpack_require__(701).SourceMapGenerator; -var util = __webpack_require__(704); - -// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other -// operating systems these days (capturing the result). -var REGEX_NEWLINE = /(\r?\n)/; - -// Newline character code for charCodeAt() comparisons -var NEWLINE_CODE = 10; - -// Private symbol for identifying `SourceNode`s when multiple versions of -// the source-map library are loaded. This MUST NOT CHANGE across -// versions! -var isSourceNode = "$$$isSourceNode$$$"; +function arrayify(val) { + return val ? (Array.isArray(val) ? val : [val]) : []; +} /** - * SourceNodes provide a way to abstract over interpolating/concatenating - * snippets of generated JavaScript source code while maintaining the line and - * column information associated with the original source code. + * Returns true if a value has a `contructor` * - * @param aLine The original line number. - * @param aColumn The original column number. - * @param aSource The original source's filename. - * @param aChunks Optional. An array of strings which are snippets of - * generated JS, or other SourceNodes. - * @param aName The original identifier. - */ -function SourceNode(aLine, aColumn, aSource, aChunks, aName) { - this.children = []; - this.sourceContents = {}; - this.line = aLine == null ? null : aLine; - this.column = aColumn == null ? null : aColumn; - this.source = aSource == null ? null : aSource; - this.name = aName == null ? null : aName; - this[isSourceNode] = true; - if (aChunks != null) this.add(aChunks); + * ```js + * hasConstructor({}); + * //=> true + * + * hasConstructor(Object.create(null)); + * //=> false + * ``` + * @param {Object} `value` + * @return {Boolean} + */ + +function hasConstructor(val) { + return isObject(val) && typeof val.constructor !== 'undefined'; } /** - * Creates a SourceNode from generated code and a SourceMapConsumer. + * Get the native `ownPropertyNames` from the constructor of the + * given `object`. An empty array is returned if the object does + * not have a constructor. * - * @param aGeneratedCode The generated code - * @param aSourceMapConsumer The SourceMap for the generated code - * @param aRelativePath Optional. The path that relative sources in the - * SourceMapConsumer should be relative to. + * ```js + * nativeKeys({a: 'b', b: 'c', c: 'd'}) + * //=> ['a', 'b', 'c'] + * + * nativeKeys(function(){}) + * //=> ['length', 'caller'] + * ``` + * + * @param {Object} `obj` Object that has a `constructor`. + * @return {Array} Array of keys. */ -SourceNode.fromStringWithSourceMap = - function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { - // The SourceNode we want to fill with the generated code - // and the SourceMap - var node = new SourceNode(); - // All even indices of this array are one line of the generated code, - // while all odd indices are the newlines between two adjacent lines - // (since `REGEX_NEWLINE` captures its match). - // Processed fragments are accessed by calling `shiftNextLine`. - var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); - var remainingLinesIndex = 0; - var shiftNextLine = function() { - var lineContents = getNextLine(); - // The last line of a file might not have a newline. - var newLine = getNextLine() || ""; - return lineContents + newLine; +function nativeKeys(val) { + if (!hasConstructor(val)) return []; + return Object.getOwnPropertyNames(val); +} - function getNextLine() { - return remainingLinesIndex < remainingLines.length ? - remainingLines[remainingLinesIndex++] : undefined; - } - }; +/** + * Expose `copy` + */ - // We need to remember the position of "remainingLines" - var lastGeneratedLine = 1, lastGeneratedColumn = 0; +module.exports = copy; - // The generate SourceNodes we need a code range. - // To extract it current and last mapping is used. - // Here we store the last mapping. - var lastMapping = null; +/** + * Expose `copy.has` for tests + */ - aSourceMapConsumer.eachMapping(function (mapping) { - if (lastMapping !== null) { - // We add the code from "lastMapping" to "mapping": - // First check if there is a new line in between. - if (lastGeneratedLine < mapping.generatedLine) { - // Associate first line with "lastMapping" - addMappingWithCode(lastMapping, shiftNextLine()); - lastGeneratedLine++; - lastGeneratedColumn = 0; - // The remaining code is added without mapping - } else { - // There is no new line in between. - // Associate the code between "lastGeneratedColumn" and - // "mapping.generatedColumn" with "lastMapping" - var nextLine = remainingLines[remainingLinesIndex]; - var code = nextLine.substr(0, mapping.generatedColumn - - lastGeneratedColumn); - remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - - lastGeneratedColumn); - lastGeneratedColumn = mapping.generatedColumn; - addMappingWithCode(lastMapping, code); - // No more remaining code, continue - lastMapping = mapping; - return; - } - } - // We add the generated code until the first mapping - // to the SourceNode without any mapping. - // Each line is added as separate string. - while (lastGeneratedLine < mapping.generatedLine) { - node.add(shiftNextLine()); - lastGeneratedLine++; - } - if (lastGeneratedColumn < mapping.generatedColumn) { - var nextLine = remainingLines[remainingLinesIndex]; - node.add(nextLine.substr(0, mapping.generatedColumn)); - remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); - lastGeneratedColumn = mapping.generatedColumn; - } - lastMapping = mapping; - }, this); - // We have processed all mappings. - if (remainingLinesIndex < remainingLines.length) { - if (lastMapping) { - // Associate the remaining code in the current line with "lastMapping" - addMappingWithCode(lastMapping, shiftNextLine()); - } - // and add the remaining lines without any mapping - node.add(remainingLines.splice(remainingLinesIndex).join("")); - } +module.exports.has = has; - // Copy sourcesContent into SourceNode - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - if (aRelativePath != null) { - sourceFile = util.join(aRelativePath, sourceFile); - } - node.setSourceContent(sourceFile, content); - } - }); - return node; +/***/ }), +/* 732 */ +/***/ (function(module, exports, __webpack_require__) { - function addMappingWithCode(mapping, code) { - if (mapping === null || mapping.source === undefined) { - node.add(code); - } else { - var source = aRelativePath - ? util.join(aRelativePath, mapping.source) - : mapping.source; - node.add(new SourceNode(mapping.originalLine, - mapping.originalColumn, - source, - code, - mapping.name)); - } - } - }; +var isBuffer = __webpack_require__(680); +var toString = Object.prototype.toString; /** - * Add a chunk of generated JS to this source node. + * Get the native `typeof` a value. * - * @param aChunk A string snippet of generated JS code, another instance of - * SourceNode, or an array where each member is one of those things. + * @param {*} `val` + * @return {*} Native javascript type */ -SourceNode.prototype.add = function SourceNode_add(aChunk) { - if (Array.isArray(aChunk)) { - aChunk.forEach(function (chunk) { - this.add(chunk); - }, this); + +module.exports = function kindOf(val) { + // primitivies + if (typeof val === 'undefined') { + return 'undefined'; } - else if (aChunk[isSourceNode] || typeof aChunk === "string") { - if (aChunk) { - this.children.push(aChunk); - } + if (val === null) { + return 'null'; } - else { - throw new TypeError( - "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk - ); + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (typeof val === 'string' || val instanceof String) { + return 'string'; + } + if (typeof val === 'number' || val instanceof Number) { + return 'number'; } - return this; -}; -/** - * Add a chunk of generated JS to the beginning of this source node. - * - * @param aChunk A string snippet of generated JS code, another instance of - * SourceNode, or an array where each member is one of those things. - */ -SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { - if (Array.isArray(aChunk)) { - for (var i = aChunk.length-1; i >= 0; i--) { - this.prepend(aChunk[i]); - } + // functions + if (typeof val === 'function' || val instanceof Function) { + return 'function'; } - else if (aChunk[isSourceNode] || typeof aChunk === "string") { - this.children.unshift(aChunk); + + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; } - else { - throw new TypeError( - "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk - ); + + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; } - return this; -}; -/** - * Walk over the tree of JS snippets in this node and its children. The - * walking function is called once for each snippet of JS and is passed that - * snippet and the its original associated source's line/column location. - * - * @param aFn The traversal function. - */ -SourceNode.prototype.walk = function SourceNode_walk(aFn) { - var chunk; - for (var i = 0, len = this.children.length; i < len; i++) { - chunk = this.children[i]; - if (chunk[isSourceNode]) { - chunk.walk(aFn); - } - else { - if (chunk !== '') { - aFn(chunk, { source: this.source, - line: this.line, - column: this.column, - name: this.name }); - } - } + // other objects + var type = toString.call(val); + + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; } -}; -/** - * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between - * each of `this.children`. - * - * @param aSep The separator. - */ -SourceNode.prototype.join = function SourceNode_join(aSep) { - var newChildren; - var i; - var len = this.children.length; - if (len > 0) { - newChildren = []; - for (i = 0; i < len-1; i++) { - newChildren.push(this.children[i]); - newChildren.push(aSep); - } - newChildren.push(this.children[i]); - this.children = newChildren; + // buffer + if (isBuffer(val)) { + return 'buffer'; } - return this; -}; -/** - * Call String.prototype.replace on the very right-most source snippet. Useful - * for trimming whitespace from the end of a source node, etc. - * - * @param aPattern The pattern to replace. - * @param aReplacement The thing to replace the pattern with. - */ -SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { - var lastChild = this.children[this.children.length - 1]; - if (lastChild[isSourceNode]) { - lastChild.replaceRight(aPattern, aReplacement); + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; } - else if (typeof lastChild === 'string') { - this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + if (type === '[object WeakSet]') { + return 'weakset'; } - else { - this.children.push(''.replace(aPattern, aReplacement)); + if (type === '[object Map]') { + return 'map'; } - return this; + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; + } + + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } + + // must be a plain object + return 'object'; }; -/** - * Set the source content for a source file. This will be added to the SourceMapGenerator - * in the sourcesContent field. - * - * @param aSourceFile The filename of the source file - * @param aSourceContent The content of the source file - */ -SourceNode.prototype.setSourceContent = - function SourceNode_setSourceContent(aSourceFile, aSourceContent) { - this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; - }; -/** - * Walk over the tree of SourceNodes. The walking function is called for each - * source file content and is passed the filename and source content. +/***/ }), +/* 733 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * copy-descriptor * - * @param aFn The traversal function. + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. */ -SourceNode.prototype.walkSourceContents = - function SourceNode_walkSourceContents(aFn) { - for (var i = 0, len = this.children.length; i < len; i++) { - if (this.children[i][isSourceNode]) { - this.children[i].walkSourceContents(aFn); - } - } - var sources = Object.keys(this.sourceContents); - for (var i = 0, len = sources.length; i < len; i++) { - aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); - } - }; -/** - * Return the string representation of this source node. Walks over the tree - * and concatenates all the various snippets together to one string. - */ -SourceNode.prototype.toString = function SourceNode_toString() { - var str = ""; - this.walk(function (chunk) { - str += chunk; - }); - return str; -}; /** - * Returns the string representation of this source node along with a source - * map. + * Copy a descriptor from one object to another. + * + * ```js + * function App() { + * this.cache = {}; + * } + * App.prototype.set = function(key, val) { + * this.cache[key] = val; + * return this; + * }; + * Object.defineProperty(App.prototype, 'count', { + * get: function() { + * return Object.keys(this.cache).length; + * } + * }); + * + * copy(App.prototype, 'count', 'len'); + * + * // create an instance + * var app = new App(); + * + * app.set('a', true); + * app.set('b', true); + * app.set('c', true); + * + * console.log(app.count); + * //=> 3 + * console.log(app.len); + * //=> 3 + * ``` + * @name copy + * @param {Object} `receiver` The target object + * @param {Object} `provider` The provider object + * @param {String} `from` The key to copy on provider. + * @param {String} `to` Optionally specify a new key name to use. + * @return {Object} + * @api public */ -SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { - var generated = { - code: "", - line: 1, - column: 0 - }; - var map = new SourceMapGenerator(aArgs); - var sourceMappingActive = false; - var lastOriginalSource = null; - var lastOriginalLine = null; - var lastOriginalColumn = null; - var lastOriginalName = null; - this.walk(function (chunk, original) { - generated.code += chunk; - if (original.source !== null - && original.line !== null - && original.column !== null) { - if(lastOriginalSource !== original.source - || lastOriginalLine !== original.line - || lastOriginalColumn !== original.column - || lastOriginalName !== original.name) { - map.addMapping({ - source: original.source, - original: { - line: original.line, - column: original.column - }, - generated: { - line: generated.line, - column: generated.column - }, - name: original.name - }); - } - lastOriginalSource = original.source; - lastOriginalLine = original.line; - lastOriginalColumn = original.column; - lastOriginalName = original.name; - sourceMappingActive = true; - } else if (sourceMappingActive) { - map.addMapping({ - generated: { - line: generated.line, - column: generated.column - } - }); - lastOriginalSource = null; - sourceMappingActive = false; - } - for (var idx = 0, length = chunk.length; idx < length; idx++) { - if (chunk.charCodeAt(idx) === NEWLINE_CODE) { - generated.line++; - generated.column = 0; - // Mappings end at eol - if (idx + 1 === length) { - lastOriginalSource = null; - sourceMappingActive = false; - } else if (sourceMappingActive) { - map.addMapping({ - source: original.source, - original: { - line: original.line, - column: original.column - }, - generated: { - line: generated.line, - column: generated.column - }, - name: original.name - }); - } - } else { - generated.column++; - } - } - }); - this.walkSourceContents(function (sourceFile, sourceContent) { - map.setSourceContent(sourceFile, sourceContent); - }); - return { code: generated.code, map: map }; +module.exports = function copyDescriptor(receiver, provider, from, to) { + if (!isObject(provider) && typeof provider !== 'function') { + to = from; + from = provider; + provider = receiver; + } + if (!isObject(receiver) && typeof receiver !== 'function') { + throw new TypeError('expected the first argument to be an object'); + } + if (!isObject(provider) && typeof provider !== 'function') { + throw new TypeError('expected provider to be an object'); + } + + if (typeof to !== 'string') { + to = from; + } + if (typeof from !== 'string') { + throw new TypeError('expected key to be a string'); + } + + if (!(from in provider)) { + throw new Error('property "' + from + '" does not exist'); + } + + var val = Object.getOwnPropertyDescriptor(provider, from); + if (val) Object.defineProperty(receiver, to, val); }; -exports.SourceNode = SourceNode; +function isObject(val) { + return {}.toString.call(val) === '[object Object]'; +} + /***/ }), -/* 711 */ +/* 734 */ /***/ (function(module, exports, __webpack_require__) { -// Copyright 2014, 2015, 2016, 2017 Simon Lydell -// X11 (“MIT”) Licensed. (See LICENSE.) +"use strict"; -var sourceMappingURL = __webpack_require__(712) -var resolveUrl = __webpack_require__(713) -var decodeUriComponent = __webpack_require__(714) -var urix = __webpack_require__(716) -var atob = __webpack_require__(717) +var use = __webpack_require__(735); +var define = __webpack_require__(723); +var debug = __webpack_require__(326)('snapdragon:compiler'); +var utils = __webpack_require__(737); +/** + * Create a new `Compiler` with the given `options`. + * @param {Object} `options` + */ -function callbackAsync(callback, error, result) { - setImmediate(function() { callback(error, result) }) +function Compiler(options, state) { + debug('initializing', __filename); + this.options = utils.extend({source: 'string'}, options); + this.state = state || {}; + this.compilers = {}; + this.output = ''; + this.set('eos', function(node) { + return this.emit(node.val, node); + }); + this.set('noop', function(node) { + return this.emit(node.val, node); + }); + this.set('bos', function(node) { + return this.emit(node.val, node); + }); + use(this); } -function parseMapToJSON(string, data) { - try { - return JSON.parse(string.replace(/^\)\]\}'/, "")) - } catch (error) { - error.sourceMapData = data - throw error - } -} +/** + * Prototype methods + */ -function readSync(read, url, data) { - var readUrl = decodeUriComponent(url) - try { - return String(read(readUrl)) - } catch (error) { - error.sourceMapData = data - throw error - } -} +Compiler.prototype = { + /** + * Throw an error message with details including the cursor position. + * @param {String} `msg` Message to use in the Error. + */ + error: function(msg, node) { + var pos = node.position || {start: {column: 0}}; + var message = this.options.source + ' column:' + pos.start.column + ': ' + msg; -function resolveSourceMap(code, codeUrl, read, callback) { - var mapData - try { - mapData = resolveSourceMapHelper(code, codeUrl) - } catch (error) { - return callbackAsync(callback, error) - } - if (!mapData || mapData.map) { - return callbackAsync(callback, null, mapData) - } - var readUrl = decodeUriComponent(mapData.url) - read(readUrl, function(error, result) { - if (error) { - error.sourceMapData = mapData - return callback(error) - } - mapData.map = String(result) - try { - mapData.map = parseMapToJSON(mapData.map, mapData) - } catch (error) { - return callback(error) + var err = new Error(message); + err.reason = msg; + err.column = pos.start.column; + err.source = this.pattern; + + if (this.options.silent) { + this.errors.push(err); + } else { + throw err; } - callback(null, mapData) - }) -} + }, -function resolveSourceMapSync(code, codeUrl, read) { - var mapData = resolveSourceMapHelper(code, codeUrl) - if (!mapData || mapData.map) { - return mapData - } - mapData.map = readSync(read, mapData.url, mapData) - mapData.map = parseMapToJSON(mapData.map, mapData) - return mapData -} + /** + * Define a non-enumberable property on the `Compiler` instance. + * + * ```js + * compiler.define('foo', 'bar'); + * ``` + * @name .define + * @param {String} `key` propery name + * @param {any} `val` property value + * @return {Object} Returns the Compiler instance for chaining. + * @api public + */ -var dataUriRegex = /^data:([^,;]*)(;[^,;]*)*(?:,(.*))?$/ -var jsonMimeTypeRegex = /^(?:application|text)\/json$/ + define: function(key, val) { + define(this, key, val); + return this; + }, -function resolveSourceMapHelper(code, codeUrl) { - codeUrl = urix(codeUrl) + /** + * Emit `node.val` + */ - var url = sourceMappingURL.getFrom(code) - if (!url) { - return null - } + emit: function(str, node) { + this.output += str; + return str; + }, - var dataUri = url.match(dataUriRegex) - if (dataUri) { - var mimeType = dataUri[1] - var lastParameter = dataUri[2] || "" - var encoded = dataUri[3] || "" - var data = { - sourceMappingURL: url, - url: null, - sourcesRelativeTo: codeUrl, - map: encoded - } - if (!jsonMimeTypeRegex.test(mimeType)) { - var error = new Error("Unuseful data uri mime type: " + (mimeType || "text/plain")) - error.sourceMapData = data - throw error - } - data.map = parseMapToJSON( - lastParameter === ";base64" ? atob(encoded) : decodeURIComponent(encoded), - data - ) - return data - } + /** + * Add a compiler `fn` with the given `name` + */ - var mapUrl = resolveUrl(codeUrl, url) - return { - sourceMappingURL: url, - url: mapUrl, - sourcesRelativeTo: mapUrl, - map: null - } -} + set: function(name, fn) { + this.compilers[name] = fn; + return this; + }, + /** + * Get compiler `name`. + */ + get: function(name) { + return this.compilers[name]; + }, -function resolveSources(map, mapUrl, read, options, callback) { - if (typeof options === "function") { - callback = options - options = {} - } - var pending = map.sources ? map.sources.length : 0 - var result = { - sourcesResolved: [], - sourcesContent: [] - } + /** + * Get the previous AST node. + */ - if (pending === 0) { - callbackAsync(callback, null, result) - return - } + prev: function(n) { + return this.ast.nodes[this.idx - (n || 1)] || { type: 'bos', val: '' }; + }, - var done = function() { - pending-- - if (pending === 0) { - callback(null, result) - } - } + /** + * Get the next AST node. + */ - resolveSourcesHelper(map, mapUrl, options, function(fullUrl, sourceContent, index) { - result.sourcesResolved[index] = fullUrl - if (typeof sourceContent === "string") { - result.sourcesContent[index] = sourceContent - callbackAsync(done, null) - } else { - var readUrl = decodeUriComponent(fullUrl) - read(readUrl, function(error, source) { - result.sourcesContent[index] = error ? error : String(source) - done() - }) - } - }) -} + next: function(n) { + return this.ast.nodes[this.idx + (n || 1)] || { type: 'eos', val: '' }; + }, -function resolveSourcesSync(map, mapUrl, read, options) { - var result = { - sourcesResolved: [], - sourcesContent: [] - } + /** + * Visit `node`. + */ - if (!map.sources || map.sources.length === 0) { - return result - } + visit: function(node, nodes, i) { + var fn = this.compilers[node.type]; + this.idx = i; - resolveSourcesHelper(map, mapUrl, options, function(fullUrl, sourceContent, index) { - result.sourcesResolved[index] = fullUrl - if (read !== null) { - if (typeof sourceContent === "string") { - result.sourcesContent[index] = sourceContent - } else { - var readUrl = decodeUriComponent(fullUrl) - try { - result.sourcesContent[index] = String(read(readUrl)) - } catch (error) { - result.sourcesContent[index] = error - } - } + if (typeof fn !== 'function') { + throw this.error('compiler "' + node.type + '" is not registered', node); } - }) - - return result -} + return fn.call(this, node, nodes, i); + }, -var endingSlash = /\/?$/ + /** + * Map visit over array of `nodes`. + */ -function resolveSourcesHelper(map, mapUrl, options, fn) { - options = options || {} - mapUrl = urix(mapUrl) - var fullUrl - var sourceContent - var sourceRoot - for (var index = 0, len = map.sources.length; index < len; index++) { - sourceRoot = null - if (typeof options.sourceRoot === "string") { - sourceRoot = options.sourceRoot - } else if (typeof map.sourceRoot === "string" && options.sourceRoot !== false) { - sourceRoot = map.sourceRoot + mapVisit: function(nodes) { + if (!Array.isArray(nodes)) { + throw new TypeError('expected an array'); } - // If the sourceRoot is the empty string, it is equivalent to not setting - // the property at all. - if (sourceRoot === null || sourceRoot === '') { - fullUrl = resolveUrl(mapUrl, map.sources[index]) - } else { - // Make sure that the sourceRoot ends with a slash, so that `/scripts/subdir` becomes - // `/scripts/subdir/`, not `/scripts/`. Pointing to a file as source root - // does not make sense. - fullUrl = resolveUrl(mapUrl, sourceRoot.replace(endingSlash, "/"), map.sources[index]) + var len = nodes.length; + var idx = -1; + while (++idx < len) { + this.visit(nodes[idx], nodes, idx); } - sourceContent = (map.sourcesContent || [])[index] - fn(fullUrl, sourceContent, index) + return this; + }, + + /** + * Compile `ast`. + */ + + compile: function(ast, options) { + var opts = utils.extend({}, this.options, options); + this.ast = ast; + this.parsingErrors = this.ast.errors; + this.output = ''; + + // source map support + if (opts.sourcemap) { + var sourcemaps = __webpack_require__(756); + sourcemaps(this); + this.mapVisit(this.ast.nodes); + this.applySourceMaps(); + this.map = opts.sourcemap === 'generator' ? this.map : this.map.toJSON(); + return this; + } + + this.mapVisit(this.ast.nodes); + return this; } -} +}; +/** + * Expose `Compiler` + */ +module.exports = Compiler; -function resolve(code, codeUrl, read, options, callback) { - if (typeof options === "function") { - callback = options - options = {} + +/***/ }), +/* 735 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * use + * + * Copyright (c) 2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var utils = __webpack_require__(736); + +module.exports = function base(app, opts) { + if (!utils.isObject(app) && typeof app !== 'function') { + throw new TypeError('use: expect `app` be an object or function'); } - if (code === null) { - var mapUrl = codeUrl - var data = { - sourceMappingURL: null, - url: mapUrl, - sourcesRelativeTo: mapUrl, - map: null - } - var readUrl = decodeUriComponent(mapUrl) - read(readUrl, function(error, result) { - if (error) { - error.sourceMapData = data - return callback(error) - } - data.map = String(result) - try { - data.map = parseMapToJSON(data.map, data) - } catch (error) { - return callback(error) - } - _resolveSources(data) - }) - } else { - resolveSourceMap(code, codeUrl, read, function(error, mapData) { - if (error) { - return callback(error) - } - if (!mapData) { - return callback(null, null) - } - _resolveSources(mapData) - }) + + if (!utils.isObject(opts)) { + opts = {}; } - function _resolveSources(mapData) { - resolveSources(mapData.map, mapData.sourcesRelativeTo, read, options, function(error, result) { - if (error) { - return callback(error) - } - mapData.sourcesResolved = result.sourcesResolved - mapData.sourcesContent = result.sourcesContent - callback(null, mapData) - }) + var prop = utils.isString(opts.prop) ? opts.prop : 'fns'; + if (!Array.isArray(app[prop])) { + utils.define(app, prop, []); } -} -function resolveSync(code, codeUrl, read, options) { - var mapData - if (code === null) { - var mapUrl = codeUrl - mapData = { - sourceMappingURL: null, - url: mapUrl, - sourcesRelativeTo: mapUrl, - map: null + /** + * Define a plugin function to be passed to use. The only + * parameter exposed to the plugin is `app`, the object or function. + * passed to `use(app)`. `app` is also exposed as `this` in plugins. + * + * Additionally, **if a plugin returns a function, the function will + * be pushed onto the `fns` array**, allowing the plugin to be + * called at a later point by the `run` method. + * + * ```js + * var use = require('use'); + * + * // define a plugin + * function foo(app) { + * // do stuff + * } + * + * var app = function(){}; + * use(app); + * + * // register plugins + * app.use(foo); + * app.use(bar); + * app.use(baz); + * ``` + * @name .use + * @param {Function} `fn` plugin function to call + * @api public + */ + + utils.define(app, 'use', use); + + /** + * Run all plugins on `fns`. Any plugin that returns a function + * when called by `use` is pushed onto the `fns` array. + * + * ```js + * var config = {}; + * app.run(config); + * ``` + * @name .run + * @param {Object} `value` Object to be modified by plugins. + * @return {Object} Returns the object passed to `run` + * @api public + */ + + utils.define(app, 'run', function(val) { + if (!utils.isObject(val)) return; + decorate(val); + + var self = this || app; + var fns = self[prop]; + var len = fns.length; + var idx = -1; + + while (++idx < len) { + val.use(fns[idx]); } - mapData.map = readSync(read, mapUrl, mapData) - mapData.map = parseMapToJSON(mapData.map, mapData) - } else { - mapData = resolveSourceMapSync(code, codeUrl, read) - if (!mapData) { - return null + return val; + }); + + /** + * Call plugin `fn`. If a function is returned push it into the + * `fns` array to be called by the `run` method. + */ + + function use(fn, options) { + if (typeof fn !== 'function') { + throw new TypeError('.use expects `fn` be a function'); + } + + var self = this || app; + if (typeof opts.fn === 'function') { + opts.fn.call(self, self, options); + } + + var plugin = fn.call(self, self); + if (typeof plugin === 'function') { + var fns = self[prop]; + fns.push(plugin); } + return self; } - var result = resolveSourcesSync(mapData.map, mapData.sourcesRelativeTo, read, options) - mapData.sourcesResolved = result.sourcesResolved - mapData.sourcesContent = result.sourcesContent - return mapData -} + /** + * Ensure the `.use` method exists on `val` + */ + function decorate(val) { + if (!val.use || !val.run) { + base(val); + } + } -module.exports = { - resolveSourceMap: resolveSourceMap, - resolveSourceMapSync: resolveSourceMapSync, - resolveSources: resolveSources, - resolveSourcesSync: resolveSourcesSync, - resolve: resolve, - resolveSync: resolveSync, - parseMapToJSON: parseMapToJSON -} + return app; +}; /***/ }), -/* 712 */ +/* 736 */ /***/ (function(module, exports, __webpack_require__) { -var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;// Copyright 2014 Simon Lydell -// X11 (“MIT”) Licensed. (See LICENSE.) +"use strict"; -void (function(root, factory) { - if (true) { - !(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : - __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) - } else {} -}(this, function() { - var innerRegex = /[#@] sourceMappingURL=([^\s'"]*)/ +var utils = {}; - var regex = RegExp( - "(?:" + - "/\\*" + - "(?:\\s*\r?\n(?://)?)?" + - "(?:" + innerRegex.source + ")" + - "\\s*" + - "\\*/" + - "|" + - "//(?:" + innerRegex.source + ")" + - ")" + - "\\s*" - ) - return { - regex: regex, - _innerRegex: innerRegex, +/** + * Lazily required module dependencies + */ - getFrom: function(code) { - var match = code.match(regex) - return (match ? match[1] || match[2] || "" : null) - }, +utils.define = __webpack_require__(723); +utils.isObject = __webpack_require__(656); - existsIn: function(code) { - return regex.test(code) - }, - removeFrom: function(code) { - return code.replace(regex, "") - }, +utils.isString = function(val) { + return val && typeof val === 'string'; +}; - insertBefore: function(code, string) { - var match = code.match(regex) - if (match) { - return code.slice(0, match.index) + string + code.slice(match.index) - } else { - return code + string - } - } - } +/** + * Expose `utils` modules + */ -})); +module.exports = utils; /***/ }), -/* 713 */ +/* 737 */ /***/ (function(module, exports, __webpack_require__) { -// Copyright 2014 Simon Lydell -// X11 (“MIT”) Licensed. (See LICENSE.) +"use strict"; -var url = __webpack_require__(324) -function resolveUrl(/* ...urls */) { - return Array.prototype.reduce.call(arguments, function(resolved, nextUrl) { - return url.resolve(resolved, nextUrl) - }) -} +/** + * Module dependencies + */ -module.exports = resolveUrl +exports.extend = __webpack_require__(707); +exports.SourceMap = __webpack_require__(738); +exports.sourceMapResolve = __webpack_require__(749); + +/** + * Convert backslash in the given string to forward slashes + */ + +exports.unixify = function(fp) { + return fp.split(/\\+/).join('/'); +}; + +/** + * Return true if `val` is a non-empty string + * + * @param {String} `str` + * @return {Boolean} + */ + +exports.isString = function(str) { + return str && typeof str === 'string'; +}; + +/** + * Cast `val` to an array + * @return {Array} + */ + +exports.arrayify = function(val) { + if (typeof val === 'string') return [val]; + return val ? (Array.isArray(val) ? val : [val]) : []; +}; + +/** + * Get the last `n` element from the given `array` + * @param {Array} `array` + * @return {*} + */ + +exports.last = function(arr, n) { + return arr[arr.length - (n || 1)]; +}; /***/ }), -/* 714 */ +/* 738 */ /***/ (function(module, exports, __webpack_require__) { -// Copyright 2017 Simon Lydell -// X11 (“MIT”) Licensed. (See LICENSE.) +/* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ +exports.SourceMapGenerator = __webpack_require__(739).SourceMapGenerator; +exports.SourceMapConsumer = __webpack_require__(745).SourceMapConsumer; +exports.SourceNode = __webpack_require__(748).SourceNode; -var decodeUriComponent = __webpack_require__(715) -function customDecodeUriComponent(string) { - // `decodeUriComponent` turns `+` into ` `, but that's not wanted. - return decodeUriComponent(string.replace(/\+/g, "%2B")) +/***/ }), +/* 739 */ +/***/ (function(module, exports, __webpack_require__) { + +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var base64VLQ = __webpack_require__(740); +var util = __webpack_require__(742); +var ArraySet = __webpack_require__(743).ArraySet; +var MappingList = __webpack_require__(744).MappingList; + +/** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ +function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; } -module.exports = customDecodeUriComponent +SourceMapGenerator.prototype._version = 3; +/** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ +SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; -/***/ }), -/* 715 */ -/***/ (function(module, exports, __webpack_require__) { + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } -"use strict"; + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; -var token = '%[a-f0-9]{2}'; -var singleMatcher = new RegExp(token, 'gi'); -var multiMatcher = new RegExp('(' + token + ')+', 'gi'); + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } -function decodeComponents(components, split) { - try { - // Try to decode the entire string first - return decodeURIComponent(components.join('')); - } catch (err) { - // Do nothing - } + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; - if (components.length === 1) { - return components; - } +/** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ +SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); - split = split || 1; + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } - // Split the array in 2 parts - var left = components.slice(0, split); - var right = components.slice(split); + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } - return Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right)); -} + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } -function decode(input) { - try { - return decodeURIComponent(input); - } catch (err) { - var tokens = input.match(singleMatcher); + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; - for (var i = 1; i < tokens.length; i++) { - input = decodeComponents(tokens, i).join(''); +/** + * Set the source content for a source file. + */ +SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } - tokens = input.match(singleMatcher); - } + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; - return input; - } -} +/** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ +SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); -function customDecodeURIComponent(input) { - // Keep track of all the replacements and prefill the map with the `BOM` - var replaceMap = { - '%FE%FF': '\uFFFD\uFFFD', - '%FF%FE': '\uFFFD\uFFFD' - }; + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } - var match = multiMatcher.exec(input); - while (match) { - try { - // Decode as big chunks as possible - replaceMap[match[0]] = decodeURIComponent(match[0]); - } catch (err) { - var result = decode(match[0]); + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } - if (result !== match[0]) { - replaceMap[match[0]] = result; - } - } + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + +/** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ +SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { + throw new Error( + 'original.line and original.column are not numbers -- you probably meant to omit ' + + 'the original mapping entirely and only map the generated position. If so, pass ' + + 'null for the original mapping instead of an object with empty or null values.' + ); + } + + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + +/** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ +SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = '' + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } + + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; - match = multiMatcher.exec(input); - } + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; - // Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else - replaceMap['%C2'] = '\uFFFD'; + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; - var entries = Object.keys(replaceMap); + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; - for (var i = 0; i < entries.length; i++) { - // Replace all decoded components - var key = entries[i]; - input = input.replace(new RegExp(key, 'g'), replaceMap[key]); - } + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } - return input; -} + result += next; + } -module.exports = function (encodedURI) { - if (typeof encodedURI !== 'string') { - throw new TypeError('Expected `encodedURI` to be of type `string`, got `' + typeof encodedURI + '`'); - } + return result; + }; - try { - encodedURI = encodedURI.replace(/\+/g, ' '); +SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; - // Try the built in decoder first - return decodeURIComponent(encodedURI); - } catch (err) { - // Fallback to a more advanced decoder - return customDecodeURIComponent(encodedURI); - } -}; +/** + * Externalize the source map. + */ +SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + return map; + }; -/***/ }), -/* 716 */ -/***/ (function(module, exports, __webpack_require__) { +/** + * Render the source map being generated to a string. + */ +SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; -// Copyright 2014 Simon Lydell -// X11 (“MIT”) Licensed. (See LICENSE.) - -var path = __webpack_require__(4) - -"use strict" - -function urix(aPath) { - if (path.sep === "\\") { - return aPath - .replace(/\\/g, "/") - .replace(/^[a-z]:\/?/i, "/") - } - return aPath -} - -module.exports = urix +exports.SourceMapGenerator = SourceMapGenerator; /***/ }), -/* 717 */ +/* 740 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; - - -function atob(str) { - return Buffer.from(str, 'base64').toString('binary'); -} +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ -module.exports = atob.atob = atob; +var base64 = __webpack_require__(741); +// A single base 64 digit can contain 6 bits of data. For the base 64 variable +// length quantities we use in the source map spec, the first bit is the sign, +// the next four bits are the actual value, and the 6th bit is the +// continuation bit. The continuation bit tells us whether there are more +// digits in this value following this digit. +// +// Continuation +// | Sign +// | | +// V V +// 101011 -/***/ }), -/* 718 */ -/***/ (function(module, exports, __webpack_require__) { +var VLQ_BASE_SHIFT = 5; -"use strict"; +// binary: 100000 +var VLQ_BASE = 1 << VLQ_BASE_SHIFT; +// binary: 011111 +var VLQ_BASE_MASK = VLQ_BASE - 1; -var fs = __webpack_require__(253); -var path = __webpack_require__(4); -var define = __webpack_require__(685); -var utils = __webpack_require__(699); +// binary: 100000 +var VLQ_CONTINUATION_BIT = VLQ_BASE; /** - * Expose `mixin()`. - * This code is based on `source-maps-support.js` in reworkcss/css - * https://github.com/reworkcss/css/blob/master/lib/stringify/source-map-support.js - * Copyright (c) 2012 TJ Holowaychuk + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) */ - -module.exports = mixin; +function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; +} /** - * Mixin source map support into `compiler`. - * - * @param {Object} `compiler` - * @api public + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 */ - -function mixin(compiler) { - define(compiler, '_comment', compiler.comment); - compiler.map = new utils.SourceMap.SourceMapGenerator(); - compiler.position = { line: 1, column: 1 }; - compiler.content = {}; - compiler.files = {}; - - for (var key in exports) { - define(compiler, key, exports[key]); - } +function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; } /** - * Update position. - * - * @param {String} str + * Returns the base 64 VLQ encoded value. */ +exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; -exports.updatePosition = function(str) { - var lines = str.match(/\n/g); - if (lines) this.position.line += lines.length; - var i = str.lastIndexOf('\n'); - this.position.column = ~i ? str.length - i : this.position.column + str.length; + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; }; /** - * Emit `str` with `position`. - * - * @param {String} str - * @param {Object} [pos] - * @return {String} + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. */ +exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; -exports.emit = function(str, node) { - var position = node.position || {}; - var source = position.source; - if (source) { - if (position.filepath) { - source = utils.unixify(position.filepath); + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); } - this.map.addMapping({ - source: source, - generated: { - line: this.position.line, - column: Math.max(this.position.column - 1, 0) - }, - original: { - line: position.start.line, - column: position.start.column - 1 - } - }); - - if (position.content) { - this.addContent(source, position); - } - if (position.filepath) { - this.addFile(source, position); + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); } - this.updatePosition(str); - this.output += str; - } - return str; + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; }; -/** - * Adds a file to the source map output if it has not already been added - * @param {String} `file` - * @param {Object} `pos` + +/***/ }), +/* 741 */ +/***/ (function(module, exports) { + +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause */ -exports.addFile = function(file, position) { - if (typeof position.content !== 'string') return; - if (Object.prototype.hasOwnProperty.call(this.files, file)) return; - this.files[file] = position.content; -}; +var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); /** - * Adds a content source to the source map output if it has not already been added - * @param {String} `source` - * @param {Object} `position` + * Encode an integer in the range of 0 to 63 to a single base 64 digit. */ - -exports.addContent = function(source, position) { - if (typeof position.content !== 'string') return; - if (Object.prototype.hasOwnProperty.call(this.content, source)) return; - this.map.setSourceContent(source, position.content); +exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); }; /** - * Applies any original source maps to the output and embeds the source file - * contents in the source map. + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. */ +exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' -exports.applySourceMaps = function() { - Object.keys(this.files).forEach(function(file) { - var content = this.files[file]; - this.map.setSourceContent(file, content); + var littleA = 97; // 'a' + var littleZ = 122; // 'z' - if (this.options.inputSourcemaps === true) { - var originalMap = utils.sourceMapResolve.resolveSync(content, file, fs.readFileSync); - if (originalMap) { - var map = new utils.SourceMap.SourceMapConsumer(originalMap.map); - var relativeTo = originalMap.sourcesRelativeTo; - this.map.applySourceMap(map, file, utils.unixify(path.dirname(relativeTo))); - } - } - }, this); -}; + var zero = 48; // '0' + var nine = 57; // '9' -/** - * Process comments, drops sourceMap comments. - * @param {Object} node - */ + var plus = 43; // '+' + var slash = 47; // '/' -exports.comment = function(node) { - if (/^# sourceMappingURL=/.test(node.comment)) { - return this.emit('', node.position); + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); } - return this._comment(node); + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; }; /***/ }), -/* 719 */ -/***/ (function(module, exports, __webpack_require__) { +/* 742 */ +/***/ (function(module, exports) { -"use strict"; +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +/** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ +function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } +} +exports.getArg = getArg; +var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/; +var dataUrlRegexp = /^data:.+\,.+$/; -var use = __webpack_require__(697); -var util = __webpack_require__(234); -var Cache = __webpack_require__(720); -var define = __webpack_require__(685); -var debug = __webpack_require__(326)('snapdragon:parser'); -var Position = __webpack_require__(721); -var utils = __webpack_require__(699); +function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; +} +exports.urlParse = urlParse; + +function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; +} +exports.urlGenerate = urlGenerate; /** - * Create a new `Parser` with the given `input` and `options`. - * @param {String} `input` - * @param {Object} `options` - * @api public + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. */ +function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); -function Parser(options) { - debug('initializing', __filename); - this.options = utils.extend({source: 'string'}, options); - this.init(this.options); - use(this); + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; } +exports.normalize = normalize; /** - * Prototype methods + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. */ +function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } -Parser.prototype = { - constructor: Parser, - - init: function(options) { - this.orig = ''; - this.input = ''; - this.parsed = ''; - - this.column = 1; - this.line = 1; - - this.regex = new Cache(); - this.errors = this.errors || []; - this.parsers = this.parsers || {}; - this.types = this.types || []; - this.sets = this.sets || {}; - this.fns = this.fns || []; - this.currentType = 'root'; + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } - var pos = this.position(); - this.bos = pos({type: 'bos', val: ''}); + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } - this.ast = { - type: 'root', - errors: this.errors, - nodes: [this.bos] - }; + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } - define(this.bos, 'parent', this.ast); - this.nodes = [this.ast]; + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); - this.count = 0; - this.setCount = 0; - this.stack = []; - }, + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; +} +exports.join = join; - /** - * Throw a formatted error with the cursor column and `msg`. - * @param {String} `msg` Message to use in the Error. - */ +exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp); +}; - error: function(msg, node) { - var pos = node.position || {start: {column: 0, line: 0}}; - var line = pos.start.line; - var column = pos.start.column; - var source = this.options.source; +/** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ +function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } - var message = source + ' : ' + msg; - var err = new Error(message); - err.source = source; - err.reason = msg; - err.pos = pos; + aRoot = aRoot.replace(/\/$/, ''); - if (this.options.silent) { - this.errors.push(err); - } else { - throw err; + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; } - }, - - /** - * Define a non-enumberable property on the `Parser` instance. - * - * ```js - * parser.define('foo', 'bar'); - * ``` - * @name .define - * @param {String} `key` propery name - * @param {any} `val` property value - * @return {Object} Returns the Parser instance for chaining. - * @api public - */ - - define: function(key, val) { - define(this, key, val); - return this; - }, - - /** - * Mark position and patch `node.position`. - */ - - position: function() { - var start = { line: this.line, column: this.column }; - var self = this; - - return function(node) { - define(node, 'position', new Position(start, self)); - return node; - }; - }, - /** - * Set parser `name` with the given `fn` - * @param {String} `name` - * @param {Function} `fn` - * @api public - */ - - set: function(type, fn) { - if (this.types.indexOf(type) === -1) { - this.types.push(type); + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; } - this.parsers[type] = fn.bind(this); - return this; - }, - - /** - * Get parser `name` - * @param {String} `name` - * @api public - */ - - get: function(name) { - return this.parsers[name]; - }, - - /** - * Push a `token` onto the `type` stack. - * - * @param {String} `type` - * @return {Object} `token` - * @api public - */ - - push: function(type, token) { - this.sets[type] = this.sets[type] || []; - this.count++; - this.stack.push(token); - return this.sets[type].push(token); - }, - - /** - * Pop a token off of the `type` stack - * @param {String} `type` - * @returns {Object} Returns a token - * @api public - */ - pop: function(type) { - this.sets[type] = this.sets[type] || []; - this.count--; - this.stack.pop(); - return this.sets[type].pop(); - }, + ++level; + } - /** - * Return true if inside a `stack` node. Types are `braces`, `parens` or `brackets`. - * - * @param {String} `type` - * @return {Boolean} - * @api public - */ + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); +} +exports.relative = relative; - isInside: function(type) { - this.sets[type] = this.sets[type] || []; - return this.sets[type].length > 0; - }, +var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); +}()); - /** - * Return true if `node` is the given `type`. - * - * ```js - * parser.isType(node, 'brace'); - * ``` - * @param {Object} `node` - * @param {String} `type` - * @return {Boolean} - * @api public - */ +function identity (s) { + return s; +} - isType: function(node, type) { - return node && node.type === type; - }, +/** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ +function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } - /** - * Get the previous AST node - * @return {Object} - */ + return aStr; +} +exports.toSetString = supportsNullProto ? identity : toSetString; - prev: function(n) { - return this.stack.length > 0 - ? utils.last(this.stack, n) - : utils.last(this.nodes, n); - }, +function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } - /** - * Update line and column based on `str`. - */ + return aStr; +} +exports.fromSetString = supportsNullProto ? identity : fromSetString; - consume: function(len) { - this.input = this.input.substr(len); - }, +function isProtoString(s) { + if (!s) { + return false; + } - /** - * Update column based on `str`. - */ + var length = s.length; - updatePosition: function(str, len) { - var lines = str.match(/\n/g); - if (lines) this.line += lines.length; - var i = str.lastIndexOf('\n'); - this.column = ~i ? len - i : this.column + len; - this.parsed += str; - this.consume(len); - }, + if (length < 9 /* "__proto__".length */) { + return false; + } - /** - * Match `regex`, return captures, and update the cursor position by `match[0]` length. - * @param {RegExp} `regex` - * @return {Object} - */ + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } - match: function(regex) { - var m = regex.exec(this.input); - if (m) { - this.updatePosition(m[0], m[0].length); - return m; + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; } - }, + } - /** - * Capture `type` with the given regex. - * @param {String} `type` - * @param {RegExp} `regex` - * @return {Function} - */ + return true; +} - capture: function(type, regex) { - if (typeof regex === 'function') { - return this.set.apply(this, arguments); - } +/** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ +function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = mappingA.source - mappingB.source; + if (cmp !== 0) { + return cmp; + } - this.regex.set(type, regex); - this.set(type, function() { - var parsed = this.parsed; - var pos = this.position(); - var m = this.match(regex); - if (!m || !m[0]) return; + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } - var prev = this.prev(); - var node = pos({ - type: type, - val: m[0], - parsed: parsed, - rest: this.input - }); + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } - if (m[1]) { - node.inner = m[1]; - } + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } - define(node, 'inside', this.stack.length > 0); - define(node, 'parent', prev); - prev.nodes.push(node); - }.bind(this)); - return this; - }, + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } - /** - * Create a parser with open and close for parens, - * brackets or braces - */ + return mappingA.name - mappingB.name; +} +exports.compareByOriginalPositions = compareByOriginalPositions; - capturePair: function(type, openRegex, closeRegex, fn) { - this.sets[type] = this.sets[type] || []; +/** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ +function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } - /** - * Open - */ + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } - this.set(type + '.open', function() { - var parsed = this.parsed; - var pos = this.position(); - var m = this.match(openRegex); - if (!m || !m[0]) return; + cmp = mappingA.source - mappingB.source; + if (cmp !== 0) { + return cmp; + } - var val = m[0]; - this.setCount++; - this.specialChars = true; - var open = pos({ - type: type + '.open', - val: val, - rest: this.input - }); + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } - if (typeof m[1] !== 'undefined') { - open.inner = m[1]; - } + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } - var prev = this.prev(); - var node = pos({ - type: type, - nodes: [open] - }); + return mappingA.name - mappingB.name; +} +exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; - define(node, 'rest', this.input); - define(node, 'parsed', parsed); - define(node, 'prefix', m[1]); - define(node, 'parent', prev); - define(open, 'parent', node); +function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } - if (typeof fn === 'function') { - fn.call(this, open, node); - } + if (aStr1 > aStr2) { + return 1; + } - this.push(type, node); - prev.nodes.push(node); - }); + return -1; +} - /** - * Close - */ +/** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ +function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } - this.set(type + '.close', function() { - var pos = this.position(); - var m = this.match(closeRegex); - if (!m || !m[0]) return; + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } - var parent = this.pop(type); - var node = pos({ - type: type + '.close', - rest: this.input, - suffix: m[1], - val: m[0] - }); + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } - if (!this.isType(parent, type)) { - if (this.options.strict) { - throw new Error('missing opening "' + type + '"'); - } + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } - this.setCount--; - node.escaped = true; - return node; - } + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } - if (node.suffix === '\\') { - parent.escaped = true; - node.escaped = true; - } + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; - parent.nodes.push(node); - define(node, 'parent', parent); - }); - return this; - }, +/***/ }), +/* 743 */ +/***/ (function(module, exports, __webpack_require__) { - /** - * Capture end-of-string - */ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ - eos: function() { - var pos = this.position(); - if (this.input) return; - var prev = this.prev(); +var util = __webpack_require__(742); +var has = Object.prototype.hasOwnProperty; +var hasNativeMap = typeof Map !== "undefined"; - while (prev.type !== 'root' && !prev.visited) { - if (this.options.strict === true) { - throw new SyntaxError('invalid syntax:' + util.inspect(prev, null, 2)); - } +/** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ +function ArraySet() { + this._array = []; + this._set = hasNativeMap ? new Map() : Object.create(null); +} - if (!hasDelims(prev)) { - prev.parent.escaped = true; - prev.escaped = true; - } +/** + * Static method for creating ArraySet instances from an existing array. + */ +ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; +}; - visit(prev, function(node) { - if (!hasDelims(node.parent)) { - node.parent.escaped = true; - node.escaped = true; - } - }); +/** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ +ArraySet.prototype.size = function ArraySet_size() { + return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; +}; - prev = prev.parent; +/** + * Add the given string to this set. + * + * @param String aStr + */ +ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = hasNativeMap ? aStr : util.toSetString(aStr); + var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + if (hasNativeMap) { + this._set.set(aStr, idx); + } else { + this._set[sStr] = idx; } + } +}; - var tok = pos({ - type: 'eos', - val: this.append || '' - }); - - define(tok, 'parent', this.ast); - return tok; - }, +/** + * Is the given string a member of this set? + * + * @param String aStr + */ +ArraySet.prototype.has = function ArraySet_has(aStr) { + if (hasNativeMap) { + return this._set.has(aStr); + } else { + var sStr = util.toSetString(aStr); + return has.call(this._set, sStr); + } +}; - /** - * Run parsers to advance the cursor position - */ +/** + * What is the index of the given string in the array? + * + * @param String aStr + */ +ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (hasNativeMap) { + var idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + } else { + var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } + } - next: function() { - var parsed = this.parsed; - var len = this.types.length; - var idx = -1; - var tok; + throw new Error('"' + aStr + '" is not in the set.'); +}; - while (++idx < len) { - if ((tok = this.parsers[this.types[idx]].call(this))) { - define(tok, 'rest', this.input); - define(tok, 'parsed', parsed); - this.last = tok; - return tok; - } - } - }, +/** + * What is the element at the given index? + * + * @param Number aIdx + */ +ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); +}; - /** - * Parse the given string. - * @return {Array} - */ +/** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ +ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); +}; - parse: function(input) { - if (typeof input !== 'string') { - throw new TypeError('expected a string'); - } +exports.ArraySet = ArraySet; - this.init(this.options); - this.orig = input; - this.input = input; - var self = this; - function parse() { - // check input before calling `.next()` - input = self.input; +/***/ }), +/* 744 */ +/***/ (function(module, exports, __webpack_require__) { - // get the next AST ndoe - var node = self.next(); - if (node) { - var prev = self.prev(); - if (prev) { - define(node, 'parent', prev); - if (prev.nodes) { - prev.nodes.push(node); - } - } +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ - if (self.sets.hasOwnProperty(prev.type)) { - self.currentType = prev.type; - } - } +var util = __webpack_require__(742); - // if we got here but input is not changed, throw an error - if (self.input && input === self.input) { - throw new Error('no parsers registered for: "' + self.input.slice(0, 5) + '"'); - } - } +/** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ +function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; +} - while (this.input) parse(); - if (this.stack.length && this.options.strict) { - var node = this.stack.pop(); - throw this.error('missing opening ' + node.type + ': "' + this.orig + '"'); - } +/** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ +function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; +} - var eos = this.eos(); - var tok = this.prev(); - if (tok.type !== 'eos') { - this.ast.nodes.push(eos); - } +/** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ +MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; - return this.ast; +/** + * Add the given source mapping. + * + * @param Object aMapping + */ +MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); } }; /** - * Visit `node` with the given `fn` + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ +MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; +}; + +exports.MappingList = MappingList; + + +/***/ }), +/* 745 */ +/***/ (function(module, exports, __webpack_require__) { + +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause */ -function visit(node, fn) { - if (!node.visited) { - define(node, 'visited', true); - return node.nodes ? mapVisit(node.nodes, fn) : fn(node); +var util = __webpack_require__(742); +var binarySearch = __webpack_require__(746); +var ArraySet = __webpack_require__(743).ArraySet; +var base64VLQ = __webpack_require__(740); +var quickSort = __webpack_require__(747).quickSort; + +function SourceMapConsumer(aSourceMap) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); } - return node; + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap) + : new BasicSourceMapConsumer(sourceMap); +} + +SourceMapConsumer.fromSourceMap = function(aSourceMap) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap); } /** - * Map visit over array of `nodes`. + * The version of the source mapping spec that we are consuming. */ +SourceMapConsumer.prototype._version = 3; -function mapVisit(nodes, fn) { - var len = nodes.length; - var idx = -1; - while (++idx < len) { - visit(nodes[idx], fn); +// `__generatedMappings` and `__originalMappings` are arrays that hold the +// parsed mapping coordinates from the source map's "mappings" attribute. They +// are lazily instantiated, accessed via the `_generatedMappings` and +// `_originalMappings` getters respectively, and we only parse the mappings +// and create these arrays once queried for a source location. We jump through +// these hoops because there can be many thousands of mappings, and parsing +// them is expensive, so we only want to do it if we must. +// +// Each object in the arrays is of the form: +// +// { +// generatedLine: The line number in the generated code, +// generatedColumn: The column number in the generated code, +// source: The path to the original source file that generated this +// chunk of code, +// originalLine: The line number in the original source that +// corresponds to this chunk of generated code, +// originalColumn: The column number in the original source that +// corresponds to this chunk of generated code, +// name: The name of the original symbol which generated this chunk of +// code. +// } +// +// All properties except for `generatedLine` and `generatedColumn` can be +// `null`. +// +// `_generatedMappings` is ordered by the generated positions. +// +// `_originalMappings` is ordered by the original positions. + +SourceMapConsumer.prototype.__generatedMappings = null; +Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; } -} +}); -function hasOpen(node) { - return node.nodes && node.nodes[0].type === (node.type + '.open'); -} +SourceMapConsumer.prototype.__originalMappings = null; +Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } -function hasClose(node) { - return node.nodes && utils.last(node.nodes).type === (node.type + '.close'); -} + return this.__originalMappings; + } +}); -function hasDelims(node) { - return hasOpen(node) && hasClose(node); -} +SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; /** - * Expose `Parser` + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). */ +SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; -module.exports = Parser; +SourceMapConsumer.GENERATED_ORDER = 1; +SourceMapConsumer.ORIGINAL_ORDER = 2; +SourceMapConsumer.GREATEST_LOWER_BOUND = 1; +SourceMapConsumer.LEAST_UPPER_BOUND = 2; -/***/ }), -/* 720 */ -/***/ (function(module, exports, __webpack_require__) { +/** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ +SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; -"use strict"; -/*! - * map-cache + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + if (source != null && sourceRoot != null) { + source = util.join(sourceRoot, source); + } + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; + +/** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. * - * Copyright (c) 2015, Jon Schlinkert. - * Licensed under the MIT License. + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. + * - column: Optional. the column number in the original source. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. */ +SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + if (this.sourceRoot != null) { + needle.source = util.relative(this.sourceRoot, needle.source); + } + if (!this._sources.has(needle.source)) { + return []; + } + needle.source = this._sources.indexOf(needle.source); -var hasOwn = Object.prototype.hasOwnProperty; + var mappings = []; -/** - * Expose `MapCache` - */ + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; -module.exports = MapCache; + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; -/** - * Creates a cache object to store key/value pairs. - * - * ```js - * var cache = new MapCache(); - * ``` - * - * @api public - */ + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); -function MapCache(data) { - this.__data__ = data || {}; -} + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; -/** - * Adds `value` to `key` on the cache. - * - * ```js - * cache.set('foo', 'bar'); - * ``` - * - * @param {String} `key` The key of the value to cache. - * @param {*} `value` The value to cache. - * @returns {Object} Returns the `Cache` object for chaining. - * @api public - */ + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); -MapCache.prototype.set = function mapSet(key, value) { - if (key !== '__proto__') { - this.__data__[key] = value; - } - return this; -}; + mapping = this._originalMappings[++index]; + } + } + } -/** - * Gets the cached value for `key`. - * - * ```js - * cache.get('foo'); - * //=> 'bar' - * ``` - * - * @param {String} `key` The key of the value to get. - * @returns {*} Returns the cached value. - * @api public - */ + return mappings; + }; -MapCache.prototype.get = function mapGet(key) { - return key === '__proto__' ? undefined : this.__data__[key]; -}; +exports.SourceMapConsumer = SourceMapConsumer; /** - * Checks if a cached value for `key` exists. + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. * - * ```js - * cache.has('foo'); - * //=> true - * ``` + * The only parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: * - * @param {String} `key` The key of the entry to check. - * @returns {Boolean} Returns `true` if an entry for `key` exists, else `false`. - * @api public - */ - -MapCache.prototype.has = function mapHas(key) { - return key !== '__proto__' && hasOwn.call(this.__data__, key); -}; - -/** - * Removes `key` and its value from the cache. + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. * - * ```js - * cache.del('foo'); - * ``` - * @title .del - * @param {String} `key` The key of the value to remove. - * @returns {Boolean} Returns `true` if the entry was removed successfully, else `false`. - * @api public + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# */ +function BasicSourceMapConsumer(aSourceMap) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); + } -MapCache.prototype.del = function mapDelete(key) { - return this.has(key) && delete this.__data__[key]; -}; + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } -/***/ }), -/* 721 */ -/***/ (function(module, exports, __webpack_require__) { + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); -"use strict"; + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this.file = file; +} -var define = __webpack_require__(685); +BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); +BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; /** - * Store position for a node + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @returns BasicSourceMapConsumer */ +BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap) { + var smc = Object.create(BasicSourceMapConsumer.prototype); -module.exports = function Position(start, parser) { - this.start = start; - this.end = { line: parser.line, column: parser.column }; - define(this, 'content', parser.orig); - define(this, 'source', parser.options.source); -}; + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. -/***/ }), -/* 722 */ -/***/ (function(module, exports, __webpack_require__) { + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; -"use strict"; + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; -var isExtendable = __webpack_require__(723); -var assignSymbols = __webpack_require__(626); + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } -module.exports = Object.assign || function(obj/*, objects*/) { - if (obj === null || typeof obj === 'undefined') { - throw new TypeError('Cannot convert undefined or null to object'); - } - if (!isObject(obj)) { - obj = {}; - } - for (var i = 1; i < arguments.length; i++) { - var val = arguments[i]; - if (isString(val)) { - val = toObject(val); - } - if (isObject(val)) { - assign(obj, val); - assignSymbols(obj, val); - } - } - return obj; -}; + destOriginalMappings.push(destMapping); + } -function assign(a, b) { - for (var key in b) { - if (hasOwn(b, key)) { - a[key] = b[key]; + destGeneratedMappings.push(destMapping); } - } -} -function isString(val) { - return (val && typeof val === 'string'); -} - -function toObject(str) { - var obj = {}; - for (var i in str) { - obj[i] = str[i]; - } - return obj; -} + quickSort(smc.__originalMappings, util.compareByOriginalPositions); -function isObject(val) { - return (val && typeof val === 'object') || isExtendable(val); -} + return smc; + }; /** - * Returns true if the given `key` is an own property of `obj`. + * The version of the source mapping spec that we are consuming. */ +BasicSourceMapConsumer.prototype._version = 3; -function hasOwn(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -} +/** + * The list of original sources. + */ +Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._sources.toArray().map(function (s) { + return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s; + }, this); + } +}); -function isEnum(obj, key) { - return Object.prototype.propertyIsEnumerable.call(obj, key); +/** + * Provide the JIT with a nice shape / hidden class. + */ +function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; } - -/***/ }), -/* 723 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/*! - * is-extendable - * - * Copyright (c) 2015-2017, Jon Schlinkert. - * Released under the MIT License. +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). */ +BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); -var isPlainObject = __webpack_require__(625); + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } -module.exports = function isExtendable(val) { - return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); -}; + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } -/***/ }), -/* 724 */ -/***/ (function(module, exports, __webpack_require__) { + cachedSegments[str] = segment; + } -"use strict"; + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; -var nanomatch = __webpack_require__(725); -var extglob = __webpack_require__(739); + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; -module.exports = function(snapdragon) { - var compilers = snapdragon.compiler.compilers; - var opts = snapdragon.options; + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; - // register nanomatch compilers - snapdragon.use(nanomatch.compilers); + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } - // get references to some specific nanomatch compilers before they - // are overridden by the extglob and/or custom compilers - var escape = compilers.escape; - var qmark = compilers.qmark; - var slash = compilers.slash; - var star = compilers.star; - var text = compilers.text; - var plus = compilers.plus; - var dot = compilers.dot; + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } - // register extglob compilers or escape exglobs if disabled - if (opts.extglob === false || opts.noext === true) { - snapdragon.compiler.use(escapeExtglobs); - } else { - snapdragon.use(extglob.compilers); - } + quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; - snapdragon.use(function() { - this.options.star = this.options.star || function(/*node*/) { - return '[^\\\\/]*?'; - }; - }); + quickSort(originalMappings, util.compareByOriginalPositions); + this.__originalMappings = originalMappings; + }; - // custom micromatch compilers - snapdragon.compiler +/** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ +BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. - // reset referenced compiler - .set('dot', dot) - .set('escape', escape) - .set('plus', plus) - .set('slash', slash) - .set('qmark', qmark) - .set('star', star) - .set('text', text); -}; + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } -function escapeExtglobs(compiler) { - compiler.set('paren', function(node) { - var val = ''; - visit(node, function(tok) { - if (tok.val) val += (/^\W/.test(tok.val) ? '\\' : '') + tok.val; - }); - return this.emit(val, node); - }); + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; - /** - * Visit `node` with the given `fn` - */ +/** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ +BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; - function visit(node, fn) { - return node.nodes ? mapVisit(node.nodes, fn) : fn(node); - } + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; - /** - * Map visit over array of `nodes`. - */ + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } - function mapVisit(nodes, fn) { - var len = nodes.length; - var idx = -1; - while (++idx < len) { - visit(nodes[idx], fn); + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; } - } -} + }; +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. + * - column: The column number in the generated source. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. + * - column: The column number in the original source, or null. + * - name: The original identifier, or null. + */ +BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; -/***/ }), -/* 725 */ -/***/ (function(module, exports, __webpack_require__) { + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); -"use strict"; + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + if (this.sourceRoot != null) { + source = util.join(this.sourceRoot, source); + } + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + return { + source: null, + line: null, + column: null, + name: null + }; + }; /** - * Module dependencies + * Return true if we have the source content for every source in the source + * map, false otherwise. */ - -var util = __webpack_require__(234); -var toRegex = __webpack_require__(610); -var extend = __webpack_require__(726); +BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; /** - * Local dependencies + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. */ +BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } -var compilers = __webpack_require__(728); -var parsers = __webpack_require__(729); -var cache = __webpack_require__(732); -var utils = __webpack_require__(734); -var MAX_LENGTH = 1024 * 64; + if (this.sourceRoot != null) { + aSource = util.relative(this.sourceRoot, aSource); + } + + if (this._sources.has(aSource)) { + return this.sourcesContent[this._sources.indexOf(aSource)]; + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = aSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + aSource)) { + return this.sourcesContent[this._sources.indexOf("/" + aSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; /** - * The main function takes a list of strings and one or more - * glob patterns to use for matching. + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: * - * ```js - * var nm = require('nanomatch'); - * nm(list, patterns[, options]); + * - source: The filename of the original source. + * - line: The line number in the original source. + * - column: The column number in the original source. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. * - * console.log(nm(['a.js', 'a.txt'], ['*.js'])); - * //=> [ 'a.js' ] - * ``` - * @param {Array} `list` A list of strings to match - * @param {String|Array} `patterns` One or more glob patterns to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Array} Returns an array of matches - * @summary false - * @api public + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. */ +BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + if (this.sourceRoot != null) { + source = util.relative(this.sourceRoot, source); + } + if (!this._sources.has(source)) { + return { + line: null, + column: null, + lastColumn: null + }; + } + source = this._sources.indexOf(source); -function nanomatch(list, patterns, options) { - patterns = utils.arrayify(patterns); - list = utils.arrayify(list); - - var len = patterns.length; - if (list.length === 0 || len === 0) { - return []; - } - - if (len === 1) { - return nanomatch.match(list, patterns[0], options); - } - - var negated = false; - var omit = []; - var keep = []; - var idx = -1; + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; - while (++idx < len) { - var pattern = patterns[idx]; + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); - if (typeof pattern === 'string' && pattern.charCodeAt(0) === 33 /* ! */) { - omit.push.apply(omit, nanomatch.match(list, pattern.slice(1), options)); - negated = true; - } else { - keep.push.apply(keep, nanomatch.match(list, pattern, options)); - } - } + if (index >= 0) { + var mapping = this._originalMappings[index]; - // minimatch.match parity - if (negated && keep.length === 0) { - if (options && options.unixify === false) { - keep = list.slice(); - } else { - var unixify = utils.unixify(options); - for (var i = 0; i < list.length; i++) { - keep.push(unixify(list[i])); + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; } } - } - var matches = utils.diff(keep, omit); - if (!options || options.nodupes !== false) { - return utils.unique(matches); - } + return { + line: null, + column: null, + lastColumn: null + }; + }; - return matches; -} +exports.BasicSourceMapConsumer = BasicSourceMapConsumer; /** - * Similar to the main function, but `pattern` must be a string. + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. * - * ```js - * var nm = require('nanomatch'); - * nm.match(list, pattern[, options]); + * The only parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: * - * console.log(nm.match(['a.a', 'a.aa', 'a.b', 'a.c'], '*.a')); - * //=> ['a.a', 'a.aa'] - * ``` - * @param {Array} `list` Array of strings to match - * @param {String} `pattern` Glob pattern to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Array} Returns an array of matches - * @api public + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt */ - -nanomatch.match = function(list, pattern, options) { - if (Array.isArray(pattern)) { - throw new TypeError('expected pattern to be a string'); +function IndexedSourceMapConsumer(aSourceMap) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); } - var unixify = utils.unixify(options); - var isMatch = memoize('match', pattern, options, nanomatch.matcher); - var matches = []; - - list = utils.arrayify(list); - var len = list.length; - var idx = -1; + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); - while (++idx < len) { - var ele = list[idx]; - if (ele === pattern || isMatch(ele)) { - matches.push(utils.value(ele, unixify, options)); - } + if (version != this._version) { + throw new Error('Unsupported version: ' + version); } - // if no options were passed, uniquify results and return - if (typeof options === 'undefined') { - return utils.unique(matches); - } + this._sources = new ArraySet(); + this._names = new ArraySet(); - if (matches.length === 0) { - if (options.failglob === true) { - throw new Error('no matches found for "' + pattern + '"'); + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); } - if (options.nonull === true || options.nullglob === true) { - return [options.unescape ? utils.unescape(pattern) : pattern]; + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); } - } + lastOffset = offset; - // if `opts.ignore` was defined, diff ignored list - if (options.ignore) { - matches = nanomatch.not(matches, options.ignore, options); - } + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map')) + } + }); +} - return options.nodupes !== false ? utils.unique(matches) : matches; -}; +IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); +IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; /** - * Returns true if the specified `string` matches the given glob `pattern`. + * The version of the source mapping spec that we are consuming. + */ +IndexedSourceMapConsumer.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } +}); + +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: * - * ```js - * var nm = require('nanomatch'); - * nm.isMatch(string, pattern[, options]); + * - line: The line number in the generated source. + * - column: The column number in the generated source. * - * console.log(nm.isMatch('a.a', '*.a')); - * //=> true - * console.log(nm.isMatch('a.b', '*.a')); - * //=> false - * ``` - * @param {String} `string` String to match - * @param {String} `pattern` Glob pattern to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Boolean} Returns true if the string matches the glob pattern. - * @api public + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. + * - column: The column number in the original source, or null. + * - name: The original identifier, or null. */ +IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; -nanomatch.isMatch = function(str, pattern, options) { - if (typeof str !== 'string') { - throw new TypeError('expected a string: "' + util.inspect(str) + '"'); - } + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } - if (utils.isEmptyString(str) || utils.isEmptyString(pattern)) { - return false; - } + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; - var equals = utils.equalsPattern(options); - if (equals(str)) { - return true; - } + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; - var isMatch = memoize('isMatch', pattern, options, nanomatch.matcher); - return isMatch(str); -}; + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; /** - * Returns true if some of the elements in the given `list` match any of the - * given glob `patterns`. + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: * - * ```js - * var nm = require('nanomatch'); - * nm.some(list, patterns[, options]); + * - source: The filename of the original source. + * - line: The line number in the original source. + * - column: The column number in the original source. * - * console.log(nm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); - * // true - * console.log(nm.some(['foo.js'], ['*.js', '!foo.js'])); - * // false - * ``` - * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found. - * @param {String|Array} `patterns` One or more glob patterns to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Boolean} Returns true if any patterns match `str` - * @api public + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. */ +IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; -nanomatch.some = function(list, patterns, options) { - if (typeof list === 'string') { - list = [list]; - } - - for (var i = 0; i < list.length; i++) { - if (nanomatch(list[i], patterns, options).length === 1) { - return true; + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } } - } - return false; -}; + return { + line: null, + column: null + }; + }; /** - * Returns true if every element in the given `list` matches - * at least one of the given glob `patterns`. - * - * ```js - * var nm = require('nanomatch'); - * nm.every(list, patterns[, options]); - * - * console.log(nm.every('foo.js', ['foo.js'])); - * // true - * console.log(nm.every(['foo.js', 'bar.js'], ['*.js'])); - * // true - * console.log(nm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); - * // false - * console.log(nm.every(['foo.js'], ['*.js', '!foo.js'])); - * // false - * ``` - * @param {String|Array} `list` The string or array of strings to test. - * @param {String|Array} `patterns` One or more glob patterns to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Boolean} Returns true if any patterns match `str` - * @api public + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). */ +IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; -nanomatch.every = function(list, patterns, options) { - if (typeof list === 'string') { - list = [list]; - } + var source = section.consumer._sources.at(mapping.source); + if (section.consumer.sourceRoot !== null) { + source = util.join(section.consumer.sourceRoot, source); + } + this._sources.add(source); + source = this._sources.indexOf(source); - for (var i = 0; i < list.length; i++) { - if (nanomatch(list[i], patterns, options).length !== 1) { - return false; + var name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } } - } - return true; -}; + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; -/** - * Returns true if **any** of the given glob `patterns` - * match the specified `string`. - * - * ```js - * var nm = require('nanomatch'); - * nm.any(string, patterns[, options]); - * - * console.log(nm.any('a.a', ['b.*', '*.a'])); - * //=> true - * console.log(nm.any('a.a', 'b.*')); - * //=> false - * ``` - * @param {String|Array} `str` The string to test. - * @param {String|Array} `patterns` One or more glob patterns to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Boolean} Returns true if any patterns match `str` - * @api public - */ +exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; -nanomatch.any = function(str, patterns, options) { - if (typeof str !== 'string') { - throw new TypeError('expected a string: "' + util.inspect(str) + '"'); - } - if (utils.isEmptyString(str) || utils.isEmptyString(patterns)) { - return false; - } +/***/ }), +/* 746 */ +/***/ (function(module, exports) { - if (typeof patterns === 'string') { - patterns = [patterns]; - } +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ - for (var i = 0; i < patterns.length; i++) { - if (nanomatch.isMatch(str, patterns[i], options)) { - return true; - } - } - return false; -}; +exports.GREATEST_LOWER_BOUND = 1; +exports.LEAST_UPPER_BOUND = 2; /** - * Returns true if **all** of the given `patterns` - * match the specified string. - * - * ```js - * var nm = require('nanomatch'); - * nm.all(string, patterns[, options]); - * - * console.log(nm.all('foo.js', ['foo.js'])); - * // true - * - * console.log(nm.all('foo.js', ['*.js', '!foo.js'])); - * // false - * - * console.log(nm.all('foo.js', ['*.js', 'foo.js'])); - * // true + * Recursive implementation of binary search. * - * console.log(nm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); - * // true - * ``` - * @param {String|Array} `str` The string to test. - * @param {String|Array} `patterns` One or more glob patterns to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Boolean} Returns true if any patterns match `str` - * @api public + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. */ - -nanomatch.all = function(str, patterns, options) { - if (typeof str !== 'string') { - throw new TypeError('expected a string: "' + util.inspect(str) + '"'); +function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } - if (typeof patterns === 'string') { - patterns = [patterns]; + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } - for (var i = 0; i < patterns.length; i++) { - if (!nanomatch.isMatch(str, patterns[i], options)) { - return false; + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; } } - return true; -}; +} /** - * Returns a list of strings that _**do not match any**_ of the given `patterns`. - * - * ```js - * var nm = require('nanomatch'); - * nm.not(list, patterns[, options]); + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. * - * console.log(nm.not(['a.a', 'b.b', 'c.c'], '*.a')); - * //=> ['b.b', 'c.c'] - * ``` - * @param {Array} `list` Array of strings to match. - * @param {String|Array} `patterns` One or more glob pattern to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Array} Returns an array of strings that **do not match** the given patterns. - * @api public + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. */ - -nanomatch.not = function(list, patterns, options) { - var opts = extend({}, options); - var ignore = opts.ignore; - delete opts.ignore; - - list = utils.arrayify(list); - - var matches = utils.diff(list, nanomatch(list, patterns, opts)); - if (ignore) { - matches = utils.diff(matches, nanomatch(list, ignore)); +exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; } - return opts.nodupes !== false ? utils.unique(matches) : matches; -}; - -/** - * Returns true if the given `string` contains the given pattern. Similar - * to [.isMatch](#isMatch) but the pattern can match any part of the string. - * - * ```js - * var nm = require('nanomatch'); - * nm.contains(string, pattern[, options]); - * - * console.log(nm.contains('aa/bb/cc', '*b')); - * //=> true - * console.log(nm.contains('aa/bb/cc', '*d')); - * //=> false - * ``` - * @param {String} `str` The string to match. - * @param {String|Array} `patterns` Glob pattern to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Boolean} Returns true if the patter matches any part of `str`. - * @api public - */ - -nanomatch.contains = function(str, patterns, options) { - if (typeof str !== 'string') { - throw new TypeError('expected a string: "' + util.inspect(str) + '"'); + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; } - if (typeof patterns === 'string') { - if (utils.isEmptyString(str) || utils.isEmptyString(patterns)) { - return false; - } - - var equals = utils.equalsPattern(patterns, options); - if (equals(str)) { - return true; - } - var contains = utils.containsPattern(patterns, options); - if (contains(str)) { - return true; + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; } + --index; } - var opts = extend({}, options, {contains: true}); - return nanomatch.any(str, patterns, opts); + return index; }; -/** - * Returns true if the given pattern and options should enable - * the `matchBase` option. - * @return {Boolean} - * @api private + +/***/ }), +/* 747 */ +/***/ (function(module, exports) { + +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause */ -nanomatch.matchBase = function(pattern, options) { - if (pattern && pattern.indexOf('/') !== -1 || !options) return false; - return options.basename === true || options.matchBase === true; -}; +// It turns out that some (most?) JavaScript engines don't self-host +// `Array.prototype.sort`. This makes sense because C++ will likely remain +// faster than JS when doing raw CPU-intensive sorting. However, when using a +// custom comparator function, calling back and forth between the VM's C++ and +// JIT'd JS is rather slow *and* loses JIT type information, resulting in +// worse generated code for the comparator function than would be optimal. In +// fact, when sorting with a comparator, these costs outweigh the benefits of +// sorting in C++. By using our own JS-implemented Quick Sort (below), we get +// a ~3500ms mean speed-up in `bench/bench.html`. /** - * Filter the keys of the given object with the given `glob` pattern - * and `options`. Does not attempt to match nested keys. If you need this feature, - * use [glob-object][] instead. - * - * ```js - * var nm = require('nanomatch'); - * nm.matchKeys(object, patterns[, options]); + * Swap the elements indexed by `x` and `y` in the array `ary`. * - * var obj = { aa: 'a', ab: 'b', ac: 'c' }; - * console.log(nm.matchKeys(obj, '*b')); - * //=> { ab: 'b' } - * ``` - * @param {Object} `object` The object with keys to filter. - * @param {String|Array} `patterns` One or more glob patterns to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Object} Returns an object with only keys that match the given patterns. - * @api public + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. */ - -nanomatch.matchKeys = function(obj, patterns, options) { - if (!utils.isObject(obj)) { - throw new TypeError('expected the first argument to be an object'); - } - var keys = nanomatch(Object.keys(obj), patterns, options); - return utils.pick(obj, keys); -}; +function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; +} /** - * Returns a memoized matcher function from the given glob `pattern` and `options`. - * The returned function takes a string to match as its only argument and returns - * true if the string is a match. + * Returns a random integer within the range `low .. high` inclusive. * - * ```js - * var nm = require('nanomatch'); - * nm.matcher(pattern[, options]); + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ +function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); +} + +/** + * The Quick Sort algorithm. * - * var isMatch = nm.matcher('*.!(*a)'); - * console.log(isMatch('a.a')); - * //=> false - * console.log(isMatch('a.b')); - * //=> true - * ``` - * @param {String} `pattern` Glob pattern - * @param {Object} `options` See available [options](#options) for changing how matches are performed. - * @return {Function} Returns a matcher function. - * @api public + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array */ +function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot) <= 0) { + i += 1; + swap(ary, i, j); + } + } -nanomatch.matcher = function matcher(pattern, options) { - if (utils.isEmptyString(pattern)) { - return function() { - return false; - }; - } + swap(ary, i + 1, j); + var q = i + 1; - if (Array.isArray(pattern)) { - return compose(pattern, options, matcher); - } + // (2) Recurse on each half. - // if pattern is a regex - if (pattern instanceof RegExp) { - return test(pattern); + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); } +} - // if pattern is invalid - if (!utils.isString(pattern)) { - throw new TypeError('expected pattern to be an array, string or regex'); - } +/** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ +exports.quickSort = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); +}; - // if pattern is a non-glob string - if (!utils.hasSpecialChars(pattern)) { - if (options && options.nocase === true) { - pattern = pattern.toLowerCase(); - } - return utils.matchPath(pattern, options); - } - // if pattern is a glob string - var re = nanomatch.makeRe(pattern, options); +/***/ }), +/* 748 */ +/***/ (function(module, exports, __webpack_require__) { - // if `options.matchBase` or `options.basename` is defined - if (nanomatch.matchBase(pattern, options)) { - return utils.matchBasename(re, options); - } +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ - function test(regex) { - var equals = utils.equalsPattern(options); - var unixify = utils.unixify(options); +var SourceMapGenerator = __webpack_require__(739).SourceMapGenerator; +var util = __webpack_require__(742); - return function(str) { - if (equals(str)) { - return true; - } +// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other +// operating systems these days (capturing the result). +var REGEX_NEWLINE = /(\r?\n)/; - if (regex.test(unixify(str))) { - return true; - } - return false; - }; - } +// Newline character code for charCodeAt() comparisons +var NEWLINE_CODE = 10; - // create matcher function - var matcherFn = test(re); - // set result object from compiler on matcher function, - // as a non-enumerable property. useful for debugging - utils.define(matcherFn, 'result', re.result); - return matcherFn; -}; +// Private symbol for identifying `SourceNode`s when multiple versions of +// the source-map library are loaded. This MUST NOT CHANGE across +// versions! +var isSourceNode = "$$$isSourceNode$$$"; /** - * Returns an array of matches captured by `pattern` in `string, or - * `null` if the pattern did not match. + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. * - * ```js - * var nm = require('nanomatch'); - * nm.capture(pattern, string[, options]); + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ +function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); +} + +/** + * Creates a SourceNode from generated code and a SourceMapConsumer. * - * console.log(nm.capture('test/*.js', 'test/foo.js')); - * //=> ['foo'] - * console.log(nm.capture('test/*.js', 'foo/bar.css')); - * //=> null - * ``` - * @param {String} `pattern` Glob pattern to use for matching. - * @param {String} `string` String to match - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Boolean} Returns an array of captures if the string matches the glob pattern, otherwise `null`. - * @api public + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. */ +SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); -nanomatch.capture = function(pattern, str, options) { - var re = nanomatch.makeRe(pattern, extend({capture: true}, options)); - var unixify = utils.unixify(options); + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var remainingLinesIndex = 0; + var shiftNextLine = function() { + var lineContents = getNextLine(); + // The last line of a file might not have a newline. + var newLine = getNextLine() || ""; + return lineContents + newLine; - function match() { - return function(string) { - var match = re.exec(unixify(string)); - if (!match) { - return null; + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? + remainingLines[remainingLinesIndex++] : undefined; } - - return match.slice(1); }; - } - - var capture = memoize('capture', pattern, options, match); - return capture(str); -}; -/** - * Create a regular expression from the given glob `pattern`. - * - * ```js - * var nm = require('nanomatch'); - * nm.makeRe(pattern[, options]); - * - * console.log(nm.makeRe('*.js')); - * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ - * ``` - * @param {String} `pattern` A glob pattern to convert to regex. - * @param {Object} `options` See available [options](#options) for changing how matches are performed. - * @return {RegExp} Returns a regex created from the given pattern. - * @api public - */ + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; -nanomatch.makeRe = function(pattern, options) { - if (pattern instanceof RegExp) { - return pattern; - } + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; - if (typeof pattern !== 'string') { - throw new TypeError('expected pattern to be a string'); - } + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[remainingLinesIndex]; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[remainingLinesIndex]; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } - if (pattern.length > MAX_LENGTH) { - throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters'); - } + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); - function makeRe() { - var opts = utils.extend({wrap: false}, options); - var result = nanomatch.create(pattern, opts); - var regex = toRegex(result.output, opts); - utils.define(regex, 'result', result); - return regex; - } + return node; - return memoize('makeRe', pattern, options, makeRe); -}; + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; /** - * Parses the given glob `pattern` and returns an object with the compiled `output` - * and optional source `map`. - * - * ```js - * var nm = require('nanomatch'); - * nm.create(pattern[, options]); + * Add a chunk of generated JS to this source node. * - * console.log(nm.create('abc/*.js')); - * // { options: { source: 'string', sourcemap: true }, - * // state: {}, - * // compilers: - * // { ... }, - * // output: '(\\.[\\\\\\/])?abc\\/(?!\\.)(?=.)[^\\/]*?\\.js', - * // ast: - * // { type: 'root', - * // errors: [], - * // nodes: - * // [ ... ], - * // dot: false, - * // input: 'abc/*.js' }, - * // parsingErrors: [], - * // map: - * // { version: 3, - * // sources: [ 'string' ], - * // names: [], - * // mappings: 'AAAA,GAAG,EAAC,kBAAC,EAAC,EAAE', - * // sourcesContent: [ 'abc/*.js' ] }, - * // position: { line: 1, column: 28 }, - * // content: {}, - * // files: {}, - * // idx: 6 } - * ``` - * @param {String} `pattern` Glob pattern to parse and compile. - * @param {Object} `options` Any [options](#options) to change how parsing and compiling is performed. - * @return {Object} Returns an object with the parsed AST, compiled string and optional source map. - * @api public + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. */ - -nanomatch.create = function(pattern, options) { - if (typeof pattern !== 'string') { - throw new TypeError('expected a string'); +SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); } - function create() { - return nanomatch.compile(nanomatch.parse(pattern, options), options); + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } } - return memoize('create', pattern, options, create); + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; }; /** - * Parse the given `str` with the given `options`. - * - * ```js - * var nm = require('nanomatch'); - * nm.parse(pattern[, options]); + * Add a chunk of generated JS to the beginning of this source node. * - * var ast = nm.parse('a/{b,c}/d'); - * console.log(ast); - * // { type: 'root', - * // errors: [], - * // input: 'a/{b,c}/d', - * // nodes: - * // [ { type: 'bos', val: '' }, - * // { type: 'text', val: 'a/' }, - * // { type: 'brace', - * // nodes: - * // [ { type: 'brace.open', val: '{' }, - * // { type: 'text', val: 'b,c' }, - * // { type: 'brace.close', val: '}' } ] }, - * // { type: 'text', val: '/d' }, - * // { type: 'eos', val: '' } ] } - * ``` - * @param {String} `str` - * @param {Object} `options` - * @return {Object} Returns an AST - * @api public + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. */ - -nanomatch.parse = function(pattern, options) { - if (typeof pattern !== 'string') { - throw new TypeError('expected a string'); +SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } } - - function parse() { - var snapdragon = utils.instantiate(null, options); - parsers(snapdragon, options); - - var ast = snapdragon.parse(pattern, options); - utils.define(ast, 'snapdragon', snapdragon); - ast.input = pattern; - return ast; + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); } - - return memoize('parse', pattern, options, parse); + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; }; /** - * Compile the given `ast` or string with the given `options`. - * - * ```js - * var nm = require('nanomatch'); - * nm.compile(ast[, options]); + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. * - * var ast = nm.parse('a/{b,c}/d'); - * console.log(nm.compile(ast)); - * // { options: { source: 'string' }, - * // state: {}, - * // compilers: - * // { eos: [Function], - * // noop: [Function], - * // bos: [Function], - * // brace: [Function], - * // 'brace.open': [Function], - * // text: [Function], - * // 'brace.close': [Function] }, - * // output: [ 'a/(b|c)/d' ], - * // ast: - * // { ... }, - * // parsingErrors: [] } - * ``` - * @param {Object|String} `ast` - * @param {Object} `options` - * @return {Object} Returns an object that has an `output` property with the compiled string. - * @api public + * @param aFn The traversal function. */ - -nanomatch.compile = function(ast, options) { - if (typeof ast === 'string') { - ast = nanomatch.parse(ast, options); - } - - function compile() { - var snapdragon = utils.instantiate(ast, options); - compilers(snapdragon, options); - return snapdragon.compile(ast, options); +SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } } - - return memoize('compile', ast.input, options, compile); }; /** - * Clear the regex cache. + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. * - * ```js - * nm.clearCache(); - * ``` - * @api public + * @param aSep The separator. */ - -nanomatch.clearCache = function() { - nanomatch.cache.__data__ = {}; +SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; }; /** - * Compose a matcher function with the given patterns. - * This allows matcher functions to be compiled once and - * called multiple times. - */ - -function compose(patterns, options, matcher) { - var matchers; - - return memoize('compose', String(patterns), options, function() { - return function(file) { - // delay composition until it's invoked the first time, - // after that it won't be called again - if (!matchers) { - matchers = []; - for (var i = 0; i < patterns.length; i++) { - matchers.push(matcher(patterns[i], options)); - } - } - - var len = matchers.length; - while (len--) { - if (matchers[len](file) === true) { - return true; - } - } - return false; - }; - }); -} - -/** - * Memoize a generated regex or function. A unique key is generated - * from the `type` (usually method name), the `pattern`, and - * user-defined options. + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. */ - -function memoize(type, pattern, options, fn) { - var key = utils.createKey(type + '=' + pattern, options); - - if (options && options.cache === false) { - return fn(pattern, options); +SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); } - - if (cache.has(type, key)) { - return cache.get(type, key); + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); } + return this; +}; - var val = fn(pattern, options); - cache.set(type, key, val); - return val; -} +/** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ +SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; /** - * Expose compiler, parser and cache on `nanomatch` + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. */ +SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } -nanomatch.compilers = compilers; -nanomatch.parsers = parsers; -nanomatch.cache = cache; + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; /** - * Expose `nanomatch` - * @type {Function} + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. */ +SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; +}; -module.exports = nanomatch; +/** + * Returns the string representation of this source node along with a source + * map. + */ +SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; +}; + +exports.SourceNode = SourceNode; /***/ }), -/* 726 */ +/* 749 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +// Copyright 2014, 2015, 2016, 2017 Simon Lydell +// X11 (“MIT”) Licensed. (See LICENSE.) +var sourceMappingURL = __webpack_require__(750) +var resolveUrl = __webpack_require__(751) +var decodeUriComponent = __webpack_require__(752) +var urix = __webpack_require__(754) +var atob = __webpack_require__(755) -var isExtendable = __webpack_require__(727); -var assignSymbols = __webpack_require__(626); -module.exports = Object.assign || function(obj/*, objects*/) { - if (obj === null || typeof obj === 'undefined') { - throw new TypeError('Cannot convert undefined or null to object'); - } - if (!isObject(obj)) { - obj = {}; - } - for (var i = 1; i < arguments.length; i++) { - var val = arguments[i]; - if (isString(val)) { - val = toObject(val); - } - if (isObject(val)) { - assign(obj, val); - assignSymbols(obj, val); - } - } - return obj; -}; -function assign(a, b) { - for (var key in b) { - if (hasOwn(b, key)) { - a[key] = b[key]; - } - } +function callbackAsync(callback, error, result) { + setImmediate(function() { callback(error, result) }) } -function isString(val) { - return (val && typeof val === 'string'); +function parseMapToJSON(string, data) { + try { + return JSON.parse(string.replace(/^\)\]\}'/, "")) + } catch (error) { + error.sourceMapData = data + throw error + } } -function toObject(str) { - var obj = {}; - for (var i in str) { - obj[i] = str[i]; +function readSync(read, url, data) { + var readUrl = decodeUriComponent(url) + try { + return String(read(readUrl)) + } catch (error) { + error.sourceMapData = data + throw error } - return obj; } -function isObject(val) { - return (val && typeof val === 'object') || isExtendable(val); -} -/** - * Returns true if the given `key` is an own property of `obj`. - */ -function hasOwn(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); +function resolveSourceMap(code, codeUrl, read, callback) { + var mapData + try { + mapData = resolveSourceMapHelper(code, codeUrl) + } catch (error) { + return callbackAsync(callback, error) + } + if (!mapData || mapData.map) { + return callbackAsync(callback, null, mapData) + } + var readUrl = decodeUriComponent(mapData.url) + read(readUrl, function(error, result) { + if (error) { + error.sourceMapData = mapData + return callback(error) + } + mapData.map = String(result) + try { + mapData.map = parseMapToJSON(mapData.map, mapData) + } catch (error) { + return callback(error) + } + callback(null, mapData) + }) } -function isEnum(obj, key) { - return Object.prototype.propertyIsEnumerable.call(obj, key); +function resolveSourceMapSync(code, codeUrl, read) { + var mapData = resolveSourceMapHelper(code, codeUrl) + if (!mapData || mapData.map) { + return mapData + } + mapData.map = readSync(read, mapData.url, mapData) + mapData.map = parseMapToJSON(mapData.map, mapData) + return mapData } +var dataUriRegex = /^data:([^,;]*)(;[^,;]*)*(?:,(.*))?$/ +var jsonMimeTypeRegex = /^(?:application|text)\/json$/ -/***/ }), -/* 727 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/*! - * is-extendable - * - * Copyright (c) 2015-2017, Jon Schlinkert. - * Released under the MIT License. - */ - - - -var isPlainObject = __webpack_require__(625); +function resolveSourceMapHelper(code, codeUrl) { + codeUrl = urix(codeUrl) -module.exports = function isExtendable(val) { - return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); -}; + var url = sourceMappingURL.getFrom(code) + if (!url) { + return null + } + var dataUri = url.match(dataUriRegex) + if (dataUri) { + var mimeType = dataUri[1] + var lastParameter = dataUri[2] || "" + var encoded = dataUri[3] || "" + var data = { + sourceMappingURL: url, + url: null, + sourcesRelativeTo: codeUrl, + map: encoded + } + if (!jsonMimeTypeRegex.test(mimeType)) { + var error = new Error("Unuseful data uri mime type: " + (mimeType || "text/plain")) + error.sourceMapData = data + throw error + } + data.map = parseMapToJSON( + lastParameter === ";base64" ? atob(encoded) : decodeURIComponent(encoded), + data + ) + return data + } -/***/ }), -/* 728 */ -/***/ (function(module, exports, __webpack_require__) { + var mapUrl = resolveUrl(codeUrl, url) + return { + sourceMappingURL: url, + url: mapUrl, + sourcesRelativeTo: mapUrl, + map: null + } +} -"use strict"; -/** -* Nanomatch compilers -*/ +function resolveSources(map, mapUrl, read, options, callback) { + if (typeof options === "function") { + callback = options + options = {} + } + var pending = map.sources ? map.sources.length : 0 + var result = { + sourcesResolved: [], + sourcesContent: [] + } -module.exports = function(nanomatch, options) { - function slash() { - if (options && typeof options.slash === 'string') { - return options.slash; - } - if (options && typeof options.slash === 'function') { - return options.slash.call(nanomatch); - } - return '\\\\/'; + if (pending === 0) { + callbackAsync(callback, null, result) + return } - function star() { - if (options && typeof options.star === 'string') { - return options.star; - } - if (options && typeof options.star === 'function') { - return options.star.call(nanomatch); + var done = function() { + pending-- + if (pending === 0) { + callback(null, result) } - return '[^' + slash() + ']*?'; } - var ast = nanomatch.ast = nanomatch.parser.ast; - ast.state = nanomatch.parser.state; - nanomatch.compiler.state = ast.state; - nanomatch.compiler - - /** - * Negation / escaping - */ + resolveSourcesHelper(map, mapUrl, options, function(fullUrl, sourceContent, index) { + result.sourcesResolved[index] = fullUrl + if (typeof sourceContent === "string") { + result.sourcesContent[index] = sourceContent + callbackAsync(done, null) + } else { + var readUrl = decodeUriComponent(fullUrl) + read(readUrl, function(error, source) { + result.sourcesContent[index] = error ? error : String(source) + done() + }) + } + }) +} - .set('not', function(node) { - var prev = this.prev(); - if (this.options.nonegate === true || prev.type !== 'bos') { - return this.emit('\\' + node.val, node); - } - return this.emit(node.val, node); - }) - .set('escape', function(node) { - if (this.options.unescape && /^[-\w_.]/.test(node.val)) { - return this.emit(node.val, node); - } - return this.emit('\\' + node.val, node); - }) - .set('quoted', function(node) { - return this.emit(node.val, node); - }) +function resolveSourcesSync(map, mapUrl, read, options) { + var result = { + sourcesResolved: [], + sourcesContent: [] + } - /** - * Regex - */ + if (!map.sources || map.sources.length === 0) { + return result + } - .set('dollar', function(node) { - if (node.parent.type === 'bracket') { - return this.emit(node.val, node); + resolveSourcesHelper(map, mapUrl, options, function(fullUrl, sourceContent, index) { + result.sourcesResolved[index] = fullUrl + if (read !== null) { + if (typeof sourceContent === "string") { + result.sourcesContent[index] = sourceContent + } else { + var readUrl = decodeUriComponent(fullUrl) + try { + result.sourcesContent[index] = String(read(readUrl)) + } catch (error) { + result.sourcesContent[index] = error + } } - return this.emit('\\' + node.val, node); - }) + } + }) - /** - * Dot: "." - */ + return result +} - .set('dot', function(node) { - if (node.dotfiles === true) this.dotfiles = true; - return this.emit('\\' + node.val, node); - }) +var endingSlash = /\/?$/ - /** - * Slashes: "/" and "\" - */ +function resolveSourcesHelper(map, mapUrl, options, fn) { + options = options || {} + mapUrl = urix(mapUrl) + var fullUrl + var sourceContent + var sourceRoot + for (var index = 0, len = map.sources.length; index < len; index++) { + sourceRoot = null + if (typeof options.sourceRoot === "string") { + sourceRoot = options.sourceRoot + } else if (typeof map.sourceRoot === "string" && options.sourceRoot !== false) { + sourceRoot = map.sourceRoot + } + // If the sourceRoot is the empty string, it is equivalent to not setting + // the property at all. + if (sourceRoot === null || sourceRoot === '') { + fullUrl = resolveUrl(mapUrl, map.sources[index]) + } else { + // Make sure that the sourceRoot ends with a slash, so that `/scripts/subdir` becomes + // `/scripts/subdir/`, not `/scripts/`. Pointing to a file as source root + // does not make sense. + fullUrl = resolveUrl(mapUrl, sourceRoot.replace(endingSlash, "/"), map.sources[index]) + } + sourceContent = (map.sourcesContent || [])[index] + fn(fullUrl, sourceContent, index) + } +} - .set('backslash', function(node) { - return this.emit(node.val, node); - }) - .set('slash', function(node, nodes, i) { - var val = '[' + slash() + ']'; - var parent = node.parent; - var prev = this.prev(); - // set "node.hasSlash" to true on all ancestor parens nodes - while (parent.type === 'paren' && !parent.hasSlash) { - parent.hasSlash = true; - parent = parent.parent; - } - if (prev.addQmark) { - val += '?'; +function resolve(code, codeUrl, read, options, callback) { + if (typeof options === "function") { + callback = options + options = {} + } + if (code === null) { + var mapUrl = codeUrl + var data = { + sourceMappingURL: null, + url: mapUrl, + sourcesRelativeTo: mapUrl, + map: null + } + var readUrl = decodeUriComponent(mapUrl) + read(readUrl, function(error, result) { + if (error) { + error.sourceMapData = data + return callback(error) } - - // word boundary - if (node.rest.slice(0, 2) === '\\b') { - return this.emit(val, node); + data.map = String(result) + try { + data.map = parseMapToJSON(data.map, data) + } catch (error) { + return callback(error) } - - // globstars - if (node.parsed === '**' || node.parsed === './**') { - this.output = '(?:' + this.output; - return this.emit(val + ')?', node); + _resolveSources(data) + }) + } else { + resolveSourceMap(code, codeUrl, read, function(error, mapData) { + if (error) { + return callback(error) + } + if (!mapData) { + return callback(null, null) } + _resolveSources(mapData) + }) + } - // negation - if (node.parsed === '!**' && this.options.nonegate !== true) { - return this.emit(val + '?\\b', node); + function _resolveSources(mapData) { + resolveSources(mapData.map, mapData.sourcesRelativeTo, read, options, function(error, result) { + if (error) { + return callback(error) } - return this.emit(val, node); + mapData.sourcesResolved = result.sourcesResolved + mapData.sourcesContent = result.sourcesContent + callback(null, mapData) }) + } +} - /** - * Square brackets - */ +function resolveSync(code, codeUrl, read, options) { + var mapData + if (code === null) { + var mapUrl = codeUrl + mapData = { + sourceMappingURL: null, + url: mapUrl, + sourcesRelativeTo: mapUrl, + map: null + } + mapData.map = readSync(read, mapUrl, mapData) + mapData.map = parseMapToJSON(mapData.map, mapData) + } else { + mapData = resolveSourceMapSync(code, codeUrl, read) + if (!mapData) { + return null + } + } + var result = resolveSourcesSync(mapData.map, mapData.sourcesRelativeTo, read, options) + mapData.sourcesResolved = result.sourcesResolved + mapData.sourcesContent = result.sourcesContent + return mapData +} - .set('bracket', function(node) { - var close = node.close; - var open = !node.escaped ? '[' : '\\['; - var negated = node.negated; - var inner = node.inner; - var val = node.val; - if (node.escaped === true) { - inner = inner.replace(/\\?(\W)/g, '\\$1'); - negated = ''; - } - if (inner === ']-') { - inner = '\\]\\-'; - } +module.exports = { + resolveSourceMap: resolveSourceMap, + resolveSourceMapSync: resolveSourceMapSync, + resolveSources: resolveSources, + resolveSourcesSync: resolveSourcesSync, + resolve: resolve, + resolveSync: resolveSync, + parseMapToJSON: parseMapToJSON +} - if (negated && inner.indexOf('.') === -1) { - inner += '.'; - } - if (negated && inner.indexOf('/') === -1) { - inner += '/'; - } - val = open + negated + inner + close; - return this.emit(val, node); - }) +/***/ }), +/* 750 */ +/***/ (function(module, exports, __webpack_require__) { - /** - * Square: "[.]" (only matches a single character in brackets) - */ +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;// Copyright 2014 Simon Lydell +// X11 (“MIT”) Licensed. (See LICENSE.) - .set('square', function(node) { - var val = (/^\W/.test(node.val) ? '\\' : '') + node.val; - return this.emit(val, node); - }) +void (function(root, factory) { + if (true) { + !(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : + __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) + } else {} +}(this, function() { - /** - * Question mark: "?" - */ + var innerRegex = /[#@] sourceMappingURL=([^\s'"]*)/ - .set('qmark', function(node) { - var prev = this.prev(); - // don't use "slash" variable so that we always avoid - // matching backslashes and slashes with a qmark - var val = '[^.\\\\/]'; - if (this.options.dot || (prev.type !== 'bos' && prev.type !== 'slash')) { - val = '[^\\\\/]'; - } + var regex = RegExp( + "(?:" + + "/\\*" + + "(?:\\s*\r?\n(?://)?)?" + + "(?:" + innerRegex.source + ")" + + "\\s*" + + "\\*/" + + "|" + + "//(?:" + innerRegex.source + ")" + + ")" + + "\\s*" + ) - if (node.parsed.slice(-1) === '(') { - var ch = node.rest.charAt(0); - if (ch === '!' || ch === '=' || ch === ':') { - return this.emit(node.val, node); - } - } + return { - if (node.val.length > 1) { - val += '{' + node.val.length + '}'; - } - return this.emit(val, node); - }) + regex: regex, + _innerRegex: innerRegex, - /** - * Plus - */ + getFrom: function(code) { + var match = code.match(regex) + return (match ? match[1] || match[2] || "" : null) + }, - .set('plus', function(node) { - var prev = node.parsed.slice(-1); - if (prev === ']' || prev === ')') { - return this.emit(node.val, node); - } - if (!this.output || (/[?*+]/.test(ch) && node.parent.type !== 'bracket')) { - return this.emit('\\+', node); - } - var ch = this.output.slice(-1); - if (/\w/.test(ch) && !node.inside) { - return this.emit('+\\+?', node); - } - return this.emit('+', node); - }) + existsIn: function(code) { + return regex.test(code) + }, - /** - * globstar: '**' - */ + removeFrom: function(code) { + return code.replace(regex, "") + }, - .set('globstar', function(node, nodes, i) { - if (!this.output) { - this.state.leadingGlobstar = true; + insertBefore: function(code, string) { + var match = code.match(regex) + if (match) { + return code.slice(0, match.index) + string + code.slice(match.index) + } else { + return code + string } + } + } - var prev = this.prev(); - var before = this.prev(2); - var next = this.next(); - var after = this.next(2); - var type = prev.type; - var val = node.val; +})); - if (prev.type === 'slash' && next.type === 'slash') { - if (before.type === 'text') { - this.output += '?'; - if (after.type !== 'text') { - this.output += '\\b'; - } - } - } +/***/ }), +/* 751 */ +/***/ (function(module, exports, __webpack_require__) { - var parsed = node.parsed; - if (parsed.charAt(0) === '!') { - parsed = parsed.slice(1); - } +// Copyright 2014 Simon Lydell +// X11 (“MIT”) Licensed. (See LICENSE.) - var isInside = node.isInside.paren || node.isInside.brace; - if (parsed && type !== 'slash' && type !== 'bos' && !isInside) { - val = star(); - } else { - val = this.options.dot !== true - ? '(?:(?!(?:[' + slash() + ']|^)\\.).)*?' - : '(?:(?!(?:[' + slash() + ']|^)(?:\\.{1,2})($|[' + slash() + ']))(?!\\.{2}).)*?'; - } +var url = __webpack_require__(324) - if ((type === 'slash' || type === 'bos') && this.options.dot !== true) { - val = '(?!\\.)' + val; - } +function resolveUrl(/* ...urls */) { + return Array.prototype.reduce.call(arguments, function(resolved, nextUrl) { + return url.resolve(resolved, nextUrl) + }) +} - if (prev.type === 'slash' && next.type === 'slash' && before.type !== 'text') { - if (after.type === 'text' || after.type === 'star') { - node.addQmark = true; - } - } +module.exports = resolveUrl - if (this.options.capture) { - val = '(' + val + ')'; - } - return this.emit(val, node); - }) +/***/ }), +/* 752 */ +/***/ (function(module, exports, __webpack_require__) { - /** - * Star: "*" - */ +// Copyright 2017 Simon Lydell +// X11 (“MIT”) Licensed. (See LICENSE.) - .set('star', function(node, nodes, i) { - var prior = nodes[i - 2] || {}; - var prev = this.prev(); - var next = this.next(); - var type = prev.type; +var decodeUriComponent = __webpack_require__(753) - function isStart(n) { - return n.type === 'bos' || n.type === 'slash'; - } +function customDecodeUriComponent(string) { + // `decodeUriComponent` turns `+` into ` `, but that's not wanted. + return decodeUriComponent(string.replace(/\+/g, "%2B")) +} - if (this.output === '' && this.options.contains !== true) { - this.output = '(?![' + slash() + '])'; - } +module.exports = customDecodeUriComponent - if (type === 'bracket' && this.options.bash === false) { - var str = next && next.type === 'bracket' ? star() : '*?'; - if (!prev.nodes || prev.nodes[1].type !== 'posix') { - return this.emit(str, node); - } - } - var prefix = !this.dotfiles && type !== 'text' && type !== 'escape' - ? (this.options.dot ? '(?!(?:^|[' + slash() + '])\\.{1,2}(?:$|[' + slash() + ']))' : '(?!\\.)') - : ''; +/***/ }), +/* 753 */ +/***/ (function(module, exports, __webpack_require__) { - if (isStart(prev) || (isStart(prior) && type === 'not')) { - if (prefix !== '(?!\\.)') { - prefix += '(?!(\\.{2}|\\.[' + slash() + ']))(?=.)'; - } else { - prefix += '(?=.)'; - } - } else if (prefix === '(?!\\.)') { - prefix = ''; - } +"use strict"; - if (prev.type === 'not' && prior.type === 'bos' && this.options.dot === true) { - this.output = '(?!\\.)' + this.output; - } +var token = '%[a-f0-9]{2}'; +var singleMatcher = new RegExp(token, 'gi'); +var multiMatcher = new RegExp('(' + token + ')+', 'gi'); - var output = prefix + star(); - if (this.options.capture) { - output = '(' + output + ')'; - } +function decodeComponents(components, split) { + try { + // Try to decode the entire string first + return decodeURIComponent(components.join('')); + } catch (err) { + // Do nothing + } - return this.emit(output, node); - }) + if (components.length === 1) { + return components; + } - /** - * Text - */ + split = split || 1; - .set('text', function(node) { - return this.emit(node.val, node); - }) + // Split the array in 2 parts + var left = components.slice(0, split); + var right = components.slice(split); - /** - * End-of-string - */ + return Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right)); +} - .set('eos', function(node) { - var prev = this.prev(); - var val = node.val; +function decode(input) { + try { + return decodeURIComponent(input); + } catch (err) { + var tokens = input.match(singleMatcher); - this.output = '(?:\\.[' + slash() + '](?=.))?' + this.output; - if (this.state.metachar && prev.type !== 'qmark' && prev.type !== 'slash') { - val += (this.options.contains ? '[' + slash() + ']?' : '(?:[' + slash() + ']|$)'); - } + for (var i = 1; i < tokens.length; i++) { + input = decodeComponents(tokens, i).join(''); - return this.emit(val, node); - }); + tokens = input.match(singleMatcher); + } - /** - * Allow custom compilers to be passed on options - */ + return input; + } +} - if (options && typeof options.compilers === 'function') { - options.compilers(nanomatch.compiler); - } -}; +function customDecodeURIComponent(input) { + // Keep track of all the replacements and prefill the map with the `BOM` + var replaceMap = { + '%FE%FF': '\uFFFD\uFFFD', + '%FF%FE': '\uFFFD\uFFFD' + }; + var match = multiMatcher.exec(input); + while (match) { + try { + // Decode as big chunks as possible + replaceMap[match[0]] = decodeURIComponent(match[0]); + } catch (err) { + var result = decode(match[0]); + if (result !== match[0]) { + replaceMap[match[0]] = result; + } + } -/***/ }), -/* 729 */ -/***/ (function(module, exports, __webpack_require__) { + match = multiMatcher.exec(input); + } -"use strict"; + // Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else + replaceMap['%C2'] = '\uFFFD'; + var entries = Object.keys(replaceMap); -var regexNot = __webpack_require__(627); -var toRegex = __webpack_require__(610); -var isOdd = __webpack_require__(730); + for (var i = 0; i < entries.length; i++) { + // Replace all decoded components + var key = entries[i]; + input = input.replace(new RegExp(key, 'g'), replaceMap[key]); + } -/** - * Characters to use in negation regex (we want to "not" match - * characters that are matched by other parsers) - */ + return input; +} -var cached; -var NOT_REGEX = '[\\[!*+?$^"\'.\\\\/]+'; -var not = createTextRegex(NOT_REGEX); +module.exports = function (encodedURI) { + if (typeof encodedURI !== 'string') { + throw new TypeError('Expected `encodedURI` to be of type `string`, got `' + typeof encodedURI + '`'); + } -/** - * Nanomatch parsers - */ + try { + encodedURI = encodedURI.replace(/\+/g, ' '); -module.exports = function(nanomatch, options) { - var parser = nanomatch.parser; - var opts = parser.options; + // Try the built in decoder first + return decodeURIComponent(encodedURI); + } catch (err) { + // Fallback to a more advanced decoder + return customDecodeURIComponent(encodedURI); + } +}; - parser.state = { - slashes: 0, - paths: [] - }; - parser.ast.state = parser.state; - parser +/***/ }), +/* 754 */ +/***/ (function(module, exports, __webpack_require__) { - /** - * Beginning-of-string - */ +// Copyright 2014 Simon Lydell +// X11 (“MIT”) Licensed. (See LICENSE.) + +var path = __webpack_require__(4) + +"use strict" + +function urix(aPath) { + if (path.sep === "\\") { + return aPath + .replace(/\\/g, "/") + .replace(/^[a-z]:\/?/i, "/") + } + return aPath +} + +module.exports = urix - .capture('prefix', function() { - if (this.parsed) return; - var m = this.match(/^\.[\\/]/); - if (!m) return; - this.state.strictOpen = !!this.options.strictOpen; - this.state.addPrefix = true; - }) - /** - * Escape: "\\." - */ +/***/ }), +/* 755 */ +/***/ (function(module, exports, __webpack_require__) { - .capture('escape', function() { - if (this.isInside('bracket')) return; - var pos = this.position(); - var m = this.match(/^(?:\\(.)|([$^]))/); - if (!m) return; +"use strict"; - return pos({ - type: 'escape', - val: m[2] || m[1] - }); - }) - /** - * Quoted strings - */ +function atob(str) { + return Buffer.from(str, 'base64').toString('binary'); +} - .capture('quoted', function() { - var pos = this.position(); - var m = this.match(/^["']/); - if (!m) return; +module.exports = atob.atob = atob; - var quote = m[0]; - if (this.input.indexOf(quote) === -1) { - return pos({ - type: 'escape', - val: quote - }); - } - var tok = advanceTo(this.input, quote); - this.consume(tok.len); +/***/ }), +/* 756 */ +/***/ (function(module, exports, __webpack_require__) { - return pos({ - type: 'quoted', - val: tok.esc - }); - }) +"use strict"; - /** - * Negations: "!" - */ - .capture('not', function() { - var parsed = this.parsed; - var pos = this.position(); - var m = this.match(this.notRegex || /^!+/); - if (!m) return; - var val = m[0]; +var fs = __webpack_require__(253); +var path = __webpack_require__(4); +var define = __webpack_require__(723); +var utils = __webpack_require__(737); - var isNegated = isOdd(val.length); - if (parsed === '' && !isNegated) { - val = ''; - } +/** + * Expose `mixin()`. + * This code is based on `source-maps-support.js` in reworkcss/css + * https://github.com/reworkcss/css/blob/master/lib/stringify/source-map-support.js + * Copyright (c) 2012 TJ Holowaychuk + */ + +module.exports = mixin; + +/** + * Mixin source map support into `compiler`. + * + * @param {Object} `compiler` + * @api public + */ + +function mixin(compiler) { + define(compiler, '_comment', compiler.comment); + compiler.map = new utils.SourceMap.SourceMapGenerator(); + compiler.position = { line: 1, column: 1 }; + compiler.content = {}; + compiler.files = {}; - // if nothing has been parsed, we know `!` is at the start, - // so we need to wrap the result in a negation regex - if (parsed === '' && isNegated && this.options.nonegate !== true) { - this.bos.val = '(?!^(?:'; - this.append = ')$).*'; - val = ''; - } - return pos({ - type: 'not', - val: val - }); - }) + for (var key in exports) { + define(compiler, key, exports[key]); + } +} - /** - * Dot: "." - */ +/** + * Update position. + * + * @param {String} str + */ - .capture('dot', function() { - var parsed = this.parsed; - var pos = this.position(); - var m = this.match(/^\.+/); - if (!m) return; +exports.updatePosition = function(str) { + var lines = str.match(/\n/g); + if (lines) this.position.line += lines.length; + var i = str.lastIndexOf('\n'); + this.position.column = ~i ? str.length - i : this.position.column + str.length; +}; - var val = m[0]; - this.state.dot = val === '.' && (parsed === '' || parsed.slice(-1) === '/'); +/** + * Emit `str` with `position`. + * + * @param {String} str + * @param {Object} [pos] + * @return {String} + */ - return pos({ - type: 'dot', - dotfiles: this.state.dot, - val: val - }); - }) +exports.emit = function(str, node) { + var position = node.position || {}; + var source = position.source; + if (source) { + if (position.filepath) { + source = utils.unixify(position.filepath); + } - /** - * Plus: "+" - */ + this.map.addMapping({ + source: source, + generated: { + line: this.position.line, + column: Math.max(this.position.column - 1, 0) + }, + original: { + line: position.start.line, + column: position.start.column - 1 + } + }); - .capture('plus', /^\+(?!\()/) + if (position.content) { + this.addContent(source, position); + } + if (position.filepath) { + this.addFile(source, position); + } - /** - * Question mark: "?" - */ + this.updatePosition(str); + this.output += str; + } + return str; +}; - .capture('qmark', function() { - var parsed = this.parsed; - var pos = this.position(); - var m = this.match(/^\?+(?!\()/); - if (!m) return; +/** + * Adds a file to the source map output if it has not already been added + * @param {String} `file` + * @param {Object} `pos` + */ - this.state.metachar = true; - this.state.qmark = true; +exports.addFile = function(file, position) { + if (typeof position.content !== 'string') return; + if (Object.prototype.hasOwnProperty.call(this.files, file)) return; + this.files[file] = position.content; +}; - return pos({ - type: 'qmark', - parsed: parsed, - val: m[0] - }); - }) +/** + * Adds a content source to the source map output if it has not already been added + * @param {String} `source` + * @param {Object} `position` + */ - /** - * Globstar: "**" - */ +exports.addContent = function(source, position) { + if (typeof position.content !== 'string') return; + if (Object.prototype.hasOwnProperty.call(this.content, source)) return; + this.map.setSourceContent(source, position.content); +}; - .capture('globstar', function() { - var parsed = this.parsed; - var pos = this.position(); - var m = this.match(/^\*{2}(?![*(])(?=[,)/]|$)/); - if (!m) return; +/** + * Applies any original source maps to the output and embeds the source file + * contents in the source map. + */ - var type = opts.noglobstar !== true ? 'globstar' : 'star'; - var node = pos({type: type, parsed: parsed}); - this.state.metachar = true; +exports.applySourceMaps = function() { + Object.keys(this.files).forEach(function(file) { + var content = this.files[file]; + this.map.setSourceContent(file, content); - while (this.input.slice(0, 4) === '/**/') { - this.input = this.input.slice(3); + if (this.options.inputSourcemaps === true) { + var originalMap = utils.sourceMapResolve.resolveSync(content, file, fs.readFileSync); + if (originalMap) { + var map = new utils.SourceMap.SourceMapConsumer(originalMap.map); + var relativeTo = originalMap.sourcesRelativeTo; + this.map.applySourceMap(map, file, utils.unixify(path.dirname(relativeTo))); } + } + }, this); +}; - node.isInside = { - brace: this.isInside('brace'), - paren: this.isInside('paren') - }; +/** + * Process comments, drops sourceMap comments. + * @param {Object} node + */ - if (type === 'globstar') { - this.state.globstar = true; - node.val = '**'; +exports.comment = function(node) { + if (/^# sourceMappingURL=/.test(node.comment)) { + return this.emit('', node.position); + } + return this._comment(node); +}; - } else { - this.state.star = true; - node.val = '*'; - } - return node; - }) +/***/ }), +/* 757 */ +/***/ (function(module, exports, __webpack_require__) { - /** - * Star: "*" - */ +"use strict"; - .capture('star', function() { - var pos = this.position(); - var starRe = /^(?:\*(?![*(])|[*]{3,}(?!\()|[*]{2}(?![(/]|$)|\*(?=\*\())/; - var m = this.match(starRe); - if (!m) return; - this.state.metachar = true; - this.state.star = true; - return pos({ - type: 'star', - val: m[0] - }); - }) +var use = __webpack_require__(735); +var util = __webpack_require__(234); +var Cache = __webpack_require__(758); +var define = __webpack_require__(723); +var debug = __webpack_require__(326)('snapdragon:parser'); +var Position = __webpack_require__(759); +var utils = __webpack_require__(737); - /** - * Slash: "/" - */ +/** + * Create a new `Parser` with the given `input` and `options`. + * @param {String} `input` + * @param {Object} `options` + * @api public + */ - .capture('slash', function() { - var pos = this.position(); - var m = this.match(/^\//); - if (!m) return; +function Parser(options) { + debug('initializing', __filename); + this.options = utils.extend({source: 'string'}, options); + this.init(this.options); + use(this); +} - this.state.slashes++; - return pos({ - type: 'slash', - val: m[0] - }); - }) +/** + * Prototype methods + */ - /** - * Backslash: "\\" - */ +Parser.prototype = { + constructor: Parser, - .capture('backslash', function() { - var pos = this.position(); - var m = this.match(/^\\(?![*+?(){}[\]'"])/); - if (!m) return; + init: function(options) { + this.orig = ''; + this.input = ''; + this.parsed = ''; - var val = m[0]; + this.column = 1; + this.line = 1; - if (this.isInside('bracket')) { - val = '\\'; - } else if (val.length > 1) { - val = '\\\\'; - } + this.regex = new Cache(); + this.errors = this.errors || []; + this.parsers = this.parsers || {}; + this.types = this.types || []; + this.sets = this.sets || {}; + this.fns = this.fns || []; + this.currentType = 'root'; - return pos({ - type: 'backslash', - val: val - }); - }) + var pos = this.position(); + this.bos = pos({type: 'bos', val: ''}); - /** - * Square: "[.]" - */ + this.ast = { + type: 'root', + errors: this.errors, + nodes: [this.bos] + }; - .capture('square', function() { - if (this.isInside('bracket')) return; - var pos = this.position(); - var m = this.match(/^\[([^!^\\])\]/); - if (!m) return; + define(this.bos, 'parent', this.ast); + this.nodes = [this.ast]; - return pos({ - type: 'square', - val: m[1] - }); - }) + this.count = 0; + this.setCount = 0; + this.stack = []; + }, - /** - * Brackets: "[...]" (basic, this can be overridden by other parsers) - */ + /** + * Throw a formatted error with the cursor column and `msg`. + * @param {String} `msg` Message to use in the Error. + */ - .capture('bracket', function() { - var pos = this.position(); - var m = this.match(/^(?:\[([!^]?)([^\]]+|\]-)(\]|[^*+?]+)|\[)/); - if (!m) return; + error: function(msg, node) { + var pos = node.position || {start: {column: 0, line: 0}}; + var line = pos.start.line; + var column = pos.start.column; + var source = this.options.source; - var val = m[0]; - var negated = m[1] ? '^' : ''; - var inner = (m[2] || '').replace(/\\\\+/, '\\\\'); - var close = m[3] || ''; + var message = source + ' : ' + msg; + var err = new Error(message); + err.source = source; + err.reason = msg; + err.pos = pos; - if (m[2] && inner.length < m[2].length) { - val = val.replace(/\\\\+/, '\\\\'); - } + if (this.options.silent) { + this.errors.push(err); + } else { + throw err; + } + }, - var esc = this.input.slice(0, 2); - if (inner === '' && esc === '\\]') { - inner += esc; - this.consume(2); + /** + * Define a non-enumberable property on the `Parser` instance. + * + * ```js + * parser.define('foo', 'bar'); + * ``` + * @name .define + * @param {String} `key` propery name + * @param {any} `val` property value + * @return {Object} Returns the Parser instance for chaining. + * @api public + */ - var str = this.input; - var idx = -1; - var ch; + define: function(key, val) { + define(this, key, val); + return this; + }, - while ((ch = str[++idx])) { - this.consume(1); - if (ch === ']') { - close = ch; - break; - } - inner += ch; - } - } + /** + * Mark position and patch `node.position`. + */ - return pos({ - type: 'bracket', - val: val, - escaped: close !== ']', - negated: negated, - inner: inner, - close: close - }); - }) + position: function() { + var start = { line: this.line, column: this.column }; + var self = this; - /** - * Text - */ + return function(node) { + define(node, 'position', new Position(start, self)); + return node; + }; + }, - .capture('text', function() { - if (this.isInside('bracket')) return; - var pos = this.position(); - var m = this.match(not); - if (!m || !m[0]) return; + /** + * Set parser `name` with the given `fn` + * @param {String} `name` + * @param {Function} `fn` + * @api public + */ - return pos({ - type: 'text', - val: m[0] - }); - }); + set: function(type, fn) { + if (this.types.indexOf(type) === -1) { + this.types.push(type); + } + this.parsers[type] = fn.bind(this); + return this; + }, /** - * Allow custom parsers to be passed on options + * Get parser `name` + * @param {String} `name` + * @api public */ - if (options && typeof options.parsers === 'function') { - options.parsers(nanomatch.parser); - } -}; + get: function(name) { + return this.parsers[name]; + }, -/** - * Advance to the next non-escaped character - */ + /** + * Push a `token` onto the `type` stack. + * + * @param {String} `type` + * @return {Object} `token` + * @api public + */ -function advanceTo(input, endChar) { - var ch = input.charAt(0); - var tok = { len: 1, val: '', esc: '' }; - var idx = 0; + push: function(type, token) { + this.sets[type] = this.sets[type] || []; + this.count++; + this.stack.push(token); + return this.sets[type].push(token); + }, - function advance() { - if (ch !== '\\') { - tok.esc += '\\' + ch; - tok.val += ch; - } + /** + * Pop a token off of the `type` stack + * @param {String} `type` + * @returns {Object} Returns a token + * @api public + */ - ch = input.charAt(++idx); - tok.len++; + pop: function(type) { + this.sets[type] = this.sets[type] || []; + this.count--; + this.stack.pop(); + return this.sets[type].pop(); + }, - if (ch === '\\') { - advance(); - advance(); - } - } + /** + * Return true if inside a `stack` node. Types are `braces`, `parens` or `brackets`. + * + * @param {String} `type` + * @return {Boolean} + * @api public + */ - while (ch && ch !== endChar) { - advance(); - } - return tok; -} + isInside: function(type) { + this.sets[type] = this.sets[type] || []; + return this.sets[type].length > 0; + }, -/** - * Create text regex - */ + /** + * Return true if `node` is the given `type`. + * + * ```js + * parser.isType(node, 'brace'); + * ``` + * @param {Object} `node` + * @param {String} `type` + * @return {Boolean} + * @api public + */ -function createTextRegex(pattern) { - if (cached) return cached; - var opts = {contains: true, strictClose: false}; - var not = regexNot.create(pattern, opts); - var re = toRegex('^(?:[*]\\((?=.)|' + not + ')', opts); - return (cached = re); -} + isType: function(node, type) { + return node && node.type === type; + }, -/** - * Expose negation string - */ + /** + * Get the previous AST node + * @return {Object} + */ -module.exports.not = NOT_REGEX; + prev: function(n) { + return this.stack.length > 0 + ? utils.last(this.stack, n) + : utils.last(this.nodes, n); + }, + + /** + * Update line and column based on `str`. + */ + + consume: function(len) { + this.input = this.input.substr(len); + }, + /** + * Update column based on `str`. + */ -/***/ }), -/* 730 */ -/***/ (function(module, exports, __webpack_require__) { + updatePosition: function(str, len) { + var lines = str.match(/\n/g); + if (lines) this.line += lines.length; + var i = str.lastIndexOf('\n'); + this.column = ~i ? len - i : this.column + len; + this.parsed += str; + this.consume(len); + }, -"use strict"; -/*! - * is-odd - * - * Copyright (c) 2015-2017, Jon Schlinkert. - * Released under the MIT License. - */ + /** + * Match `regex`, return captures, and update the cursor position by `match[0]` length. + * @param {RegExp} `regex` + * @return {Object} + */ + match: function(regex) { + var m = regex.exec(this.input); + if (m) { + this.updatePosition(m[0], m[0].length); + return m; + } + }, + /** + * Capture `type` with the given regex. + * @param {String} `type` + * @param {RegExp} `regex` + * @return {Function} + */ -var isNumber = __webpack_require__(731); + capture: function(type, regex) { + if (typeof regex === 'function') { + return this.set.apply(this, arguments); + } -module.exports = function isOdd(i) { - if (!isNumber(i)) { - throw new TypeError('is-odd expects a number.'); - } - if (Number(i) !== Math.floor(i)) { - throw new RangeError('is-odd expects an integer.'); - } - return !!(~~i & 1); -}; + this.regex.set(type, regex); + this.set(type, function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(regex); + if (!m || !m[0]) return; + var prev = this.prev(); + var node = pos({ + type: type, + val: m[0], + parsed: parsed, + rest: this.input + }); -/***/ }), -/* 731 */ -/***/ (function(module, exports, __webpack_require__) { + if (m[1]) { + node.inner = m[1]; + } -"use strict"; -/*! - * is-number - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. - */ + define(node, 'inside', this.stack.length > 0); + define(node, 'parent', prev); + prev.nodes.push(node); + }.bind(this)); + return this; + }, + /** + * Create a parser with open and close for parens, + * brackets or braces + */ + capturePair: function(type, openRegex, closeRegex, fn) { + this.sets[type] = this.sets[type] || []; -module.exports = function isNumber(num) { - var type = typeof num; + /** + * Open + */ - if (type === 'string' || num instanceof String) { - // an empty string would be coerced to true with the below logic - if (!num.trim()) return false; - } else if (type !== 'number' && !(num instanceof Number)) { - return false; - } + this.set(type + '.open', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(openRegex); + if (!m || !m[0]) return; - return (num - num + 1) >= 0; -}; + var val = m[0]; + this.setCount++; + this.specialChars = true; + var open = pos({ + type: type + '.open', + val: val, + rest: this.input + }); + if (typeof m[1] !== 'undefined') { + open.inner = m[1]; + } -/***/ }), -/* 732 */ -/***/ (function(module, exports, __webpack_require__) { + var prev = this.prev(); + var node = pos({ + type: type, + nodes: [open] + }); -module.exports = new (__webpack_require__(733))(); + define(node, 'rest', this.input); + define(node, 'parsed', parsed); + define(node, 'prefix', m[1]); + define(node, 'parent', prev); + define(open, 'parent', node); + if (typeof fn === 'function') { + fn.call(this, open, node); + } -/***/ }), -/* 733 */ -/***/ (function(module, exports, __webpack_require__) { + this.push(type, node); + prev.nodes.push(node); + }); -"use strict"; -/*! - * fragment-cache - * - * Copyright (c) 2016-2017, Jon Schlinkert. - * Released under the MIT License. - */ + /** + * Close + */ + this.set(type + '.close', function() { + var pos = this.position(); + var m = this.match(closeRegex); + if (!m || !m[0]) return; + var parent = this.pop(type); + var node = pos({ + type: type + '.close', + rest: this.input, + suffix: m[1], + val: m[0] + }); -var MapCache = __webpack_require__(720); + if (!this.isType(parent, type)) { + if (this.options.strict) { + throw new Error('missing opening "' + type + '"'); + } -/** - * Create a new `FragmentCache` with an optional object to use for `caches`. - * - * ```js - * var fragment = new FragmentCache(); - * ``` - * @name FragmentCache - * @param {String} `cacheName` - * @return {Object} Returns the [map-cache][] instance. - * @api public - */ + this.setCount--; + node.escaped = true; + return node; + } -function FragmentCache(caches) { - this.caches = caches || {}; -} + if (node.suffix === '\\') { + parent.escaped = true; + node.escaped = true; + } -/** - * Prototype - */ + parent.nodes.push(node); + define(node, 'parent', parent); + }); -FragmentCache.prototype = { + return this; + }, /** - * Get cache `name` from the `fragment.caches` object. Creates a new - * `MapCache` if it doesn't already exist. - * - * ```js - * var cache = fragment.cache('files'); - * console.log(fragment.caches.hasOwnProperty('files')); - * //=> true - * ``` - * @name .cache - * @param {String} `cacheName` - * @return {Object} Returns the [map-cache][] instance. - * @api public + * Capture end-of-string */ - cache: function(cacheName) { - return this.caches[cacheName] || (this.caches[cacheName] = new MapCache()); - }, + eos: function() { + var pos = this.position(); + if (this.input) return; + var prev = this.prev(); - /** - * Set a value for property `key` on cache `name` - * - * ```js - * fragment.set('files', 'somefile.js', new File({path: 'somefile.js'})); - * ``` - * @name .set - * @param {String} `name` - * @param {String} `key` Property name to set - * @param {any} `val` The value of `key` - * @return {Object} The cache instance for chaining - * @api public - */ + while (prev.type !== 'root' && !prev.visited) { + if (this.options.strict === true) { + throw new SyntaxError('invalid syntax:' + util.inspect(prev, null, 2)); + } - set: function(cacheName, key, val) { - var cache = this.cache(cacheName); - cache.set(key, val); - return cache; + if (!hasDelims(prev)) { + prev.parent.escaped = true; + prev.escaped = true; + } + + visit(prev, function(node) { + if (!hasDelims(node.parent)) { + node.parent.escaped = true; + node.escaped = true; + } + }); + + prev = prev.parent; + } + + var tok = pos({ + type: 'eos', + val: this.append || '' + }); + + define(tok, 'parent', this.ast); + return tok; }, /** - * Returns true if a non-undefined value is set for `key` on fragment cache `name`. - * - * ```js - * var cache = fragment.cache('files'); - * cache.set('somefile.js'); - * - * console.log(cache.has('somefile.js')); - * //=> true - * - * console.log(cache.has('some-other-file.js')); - * //=> false - * ``` - * @name .has - * @param {String} `name` Cache name - * @param {String} `key` Optionally specify a property to check for on cache `name` - * @return {Boolean} - * @api public + * Run parsers to advance the cursor position */ - has: function(cacheName, key) { - return typeof this.get(cacheName, key) !== 'undefined'; + next: function() { + var parsed = this.parsed; + var len = this.types.length; + var idx = -1; + var tok; + + while (++idx < len) { + if ((tok = this.parsers[this.types[idx]].call(this))) { + define(tok, 'rest', this.input); + define(tok, 'parsed', parsed); + this.last = tok; + return tok; + } + } }, /** - * Get `name`, or if specified, the value of `key`. Invokes the [cache]() method, - * so that cache `name` will be created it doesn't already exist. If `key` is not passed, - * the entire cache (`name`) is returned. - * - * ```js - * var Vinyl = require('vinyl'); - * var cache = fragment.cache('files'); - * cache.set('somefile.js', new Vinyl({path: 'somefile.js'})); - * console.log(cache.get('somefile.js')); - * //=> - * ``` - * @name .get - * @param {String} `name` - * @return {Object} Returns cache `name`, or the value of `key` if specified - * @api public + * Parse the given string. + * @return {Array} */ - get: function(name, key) { - var cache = this.cache(name); - if (typeof key === 'string') { - return cache.get(key); + parse: function(input) { + if (typeof input !== 'string') { + throw new TypeError('expected a string'); } - return cache; - } -}; - -/** - * Expose `FragmentCache` - */ -exports = module.exports = FragmentCache; + this.init(this.options); + this.orig = input; + this.input = input; + var self = this; + function parse() { + // check input before calling `.next()` + input = self.input; -/***/ }), -/* 734 */ -/***/ (function(module, exports, __webpack_require__) { + // get the next AST ndoe + var node = self.next(); + if (node) { + var prev = self.prev(); + if (prev) { + define(node, 'parent', prev); + if (prev.nodes) { + prev.nodes.push(node); + } + } -"use strict"; + if (self.sets.hasOwnProperty(prev.type)) { + self.currentType = prev.type; + } + } + // if we got here but input is not changed, throw an error + if (self.input && input === self.input) { + throw new Error('no parsers registered for: "' + self.input.slice(0, 5) + '"'); + } + } -var utils = module.exports; -var path = __webpack_require__(4); + while (this.input) parse(); + if (this.stack.length && this.options.strict) { + var node = this.stack.pop(); + throw this.error('missing opening ' + node.type + ': "' + this.orig + '"'); + } -/** - * Module dependencies - */ + var eos = this.eos(); + var tok = this.prev(); + if (tok.type !== 'eos') { + this.ast.nodes.push(eos); + } -var isWindows = __webpack_require__(735)(); -var Snapdragon = __webpack_require__(654); -utils.define = __webpack_require__(736); -utils.diff = __webpack_require__(737); -utils.extend = __webpack_require__(726); -utils.pick = __webpack_require__(738); -utils.typeOf = __webpack_require__(620); -utils.unique = __webpack_require__(630); + return this.ast; + } +}; /** - * Returns true if the given value is effectively an empty string + * Visit `node` with the given `fn` */ -utils.isEmptyString = function(val) { - return String(val) === '' || String(val) === './'; -}; +function visit(node, fn) { + if (!node.visited) { + define(node, 'visited', true); + return node.nodes ? mapVisit(node.nodes, fn) : fn(node); + } + return node; +} /** - * Returns true if the platform is windows, or `path.sep` is `\\`. - * This is defined as a function to allow `path.sep` to be set in unit tests, - * or by the user, if there is a reason to do so. - * @return {Boolean} + * Map visit over array of `nodes`. */ -utils.isWindows = function() { - return path.sep === '\\' || isWindows === true; -}; +function mapVisit(nodes, fn) { + var len = nodes.length; + var idx = -1; + while (++idx < len) { + visit(nodes[idx], fn); + } +} -/** - * Return the last element from an array - */ +function hasOpen(node) { + return node.nodes && node.nodes[0].type === (node.type + '.open'); +} -utils.last = function(arr, n) { - return arr[arr.length - (n || 1)]; -}; +function hasClose(node) { + return node.nodes && utils.last(node.nodes).type === (node.type + '.close'); +} + +function hasDelims(node) { + return hasOpen(node) && hasClose(node); +} /** - * Get the `Snapdragon` instance to use + * Expose `Parser` */ -utils.instantiate = function(ast, options) { - var snapdragon; - // if an instance was created by `.parse`, use that instance - if (utils.typeOf(ast) === 'object' && ast.snapdragon) { - snapdragon = ast.snapdragon; - // if the user supplies an instance on options, use that instance - } else if (utils.typeOf(options) === 'object' && options.snapdragon) { - snapdragon = options.snapdragon; - // create a new instance - } else { - snapdragon = new Snapdragon(options); - } +module.exports = Parser; - utils.define(snapdragon, 'parse', function(str, options) { - var parsed = Snapdragon.prototype.parse.call(this, str, options); - parsed.input = str; - // escape unmatched brace/bracket/parens - var last = this.parser.stack.pop(); - if (last && this.options.strictErrors !== true) { - var open = last.nodes[0]; - var inner = last.nodes[1]; - if (last.type === 'bracket') { - if (inner.val.charAt(0) === '[') { - inner.val = '\\' + inner.val; - } +/***/ }), +/* 758 */ +/***/ (function(module, exports, __webpack_require__) { - } else { - open.val = '\\' + open.val; - var sibling = open.parent.nodes[1]; - if (sibling.type === 'star') { - sibling.loose = true; - } - } - } +"use strict"; +/*! + * map-cache + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ - // add non-enumerable parser reference - utils.define(parsed, 'parser', this.parser); - return parsed; - }); - return snapdragon; -}; + +var hasOwn = Object.prototype.hasOwnProperty; /** - * Create the key to use for memoization. The key is generated - * by iterating over the options and concatenating key-value pairs - * to the pattern string. + * Expose `MapCache` */ -utils.createKey = function(pattern, options) { - if (typeof options === 'undefined') { - return pattern; - } - var key = pattern; - for (var prop in options) { - if (options.hasOwnProperty(prop)) { - key += ';' + prop + '=' + String(options[prop]); - } - } - return key; -}; +module.exports = MapCache; /** - * Cast `val` to an array - * @return {Array} + * Creates a cache object to store key/value pairs. + * + * ```js + * var cache = new MapCache(); + * ``` + * + * @api public */ -utils.arrayify = function(val) { - if (typeof val === 'string') return [val]; - return val ? (Array.isArray(val) ? val : [val]) : []; -}; +function MapCache(data) { + this.__data__ = data || {}; +} /** - * Return true if `val` is a non-empty string + * Adds `value` to `key` on the cache. + * + * ```js + * cache.set('foo', 'bar'); + * ``` + * + * @param {String} `key` The key of the value to cache. + * @param {*} `value` The value to cache. + * @returns {Object} Returns the `Cache` object for chaining. + * @api public */ -utils.isString = function(val) { - return typeof val === 'string'; +MapCache.prototype.set = function mapSet(key, value) { + if (key !== '__proto__') { + this.__data__[key] = value; + } + return this; }; /** - * Return true if `val` is a non-empty string + * Gets the cached value for `key`. + * + * ```js + * cache.get('foo'); + * //=> 'bar' + * ``` + * + * @param {String} `key` The key of the value to get. + * @returns {*} Returns the cached value. + * @api public */ -utils.isRegex = function(val) { - return utils.typeOf(val) === 'regexp'; +MapCache.prototype.get = function mapGet(key) { + return key === '__proto__' ? undefined : this.__data__[key]; }; /** - * Return true if `val` is a non-empty string + * Checks if a cached value for `key` exists. + * + * ```js + * cache.has('foo'); + * //=> true + * ``` + * + * @param {String} `key` The key of the entry to check. + * @returns {Boolean} Returns `true` if an entry for `key` exists, else `false`. + * @api public */ -utils.isObject = function(val) { - return utils.typeOf(val) === 'object'; +MapCache.prototype.has = function mapHas(key) { + return key !== '__proto__' && hasOwn.call(this.__data__, key); }; /** - * Escape regex characters in the given string + * Removes `key` and its value from the cache. + * + * ```js + * cache.del('foo'); + * ``` + * @title .del + * @param {String} `key` The key of the value to remove. + * @returns {Boolean} Returns `true` if the entry was removed successfully, else `false`. + * @api public */ -utils.escapeRegex = function(str) { - return str.replace(/[-[\]{}()^$|*+?.\\/\s]/g, '\\$&'); +MapCache.prototype.del = function mapDelete(key) { + return this.has(key) && delete this.__data__[key]; }; -/** - * Combines duplicate characters in the provided `input` string. - * @param {String} `input` - * @returns {String} - */ -utils.combineDupes = function(input, patterns) { - patterns = utils.arrayify(patterns).join('|').split('|'); - patterns = patterns.map(function(s) { - return s.replace(/\\?([+*\\/])/g, '\\$1'); - }); - var substr = patterns.join('|'); - var regex = new RegExp('(' + substr + ')(?=\\1)', 'g'); - return input.replace(regex, ''); -}; +/***/ }), +/* 759 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * Returns true if the given `str` has special characters - */ +"use strict"; -utils.hasSpecialChars = function(str) { - return /(?:(?:(^|\/)[!.])|[*?+()|[\]{}]|[+@]\()/.test(str); -}; + +var define = __webpack_require__(723); /** - * Normalize slashes in the given filepath. - * - * @param {String} `filepath` - * @return {String} + * Store position for a node */ -utils.toPosixPath = function(str) { - return str.replace(/\\+/g, '/'); +module.exports = function Position(start, parser) { + this.start = start; + this.end = { line: parser.line, column: parser.column }; + define(this, 'content', parser.orig); + define(this, 'source', parser.options.source); }; -/** - * Strip backslashes before special characters in a string. - * - * @param {String} `str` - * @return {String} - */ -utils.unescape = function(str) { - return utils.toPosixPath(str.replace(/\\(?=[*+?!.])/g, '')); -}; +/***/ }), +/* 760 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * Strip the drive letter from a windows filepath - * @param {String} `fp` - * @return {String} - */ +"use strict"; -utils.stripDrive = function(fp) { - return utils.isWindows() ? fp.replace(/^[a-z]:[\\/]+?/i, '/') : fp; -}; -/** - * Strip the prefix from a filepath - * @param {String} `fp` - * @return {String} - */ +var isExtendable = __webpack_require__(761); +var assignSymbols = __webpack_require__(664); -utils.stripPrefix = function(str) { - if (str.charAt(0) === '.' && (str.charAt(1) === '/' || str.charAt(1) === '\\')) { - return str.slice(2); +module.exports = Object.assign || function(obj/*, objects*/) { + if (obj === null || typeof obj === 'undefined') { + throw new TypeError('Cannot convert undefined or null to object'); } - return str; + if (!isObject(obj)) { + obj = {}; + } + for (var i = 1; i < arguments.length; i++) { + var val = arguments[i]; + if (isString(val)) { + val = toObject(val); + } + if (isObject(val)) { + assign(obj, val); + assignSymbols(obj, val); + } + } + return obj; }; -/** - * Returns true if `str` is a common character that doesn't need - * to be processed to be used for matching. - * @param {String} `str` - * @return {Boolean} - */ +function assign(a, b) { + for (var key in b) { + if (hasOwn(b, key)) { + a[key] = b[key]; + } + } +} -utils.isSimpleChar = function(str) { - return str.trim() === '' || str === '.'; -}; +function isString(val) { + return (val && typeof val === 'string'); +} + +function toObject(str) { + var obj = {}; + for (var i in str) { + obj[i] = str[i]; + } + return obj; +} + +function isObject(val) { + return (val && typeof val === 'object') || isExtendable(val); +} /** - * Returns true if the given str is an escaped or - * unescaped path character + * Returns true if the given `key` is an own property of `obj`. */ -utils.isSlash = function(str) { - return str === '/' || str === '\\/' || str === '\\' || str === '\\\\'; -}; +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} -/** - * Returns a function that returns true if the given - * pattern matches or contains a `filepath` +function isEnum(obj, key) { + return Object.prototype.propertyIsEnumerable.call(obj, key); +} + + +/***/ }), +/* 761 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * is-extendable * - * @param {String} `pattern` - * @return {Function} + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. */ -utils.matchPath = function(pattern, options) { - return (options && options.contains) - ? utils.containsPattern(pattern, options) - : utils.equalsPattern(pattern, options); -}; -/** - * Returns true if the given (original) filepath or unixified path are equal - * to the given pattern. - */ -utils._equals = function(filepath, unixPath, pattern) { - return pattern === filepath || pattern === unixPath; +var isPlainObject = __webpack_require__(663); + +module.exports = function isExtendable(val) { + return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); }; -/** - * Returns true if the given (original) filepath or unixified path contain - * the given pattern. - */ -utils._contains = function(filepath, unixPath, pattern) { - return filepath.indexOf(pattern) !== -1 || unixPath.indexOf(pattern) !== -1; -}; +/***/ }), +/* 762 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * Returns a function that returns true if the given - * pattern is the same as a given `filepath` - * - * @param {String} `pattern` - * @return {Function} - */ +"use strict"; -utils.equalsPattern = function(pattern, options) { - var unixify = utils.unixify(options); - options = options || {}; - return function fn(filepath) { - var equal = utils._equals(filepath, unixify(filepath), pattern); - if (equal === true || options.nocase !== true) { - return equal; - } - var lower = filepath.toLowerCase(); - return utils._equals(lower, unixify(lower), pattern); - }; +var nanomatch = __webpack_require__(763); +var extglob = __webpack_require__(777); + +module.exports = function(snapdragon) { + var compilers = snapdragon.compiler.compilers; + var opts = snapdragon.options; + + // register nanomatch compilers + snapdragon.use(nanomatch.compilers); + + // get references to some specific nanomatch compilers before they + // are overridden by the extglob and/or custom compilers + var escape = compilers.escape; + var qmark = compilers.qmark; + var slash = compilers.slash; + var star = compilers.star; + var text = compilers.text; + var plus = compilers.plus; + var dot = compilers.dot; + + // register extglob compilers or escape exglobs if disabled + if (opts.extglob === false || opts.noext === true) { + snapdragon.compiler.use(escapeExtglobs); + } else { + snapdragon.use(extglob.compilers); + } + + snapdragon.use(function() { + this.options.star = this.options.star || function(/*node*/) { + return '[^\\\\/]*?'; + }; + }); + + // custom micromatch compilers + snapdragon.compiler + + // reset referenced compiler + .set('dot', dot) + .set('escape', escape) + .set('plus', plus) + .set('slash', slash) + .set('qmark', qmark) + .set('star', star) + .set('text', text); }; -/** - * Returns a function that returns true if the given - * pattern contains a `filepath` - * - * @param {String} `pattern` - * @return {Function} - */ +function escapeExtglobs(compiler) { + compiler.set('paren', function(node) { + var val = ''; + visit(node, function(tok) { + if (tok.val) val += (/^\W/.test(tok.val) ? '\\' : '') + tok.val; + }); + return this.emit(val, node); + }); -utils.containsPattern = function(pattern, options) { - var unixify = utils.unixify(options); - options = options || {}; + /** + * Visit `node` with the given `fn` + */ - return function(filepath) { - var contains = utils._contains(filepath, unixify(filepath), pattern); - if (contains === true || options.nocase !== true) { - return contains; + function visit(node, fn) { + return node.nodes ? mapVisit(node.nodes, fn) : fn(node); + } + + /** + * Map visit over array of `nodes`. + */ + + function mapVisit(nodes, fn) { + var len = nodes.length; + var idx = -1; + while (++idx < len) { + visit(nodes[idx], fn); } - var lower = filepath.toLowerCase(); - return utils._contains(lower, unixify(lower), pattern); - }; -}; + } +} + + +/***/ }), +/* 763 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + /** - * Returns a function that returns true if the given - * regex matches the `filename` of a file path. - * - * @param {RegExp} `re` Matching regex - * @return {Function} + * Module dependencies */ -utils.matchBasename = function(re) { - return function(filepath) { - return re.test(filepath) || re.test(path.basename(filepath)); - }; -}; +var util = __webpack_require__(234); +var toRegex = __webpack_require__(648); +var extend = __webpack_require__(764); /** - * Returns the given value unchanced. - * @return {any} + * Local dependencies */ -utils.identity = function(val) { - return val; -}; +var compilers = __webpack_require__(766); +var parsers = __webpack_require__(767); +var cache = __webpack_require__(770); +var utils = __webpack_require__(772); +var MAX_LENGTH = 1024 * 64; /** - * Determines the filepath to return based on the provided options. - * @return {any} + * The main function takes a list of strings and one or more + * glob patterns to use for matching. + * + * ```js + * var nm = require('nanomatch'); + * nm(list, patterns[, options]); + * + * console.log(nm(['a.js', 'a.txt'], ['*.js'])); + * //=> [ 'a.js' ] + * ``` + * @param {Array} `list` A list of strings to match + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array} Returns an array of matches + * @summary false + * @api public */ -utils.value = function(str, unixify, options) { - if (options && options.unixify === false) { - return str; +function nanomatch(list, patterns, options) { + patterns = utils.arrayify(patterns); + list = utils.arrayify(list); + + var len = patterns.length; + if (list.length === 0 || len === 0) { + return []; } - if (options && typeof options.unixify === 'function') { - return options.unixify(str); + + if (len === 1) { + return nanomatch.match(list, patterns[0], options); } - return unixify(str); -}; -/** - * Returns a function that normalizes slashes in a string to forward - * slashes, strips `./` from beginning of paths, and optionally unescapes - * special characters. - * @return {Function} - */ + var negated = false; + var omit = []; + var keep = []; + var idx = -1; -utils.unixify = function(options) { - var opts = options || {}; - return function(filepath) { - if (opts.stripPrefix !== false) { - filepath = utils.stripPrefix(filepath); - } - if (opts.unescape === true) { - filepath = utils.unescape(filepath); + while (++idx < len) { + var pattern = patterns[idx]; + + if (typeof pattern === 'string' && pattern.charCodeAt(0) === 33 /* ! */) { + omit.push.apply(omit, nanomatch.match(list, pattern.slice(1), options)); + negated = true; + } else { + keep.push.apply(keep, nanomatch.match(list, pattern, options)); } - if (opts.unixify === true || utils.isWindows()) { - filepath = utils.toPosixPath(filepath); + } + + // minimatch.match parity + if (negated && keep.length === 0) { + if (options && options.unixify === false) { + keep = list.slice(); + } else { + var unixify = utils.unixify(options); + for (var i = 0; i < list.length; i++) { + keep.push(unixify(list[i])); + } } - return filepath; - }; -}; + } + var matches = utils.diff(keep, omit); + if (!options || options.nodupes !== false) { + return utils.unique(matches); + } -/***/ }), -/* 735 */ -/***/ (function(module, exports, __webpack_require__) { + return matches; +} -var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! - * is-windows +/** + * Similar to the main function, but `pattern` must be a string. * - * Copyright © 2015-2018, Jon Schlinkert. - * Released under the MIT License. - */ - -(function(factory) { - if (exports && typeof exports === 'object' && typeof module !== 'undefined') { - module.exports = factory(); - } else if (true) { - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else {} -})(function() { - 'use strict'; - return function isWindows() { - return process && (process.platform === 'win32' || /^(msys|cygwin)$/.test(process.env.OSTYPE)); - }; -}); - - -/***/ }), -/* 736 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/*! - * define-property + * ```js + * var nm = require('nanomatch'); + * nm.match(list, pattern[, options]); * - * Copyright (c) 2015-2018, Jon Schlinkert. - * Released under the MIT License. + * console.log(nm.match(['a.a', 'a.aa', 'a.b', 'a.c'], '*.a')); + * //=> ['a.a', 'a.aa'] + * ``` + * @param {Array} `list` Array of strings to match + * @param {String} `pattern` Glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array} Returns an array of matches + * @api public */ +nanomatch.match = function(list, pattern, options) { + if (Array.isArray(pattern)) { + throw new TypeError('expected pattern to be a string'); + } + var unixify = utils.unixify(options); + var isMatch = memoize('match', pattern, options, nanomatch.matcher); + var matches = []; -var isobject = __webpack_require__(618); -var isDescriptor = __webpack_require__(619); -var define = (typeof Reflect !== 'undefined' && Reflect.defineProperty) - ? Reflect.defineProperty - : Object.defineProperty; + list = utils.arrayify(list); + var len = list.length; + var idx = -1; -module.exports = function defineProperty(obj, key, val) { - if (!isobject(obj) && typeof obj !== 'function' && !Array.isArray(obj)) { - throw new TypeError('expected an object, function, or array'); + while (++idx < len) { + var ele = list[idx]; + if (ele === pattern || isMatch(ele)) { + matches.push(utils.value(ele, unixify, options)); + } + } + + // if no options were passed, uniquify results and return + if (typeof options === 'undefined') { + return utils.unique(matches); } - if (typeof key !== 'string') { - throw new TypeError('expected "key" to be a string'); + if (matches.length === 0) { + if (options.failglob === true) { + throw new Error('no matches found for "' + pattern + '"'); + } + if (options.nonull === true || options.nullglob === true) { + return [options.unescape ? utils.unescape(pattern) : pattern]; + } } - if (isDescriptor(val)) { - define(obj, key, val); - return obj; + // if `opts.ignore` was defined, diff ignored list + if (options.ignore) { + matches = nanomatch.not(matches, options.ignore, options); } - define(obj, key, { - configurable: true, - enumerable: false, - writable: true, - value: val - }); - - return obj; + return options.nodupes !== false ? utils.unique(matches) : matches; }; - -/***/ }), -/* 737 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/*! - * arr-diff +/** + * Returns true if the specified `string` matches the given glob `pattern`. * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. + * ```js + * var nm = require('nanomatch'); + * nm.isMatch(string, pattern[, options]); + * + * console.log(nm.isMatch('a.a', '*.a')); + * //=> true + * console.log(nm.isMatch('a.b', '*.a')); + * //=> false + * ``` + * @param {String} `string` String to match + * @param {String} `pattern` Glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if the string matches the glob pattern. + * @api public */ +nanomatch.isMatch = function(str, pattern, options) { + if (typeof str !== 'string') { + throw new TypeError('expected a string: "' + util.inspect(str) + '"'); + } + if (utils.isEmptyString(str) || utils.isEmptyString(pattern)) { + return false; + } -module.exports = function diff(arr/*, arrays*/) { - var len = arguments.length; - var idx = 0; - while (++idx < len) { - arr = diffArray(arr, arguments[idx]); + var equals = utils.equalsPattern(options); + if (equals(str)) { + return true; } - return arr; + + var isMatch = memoize('isMatch', pattern, options, nanomatch.matcher); + return isMatch(str); }; -function diffArray(one, two) { - if (!Array.isArray(two)) { - return one.slice(); +/** + * Returns true if some of the elements in the given `list` match any of the + * given glob `patterns`. + * + * ```js + * var nm = require('nanomatch'); + * nm.some(list, patterns[, options]); + * + * console.log(nm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * // true + * console.log(nm.some(['foo.js'], ['*.js', '!foo.js'])); + * // false + * ``` + * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +nanomatch.some = function(list, patterns, options) { + if (typeof list === 'string') { + list = [list]; } - var tlen = two.length - var olen = one.length; - var idx = -1; - var arr = []; + for (var i = 0; i < list.length; i++) { + if (nanomatch(list[i], patterns, options).length === 1) { + return true; + } + } - while (++idx < olen) { - var ele = one[idx]; + return false; +}; - var hasEle = false; - for (var i = 0; i < tlen; i++) { - var val = two[i]; +/** + * Returns true if every element in the given `list` matches + * at least one of the given glob `patterns`. + * + * ```js + * var nm = require('nanomatch'); + * nm.every(list, patterns[, options]); + * + * console.log(nm.every('foo.js', ['foo.js'])); + * // true + * console.log(nm.every(['foo.js', 'bar.js'], ['*.js'])); + * // true + * console.log(nm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * // false + * console.log(nm.every(['foo.js'], ['*.js', '!foo.js'])); + * // false + * ``` + * @param {String|Array} `list` The string or array of strings to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ - if (ele === val) { - hasEle = true; - break; - } - } +nanomatch.every = function(list, patterns, options) { + if (typeof list === 'string') { + list = [list]; + } - if (hasEle === false) { - arr.push(ele); + for (var i = 0; i < list.length; i++) { + if (nanomatch(list[i], patterns, options).length !== 1) { + return false; } } - return arr; -} + return true; +}; -/***/ }), -/* 738 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/*! - * object.pick +/** + * Returns true if **any** of the given glob `patterns` + * match the specified `string`. * - * Copyright (c) 2014-2015 Jon Schlinkert, contributors. - * Licensed under the MIT License + * ```js + * var nm = require('nanomatch'); + * nm.any(string, patterns[, options]); + * + * console.log(nm.any('a.a', ['b.*', '*.a'])); + * //=> true + * console.log(nm.any('a.a', 'b.*')); + * //=> false + * ``` + * @param {String|Array} `str` The string to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public */ +nanomatch.any = function(str, patterns, options) { + if (typeof str !== 'string') { + throw new TypeError('expected a string: "' + util.inspect(str) + '"'); + } + if (utils.isEmptyString(str) || utils.isEmptyString(patterns)) { + return false; + } -var isObject = __webpack_require__(618); - -module.exports = function pick(obj, keys) { - if (!isObject(obj) && typeof obj !== 'function') { - return {}; + if (typeof patterns === 'string') { + patterns = [patterns]; } - var res = {}; - if (typeof keys === 'string') { - if (keys in obj) { - res[keys] = obj[keys]; + for (var i = 0; i < patterns.length; i++) { + if (nanomatch.isMatch(str, patterns[i], options)) { + return true; } - return res; } + return false; +}; - var len = keys.length; - var idx = -1; +/** + * Returns true if **all** of the given `patterns` + * match the specified string. + * + * ```js + * var nm = require('nanomatch'); + * nm.all(string, patterns[, options]); + * + * console.log(nm.all('foo.js', ['foo.js'])); + * // true + * + * console.log(nm.all('foo.js', ['*.js', '!foo.js'])); + * // false + * + * console.log(nm.all('foo.js', ['*.js', 'foo.js'])); + * // true + * + * console.log(nm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); + * // true + * ``` + * @param {String|Array} `str` The string to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ - while (++idx < len) { - var key = keys[idx]; - if (key in obj) { - res[key] = obj[key]; +nanomatch.all = function(str, patterns, options) { + if (typeof str !== 'string') { + throw new TypeError('expected a string: "' + util.inspect(str) + '"'); + } + + if (typeof patterns === 'string') { + patterns = [patterns]; + } + + for (var i = 0; i < patterns.length; i++) { + if (!nanomatch.isMatch(str, patterns[i], options)) { + return false; } } - return res; + return true; }; +/** + * Returns a list of strings that _**do not match any**_ of the given `patterns`. + * + * ```js + * var nm = require('nanomatch'); + * nm.not(list, patterns[, options]); + * + * console.log(nm.not(['a.a', 'b.b', 'c.c'], '*.a')); + * //=> ['b.b', 'c.c'] + * ``` + * @param {Array} `list` Array of strings to match. + * @param {String|Array} `patterns` One or more glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array} Returns an array of strings that **do not match** the given patterns. + * @api public + */ + +nanomatch.not = function(list, patterns, options) { + var opts = extend({}, options); + var ignore = opts.ignore; + delete opts.ignore; -/***/ }), -/* 739 */ -/***/ (function(module, exports, __webpack_require__) { + list = utils.arrayify(list); -"use strict"; + var matches = utils.diff(list, nanomatch(list, patterns, opts)); + if (ignore) { + matches = utils.diff(matches, nanomatch(list, ignore)); + } + return opts.nodupes !== false ? utils.unique(matches) : matches; +}; /** - * Module dependencies + * Returns true if the given `string` contains the given pattern. Similar + * to [.isMatch](#isMatch) but the pattern can match any part of the string. + * + * ```js + * var nm = require('nanomatch'); + * nm.contains(string, pattern[, options]); + * + * console.log(nm.contains('aa/bb/cc', '*b')); + * //=> true + * console.log(nm.contains('aa/bb/cc', '*d')); + * //=> false + * ``` + * @param {String} `str` The string to match. + * @param {String|Array} `patterns` Glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if the patter matches any part of `str`. + * @api public */ -var extend = __webpack_require__(669); -var unique = __webpack_require__(630); -var toRegex = __webpack_require__(610); +nanomatch.contains = function(str, patterns, options) { + if (typeof str !== 'string') { + throw new TypeError('expected a string: "' + util.inspect(str) + '"'); + } + + if (typeof patterns === 'string') { + if (utils.isEmptyString(str) || utils.isEmptyString(patterns)) { + return false; + } + + var equals = utils.equalsPattern(patterns, options); + if (equals(str)) { + return true; + } + var contains = utils.containsPattern(patterns, options); + if (contains(str)) { + return true; + } + } + + var opts = extend({}, options, {contains: true}); + return nanomatch.any(str, patterns, opts); +}; /** - * Local dependencies + * Returns true if the given pattern and options should enable + * the `matchBase` option. + * @return {Boolean} + * @api private */ -var compilers = __webpack_require__(740); -var parsers = __webpack_require__(746); -var Extglob = __webpack_require__(749); -var utils = __webpack_require__(748); -var MAX_LENGTH = 1024 * 64; +nanomatch.matchBase = function(pattern, options) { + if (pattern && pattern.indexOf('/') !== -1 || !options) return false; + return options.basename === true || options.matchBase === true; +}; /** - * Convert the given `extglob` pattern into a regex-compatible string. Returns - * an object with the compiled result and the parsed AST. + * Filter the keys of the given object with the given `glob` pattern + * and `options`. Does not attempt to match nested keys. If you need this feature, + * use [glob-object][] instead. * * ```js - * var extglob = require('extglob'); - * console.log(extglob('*.!(*a)')); - * //=> '(?!\\.)[^/]*?\\.(?!(?!\\.)[^/]*?a\\b).*?' + * var nm = require('nanomatch'); + * nm.matchKeys(object, patterns[, options]); + * + * var obj = { aa: 'a', ab: 'b', ac: 'c' }; + * console.log(nm.matchKeys(obj, '*b')); + * //=> { ab: 'b' } * ``` - * @param {String} `pattern` - * @param {Object} `options` - * @return {String} + * @param {Object} `object` The object with keys to filter. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Object} Returns an object with only keys that match the given patterns. * @api public */ -function extglob(pattern, options) { - return extglob.create(pattern, options).output; -} +nanomatch.matchKeys = function(obj, patterns, options) { + if (!utils.isObject(obj)) { + throw new TypeError('expected the first argument to be an object'); + } + var keys = nanomatch(Object.keys(obj), patterns, options); + return utils.pick(obj, keys); +}; /** - * Takes an array of strings and an extglob pattern and returns a new - * array that contains only the strings that match the pattern. + * Returns a memoized matcher function from the given glob `pattern` and `options`. + * The returned function takes a string to match as its only argument and returns + * true if the string is a match. * * ```js - * var extglob = require('extglob'); - * console.log(extglob.match(['a.a', 'a.b', 'a.c'], '*.!(*a)')); - * //=> ['a.b', 'a.c'] + * var nm = require('nanomatch'); + * nm.matcher(pattern[, options]); + * + * var isMatch = nm.matcher('*.!(*a)'); + * console.log(isMatch('a.a')); + * //=> false + * console.log(isMatch('a.b')); + * //=> true * ``` - * @param {Array} `list` Array of strings to match - * @param {String} `pattern` Extglob pattern - * @param {Object} `options` - * @return {Array} Returns an array of matches + * @param {String} `pattern` Glob pattern + * @param {Object} `options` See available [options](#options) for changing how matches are performed. + * @return {Function} Returns a matcher function. * @api public */ -extglob.match = function(list, pattern, options) { - if (typeof pattern !== 'string') { - throw new TypeError('expected pattern to be a string'); +nanomatch.matcher = function matcher(pattern, options) { + if (utils.isEmptyString(pattern)) { + return function() { + return false; + }; } - list = utils.arrayify(list); - var isMatch = extglob.matcher(pattern, options); - var len = list.length; - var idx = -1; - var matches = []; + if (Array.isArray(pattern)) { + return compose(pattern, options, matcher); + } - while (++idx < len) { - var ele = list[idx]; + // if pattern is a regex + if (pattern instanceof RegExp) { + return test(pattern); + } - if (isMatch(ele)) { - matches.push(ele); + // if pattern is invalid + if (!utils.isString(pattern)) { + throw new TypeError('expected pattern to be an array, string or regex'); + } + + // if pattern is a non-glob string + if (!utils.hasSpecialChars(pattern)) { + if (options && options.nocase === true) { + pattern = pattern.toLowerCase(); } + return utils.matchPath(pattern, options); } - // if no options were passed, uniquify results and return - if (typeof options === 'undefined') { - return unique(matches); + // if pattern is a glob string + var re = nanomatch.makeRe(pattern, options); + + // if `options.matchBase` or `options.basename` is defined + if (nanomatch.matchBase(pattern, options)) { + return utils.matchBasename(re, options); } - if (matches.length === 0) { - if (options.failglob === true) { - throw new Error('no matches found for "' + pattern + '"'); - } - if (options.nonull === true || options.nullglob === true) { - return [pattern.split('\\').join('')]; - } + function test(regex) { + var equals = utils.equalsPattern(options); + var unixify = utils.unixify(options); + + return function(str) { + if (equals(str)) { + return true; + } + + if (regex.test(unixify(str))) { + return true; + } + return false; + }; } - return options.nodupes !== false ? unique(matches) : matches; + // create matcher function + var matcherFn = test(re); + // set result object from compiler on matcher function, + // as a non-enumerable property. useful for debugging + utils.define(matcherFn, 'result', re.result); + return matcherFn; }; /** - * Returns true if the specified `string` matches the given - * extglob `pattern`. + * Returns an array of matches captured by `pattern` in `string, or + * `null` if the pattern did not match. * * ```js - * var extglob = require('extglob'); + * var nm = require('nanomatch'); + * nm.capture(pattern, string[, options]); * - * console.log(extglob.isMatch('a.a', '*.!(*a)')); - * //=> false - * console.log(extglob.isMatch('a.b', '*.!(*a)')); - * //=> true + * console.log(nm.capture('test/*.js', 'test/foo.js')); + * //=> ['foo'] + * console.log(nm.capture('test/*.js', 'foo/bar.css')); + * //=> null * ``` + * @param {String} `pattern` Glob pattern to use for matching. * @param {String} `string` String to match - * @param {String} `pattern` Extglob pattern - * @param {String} `options` - * @return {Boolean} + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns an array of captures if the string matches the glob pattern, otherwise `null`. + * @api public + */ + +nanomatch.capture = function(pattern, str, options) { + var re = nanomatch.makeRe(pattern, extend({capture: true}, options)); + var unixify = utils.unixify(options); + + function match() { + return function(string) { + var match = re.exec(unixify(string)); + if (!match) { + return null; + } + + return match.slice(1); + }; + } + + var capture = memoize('capture', pattern, options, match); + return capture(str); +}; + +/** + * Create a regular expression from the given glob `pattern`. + * + * ```js + * var nm = require('nanomatch'); + * nm.makeRe(pattern[, options]); + * + * console.log(nm.makeRe('*.js')); + * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ + * ``` + * @param {String} `pattern` A glob pattern to convert to regex. + * @param {Object} `options` See available [options](#options) for changing how matches are performed. + * @return {RegExp} Returns a regex created from the given pattern. * @api public */ -extglob.isMatch = function(str, pattern, options) { - if (typeof pattern !== 'string') { - throw new TypeError('expected pattern to be a string'); +nanomatch.makeRe = function(pattern, options) { + if (pattern instanceof RegExp) { + return pattern; } - if (typeof str !== 'string') { - throw new TypeError('expected a string'); + if (typeof pattern !== 'string') { + throw new TypeError('expected pattern to be a string'); } - if (pattern === str) { - return true; + if (pattern.length > MAX_LENGTH) { + throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters'); } - if (pattern === '' || pattern === ' ' || pattern === '.') { - return pattern === str; + function makeRe() { + var opts = utils.extend({wrap: false}, options); + var result = nanomatch.create(pattern, opts); + var regex = toRegex(result.output, opts); + utils.define(regex, 'result', result); + return regex; } - var isMatch = utils.memoize('isMatch', pattern, options, extglob.matcher); - return isMatch(str); + return memoize('makeRe', pattern, options, makeRe); }; /** - * Returns true if the given `string` contains the given pattern. Similar to `.isMatch` but - * the pattern can match any part of the string. + * Parses the given glob `pattern` and returns an object with the compiled `output` + * and optional source `map`. * * ```js - * var extglob = require('extglob'); - * console.log(extglob.contains('aa/bb/cc', '*b')); - * //=> true - * console.log(extglob.contains('aa/bb/cc', '*d')); - * //=> false + * var nm = require('nanomatch'); + * nm.create(pattern[, options]); + * + * console.log(nm.create('abc/*.js')); + * // { options: { source: 'string', sourcemap: true }, + * // state: {}, + * // compilers: + * // { ... }, + * // output: '(\\.[\\\\\\/])?abc\\/(?!\\.)(?=.)[^\\/]*?\\.js', + * // ast: + * // { type: 'root', + * // errors: [], + * // nodes: + * // [ ... ], + * // dot: false, + * // input: 'abc/*.js' }, + * // parsingErrors: [], + * // map: + * // { version: 3, + * // sources: [ 'string' ], + * // names: [], + * // mappings: 'AAAA,GAAG,EAAC,kBAAC,EAAC,EAAE', + * // sourcesContent: [ 'abc/*.js' ] }, + * // position: { line: 1, column: 28 }, + * // content: {}, + * // files: {}, + * // idx: 6 } * ``` - * @param {String} `str` The string to match. - * @param {String} `pattern` Glob pattern to use for matching. - * @param {Object} `options` - * @return {Boolean} Returns true if the patter matches any part of `str`. + * @param {String} `pattern` Glob pattern to parse and compile. + * @param {Object} `options` Any [options](#options) to change how parsing and compiling is performed. + * @return {Object} Returns an object with the parsed AST, compiled string and optional source map. * @api public */ -extglob.contains = function(str, pattern, options) { - if (typeof str !== 'string') { +nanomatch.create = function(pattern, options) { + if (typeof pattern !== 'string') { throw new TypeError('expected a string'); } - - if (pattern === '' || pattern === ' ' || pattern === '.') { - return pattern === str; + function create() { + return nanomatch.compile(nanomatch.parse(pattern, options), options); } - - var opts = extend({}, options, {contains: true}); - opts.strictClose = false; - opts.strictOpen = false; - return extglob.isMatch(str, pattern, opts); + return memoize('create', pattern, options, create); }; /** - * Takes an extglob pattern and returns a matcher function. The returned - * function takes the string to match as its only argument. + * Parse the given `str` with the given `options`. * * ```js - * var extglob = require('extglob'); - * var isMatch = extglob.matcher('*.!(*a)'); + * var nm = require('nanomatch'); + * nm.parse(pattern[, options]); * - * console.log(isMatch('a.a')); - * //=> false - * console.log(isMatch('a.b')); - * //=> true + * var ast = nm.parse('a/{b,c}/d'); + * console.log(ast); + * // { type: 'root', + * // errors: [], + * // input: 'a/{b,c}/d', + * // nodes: + * // [ { type: 'bos', val: '' }, + * // { type: 'text', val: 'a/' }, + * // { type: 'brace', + * // nodes: + * // [ { type: 'brace.open', val: '{' }, + * // { type: 'text', val: 'b,c' }, + * // { type: 'brace.close', val: '}' } ] }, + * // { type: 'text', val: '/d' }, + * // { type: 'eos', val: '' } ] } * ``` - * @param {String} `pattern` Extglob pattern - * @param {String} `options` - * @return {Boolean} + * @param {String} `str` + * @param {Object} `options` + * @return {Object} Returns an AST * @api public */ -extglob.matcher = function(pattern, options) { +nanomatch.parse = function(pattern, options) { if (typeof pattern !== 'string') { - throw new TypeError('expected pattern to be a string'); + throw new TypeError('expected a string'); } - function matcher() { - var re = extglob.makeRe(pattern, options); - return function(str) { - return re.test(str); - }; + function parse() { + var snapdragon = utils.instantiate(null, options); + parsers(snapdragon, options); + + var ast = snapdragon.parse(pattern, options); + utils.define(ast, 'snapdragon', snapdragon); + ast.input = pattern; + return ast; } - return utils.memoize('matcher', pattern, options, matcher); + return memoize('parse', pattern, options, parse); }; /** - * Convert the given `extglob` pattern into a regex-compatible string. Returns - * an object with the compiled result and the parsed AST. + * Compile the given `ast` or string with the given `options`. * * ```js - * var extglob = require('extglob'); - * console.log(extglob.create('*.!(*a)').output); - * //=> '(?!\\.)[^/]*?\\.(?!(?!\\.)[^/]*?a\\b).*?' + * var nm = require('nanomatch'); + * nm.compile(ast[, options]); + * + * var ast = nm.parse('a/{b,c}/d'); + * console.log(nm.compile(ast)); + * // { options: { source: 'string' }, + * // state: {}, + * // compilers: + * // { eos: [Function], + * // noop: [Function], + * // bos: [Function], + * // brace: [Function], + * // 'brace.open': [Function], + * // text: [Function], + * // 'brace.close': [Function] }, + * // output: [ 'a/(b|c)/d' ], + * // ast: + * // { ... }, + * // parsingErrors: [] } * ``` - * @param {String} `str` + * @param {Object|String} `ast` * @param {Object} `options` - * @return {String} + * @return {Object} Returns an object that has an `output` property with the compiled string. * @api public */ -extglob.create = function(pattern, options) { - if (typeof pattern !== 'string') { - throw new TypeError('expected pattern to be a string'); +nanomatch.compile = function(ast, options) { + if (typeof ast === 'string') { + ast = nanomatch.parse(ast, options); } - function create() { - var ext = new Extglob(options); - var ast = ext.parse(pattern, options); - return ext.compile(ast, options); + function compile() { + var snapdragon = utils.instantiate(ast, options); + compilers(snapdragon, options); + return snapdragon.compile(ast, options); } - return utils.memoize('create', pattern, options, create); + return memoize('compile', ast.input, options, compile); }; /** - * Returns an array of matches captured by `pattern` in `string`, or `null` - * if the pattern did not match. + * Clear the regex cache. * * ```js - * var extglob = require('extglob'); - * extglob.capture(pattern, string[, options]); - * - * console.log(extglob.capture('test/*.js', 'test/foo.js')); - * //=> ['foo'] - * console.log(extglob.capture('test/*.js', 'foo/bar.css')); - * //=> null + * nm.clearCache(); * ``` - * @param {String} `pattern` Glob pattern to use for matching. - * @param {String} `string` String to match - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Boolean} Returns an array of captures if the string matches the glob pattern, otherwise `null`. * @api public */ -extglob.capture = function(pattern, str, options) { - var re = extglob.makeRe(pattern, extend({capture: true}, options)); +nanomatch.clearCache = function() { + nanomatch.cache.__data__ = {}; +}; - function match() { - return function(string) { - var match = re.exec(string); - if (!match) { - return null; +/** + * Compose a matcher function with the given patterns. + * This allows matcher functions to be compiled once and + * called multiple times. + */ + +function compose(patterns, options, matcher) { + var matchers; + + return memoize('compose', String(patterns), options, function() { + return function(file) { + // delay composition until it's invoked the first time, + // after that it won't be called again + if (!matchers) { + matchers = []; + for (var i = 0; i < patterns.length; i++) { + matchers.push(matcher(patterns[i], options)); + } } - return match.slice(1); + var len = matchers.length; + while (len--) { + if (matchers[len](file) === true) { + return true; + } + } + return false; }; - } - - var capture = utils.memoize('capture', pattern, options, match); - return capture(str); -}; + }); +} /** - * Create a regular expression from the given `pattern` and `options`. - * - * ```js - * var extglob = require('extglob'); - * var re = extglob.makeRe('*.!(*a)'); - * console.log(re); - * //=> /^[^\/]*?\.(?![^\/]*?a)[^\/]*?$/ - * ``` - * @param {String} `pattern` The pattern to convert to regex. - * @param {Object} `options` - * @return {RegExp} - * @api public + * Memoize a generated regex or function. A unique key is generated + * from the `type` (usually method name), the `pattern`, and + * user-defined options. */ -extglob.makeRe = function(pattern, options) { - if (pattern instanceof RegExp) { - return pattern; - } +function memoize(type, pattern, options, fn) { + var key = utils.createKey(type + '=' + pattern, options); - if (typeof pattern !== 'string') { - throw new TypeError('expected pattern to be a string'); + if (options && options.cache === false) { + return fn(pattern, options); } - if (pattern.length > MAX_LENGTH) { - throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters'); + if (cache.has(type, key)) { + return cache.get(type, key); } - function makeRe() { - var opts = extend({strictErrors: false}, options); - if (opts.strictErrors === true) opts.strict = true; - var res = extglob.create(pattern, opts); - return toRegex(res.output, opts); - } + var val = fn(pattern, options); + cache.set(type, key, val); + return val; +} - var regex = utils.memoize('makeRe', pattern, options, makeRe); - if (regex.source.length > MAX_LENGTH) { - throw new SyntaxError('potentially malicious regex detected'); - } +/** + * Expose compiler, parser and cache on `nanomatch` + */ - return regex; -}; +nanomatch.compilers = compilers; +nanomatch.parsers = parsers; +nanomatch.cache = cache; /** - * Cache + * Expose `nanomatch` + * @type {Function} */ -extglob.cache = utils.cache; -extglob.clearCache = function() { - extglob.cache.__data__ = {}; +module.exports = nanomatch; + + +/***/ }), +/* 764 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var isExtendable = __webpack_require__(765); +var assignSymbols = __webpack_require__(664); + +module.exports = Object.assign || function(obj/*, objects*/) { + if (obj === null || typeof obj === 'undefined') { + throw new TypeError('Cannot convert undefined or null to object'); + } + if (!isObject(obj)) { + obj = {}; + } + for (var i = 1; i < arguments.length; i++) { + var val = arguments[i]; + if (isString(val)) { + val = toObject(val); + } + if (isObject(val)) { + assign(obj, val); + assignSymbols(obj, val); + } + } + return obj; }; -/** - * Expose `Extglob` constructor, parsers and compilers - */ +function assign(a, b) { + for (var key in b) { + if (hasOwn(b, key)) { + a[key] = b[key]; + } + } +} -extglob.Extglob = Extglob; -extglob.compilers = compilers; -extglob.parsers = parsers; +function isString(val) { + return (val && typeof val === 'string'); +} + +function toObject(str) { + var obj = {}; + for (var i in str) { + obj[i] = str[i]; + } + return obj; +} + +function isObject(val) { + return (val && typeof val === 'object') || isExtendable(val); +} /** - * Expose `extglob` - * @type {Function} + * Returns true if the given `key` is an own property of `obj`. */ -module.exports = extglob; +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +function isEnum(obj, key) { + return Object.prototype.propertyIsEnumerable.call(obj, key); +} /***/ }), -/* 740 */ +/* 765 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +/*! + * is-extendable + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var isPlainObject = __webpack_require__(663); + +module.exports = function isExtendable(val) { + return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); +}; + + +/***/ }), +/* 766 */ +/***/ (function(module, exports, __webpack_require__) { +"use strict"; -var brackets = __webpack_require__(741); /** - * Extglob compilers - */ +* Nanomatch compilers +*/ + +module.exports = function(nanomatch, options) { + function slash() { + if (options && typeof options.slash === 'string') { + return options.slash; + } + if (options && typeof options.slash === 'function') { + return options.slash.call(nanomatch); + } + return '\\\\/'; + } -module.exports = function(extglob) { function star() { - if (typeof extglob.options.star === 'function') { - return extglob.options.star.apply(this, arguments); + if (options && typeof options.star === 'string') { + return options.star; } - if (typeof extglob.options.star === 'string') { - return extglob.options.star; + if (options && typeof options.star === 'function') { + return options.star.call(nanomatch); } - return '.*?'; + return '[^' + slash() + ']*?'; } - /** - * Use `expand-brackets` compilers - */ + var ast = nanomatch.ast = nanomatch.parser.ast; + ast.state = nanomatch.parser.state; + nanomatch.compiler.state = ast.state; + nanomatch.compiler + + /** + * Negation / escaping + */ + + .set('not', function(node) { + var prev = this.prev(); + if (this.options.nonegate === true || prev.type !== 'bos') { + return this.emit('\\' + node.val, node); + } + return this.emit(node.val, node); + }) + .set('escape', function(node) { + if (this.options.unescape && /^[-\w_.]/.test(node.val)) { + return this.emit(node.val, node); + } + return this.emit('\\' + node.val, node); + }) + .set('quoted', function(node) { + return this.emit(node.val, node); + }) + + /** + * Regex + */ + + .set('dollar', function(node) { + if (node.parent.type === 'bracket') { + return this.emit(node.val, node); + } + return this.emit('\\' + node.val, node); + }) + + /** + * Dot: "." + */ + + .set('dot', function(node) { + if (node.dotfiles === true) this.dotfiles = true; + return this.emit('\\' + node.val, node); + }) + + /** + * Slashes: "/" and "\" + */ + + .set('backslash', function(node) { + return this.emit(node.val, node); + }) + .set('slash', function(node, nodes, i) { + var val = '[' + slash() + ']'; + var parent = node.parent; + var prev = this.prev(); + + // set "node.hasSlash" to true on all ancestor parens nodes + while (parent.type === 'paren' && !parent.hasSlash) { + parent.hasSlash = true; + parent = parent.parent; + } + + if (prev.addQmark) { + val += '?'; + } + + // word boundary + if (node.rest.slice(0, 2) === '\\b') { + return this.emit(val, node); + } + + // globstars + if (node.parsed === '**' || node.parsed === './**') { + this.output = '(?:' + this.output; + return this.emit(val + ')?', node); + } + + // negation + if (node.parsed === '!**' && this.options.nonegate !== true) { + return this.emit(val + '?\\b', node); + } + return this.emit(val, node); + }) + + /** + * Square brackets + */ + + .set('bracket', function(node) { + var close = node.close; + var open = !node.escaped ? '[' : '\\['; + var negated = node.negated; + var inner = node.inner; + var val = node.val; + + if (node.escaped === true) { + inner = inner.replace(/\\?(\W)/g, '\\$1'); + negated = ''; + } - extglob.use(brackets.compilers); - extglob.compiler + if (inner === ']-') { + inner = '\\]\\-'; + } - /** - * Escaped: "\\*" - */ + if (negated && inner.indexOf('.') === -1) { + inner += '.'; + } + if (negated && inner.indexOf('/') === -1) { + inner += '/'; + } - .set('escape', function(node) { - return this.emit(node.val, node); + val = open + negated + inner + close; + return this.emit(val, node); }) /** - * Dot: "." + * Square: "[.]" (only matches a single character in brackets) */ - .set('dot', function(node) { - return this.emit('\\' + node.val, node); + .set('square', function(node) { + var val = (/^\W/.test(node.val) ? '\\' : '') + node.val; + return this.emit(val, node); }) /** @@ -79209,19 +79915,19 @@ module.exports = function(extglob) { */ .set('qmark', function(node) { - var val = '[^\\\\/.]'; var prev = this.prev(); + // don't use "slash" variable so that we always avoid + // matching backslashes and slashes with a qmark + var val = '[^.\\\\/]'; + if (this.options.dot || (prev.type !== 'bos' && prev.type !== 'slash')) { + val = '[^\\\\/]'; + } if (node.parsed.slice(-1) === '(') { var ch = node.rest.charAt(0); - if (ch !== '!' && ch !== '=' && ch !== ':') { - return this.emit(val, node); + if (ch === '!' || ch === '=' || ch === ':') { + return this.emit(node.val, node); } - return this.emit(node.val, node); - } - - if (prev.type === 'text' && prev.val) { - return this.emit(val, node); } if (node.val.length > 1) { @@ -79231,7 +79937,7 @@ module.exports = function(extglob) { }) /** - * Plus: "+" + * Plus */ .set('plus', function(node) { @@ -79239,10 +79945,10 @@ module.exports = function(extglob) { if (prev === ']' || prev === ')') { return this.emit(node.val, node); } - var ch = this.output.slice(-1); if (!this.output || (/[?*+]/.test(ch) && node.parent.type !== 'bracket')) { return this.emit('\\+', node); } + var ch = this.output.slice(-1); if (/\w/.test(ch) && !node.inside) { return this.emit('+\\+?', node); } @@ -79250,76 +79956,111 @@ module.exports = function(extglob) { }) /** - * Star: "*" + * globstar: '**' */ - .set('star', function(node) { + .set('globstar', function(node, nodes, i) { + if (!this.output) { + this.state.leadingGlobstar = true; + } + var prev = this.prev(); - var prefix = prev.type !== 'text' && prev.type !== 'escape' - ? '(?!\\.)' - : ''; + var before = this.prev(2); + var next = this.next(); + var after = this.next(2); + var type = prev.type; + var val = node.val; - return this.emit(prefix + star.call(this, node), node); + if (prev.type === 'slash' && next.type === 'slash') { + if (before.type === 'text') { + this.output += '?'; + + if (after.type !== 'text') { + this.output += '\\b'; + } + } + } + + var parsed = node.parsed; + if (parsed.charAt(0) === '!') { + parsed = parsed.slice(1); + } + + var isInside = node.isInside.paren || node.isInside.brace; + if (parsed && type !== 'slash' && type !== 'bos' && !isInside) { + val = star(); + } else { + val = this.options.dot !== true + ? '(?:(?!(?:[' + slash() + ']|^)\\.).)*?' + : '(?:(?!(?:[' + slash() + ']|^)(?:\\.{1,2})($|[' + slash() + ']))(?!\\.{2}).)*?'; + } + + if ((type === 'slash' || type === 'bos') && this.options.dot !== true) { + val = '(?!\\.)' + val; + } + + if (prev.type === 'slash' && next.type === 'slash' && before.type !== 'text') { + if (after.type === 'text' || after.type === 'star') { + node.addQmark = true; + } + } + + if (this.options.capture) { + val = '(' + val + ')'; + } + + return this.emit(val, node); }) /** - * Parens + * Star: "*" */ - .set('paren', function(node) { - return this.mapVisit(node.nodes); - }) - .set('paren.open', function(node) { - var capture = this.options.capture ? '(' : ''; + .set('star', function(node, nodes, i) { + var prior = nodes[i - 2] || {}; + var prev = this.prev(); + var next = this.next(); + var type = prev.type; - switch (node.parent.prefix) { - case '!': - case '^': - return this.emit(capture + '(?:(?!(?:', node); - case '*': - case '+': - case '?': - case '@': - return this.emit(capture + '(?:', node); - default: { - var val = node.val; - if (this.options.bash === true) { - val = '\\' + val; - } else if (!this.options.capture && val === '(' && node.parent.rest[0] !== '?') { - val += '?:'; - } + function isStart(n) { + return n.type === 'bos' || n.type === 'slash'; + } - return this.emit(val, node); - } + if (this.output === '' && this.options.contains !== true) { + this.output = '(?![' + slash() + '])'; } - }) - .set('paren.close', function(node) { - var capture = this.options.capture ? ')' : ''; - switch (node.prefix) { - case '!': - case '^': - var prefix = /^(\)|$)/.test(node.rest) ? '$' : ''; - var str = star.call(this, node); + if (type === 'bracket' && this.options.bash === false) { + var str = next && next.type === 'bracket' ? star() : '*?'; + if (!prev.nodes || prev.nodes[1].type !== 'posix') { + return this.emit(str, node); + } + } - // if the extglob has a slash explicitly defined, we know the user wants - // to match slashes, so we need to ensure the "star" regex allows for it - if (node.parent.hasSlash && !this.options.star && this.options.slash !== false) { - str = '.*?'; - } + var prefix = !this.dotfiles && type !== 'text' && type !== 'escape' + ? (this.options.dot ? '(?!(?:^|[' + slash() + '])\\.{1,2}(?:$|[' + slash() + ']))' : '(?!\\.)') + : ''; - return this.emit(prefix + ('))' + str + ')') + capture, node); - case '*': - case '+': - case '?': - return this.emit(')' + node.prefix + capture, node); - case '@': - return this.emit(')' + capture, node); - default: { - var val = (this.options.bash === true ? '\\' : '') + ')'; - return this.emit(val, node); + if (isStart(prev) || (isStart(prior) && type === 'not')) { + if (prefix !== '(?!\\.)') { + prefix += '(?!(\\.{2}|\\.[' + slash() + ']))(?=.)'; + } else { + prefix += '(?=.)'; } + } else if (prefix === '(?!\\.)') { + prefix = ''; } + + if (prev.type === 'not' && prior.type === 'bos' && this.options.dot === true) { + this.output = '(?!\\.)' + this.output; + } + + var output = prefix + star(); + if (this.options.capture) { + output = '(' + output + ')'; + } + + return this.emit(output, node); }) /** @@ -79327,3369 +80068,3126 @@ module.exports = function(extglob) { */ .set('text', function(node) { - var val = node.val.replace(/[\[\]]/g, '\\$&'); + return this.emit(node.val, node); + }) + + /** + * End-of-string + */ + + .set('eos', function(node) { + var prev = this.prev(); + var val = node.val; + + this.output = '(?:\\.[' + slash() + '](?=.))?' + this.output; + if (this.state.metachar && prev.type !== 'qmark' && prev.type !== 'slash') { + val += (this.options.contains ? '[' + slash() + ']?' : '(?:[' + slash() + ']|$)'); + } + return this.emit(val, node); }); + + /** + * Allow custom compilers to be passed on options + */ + + if (options && typeof options.compilers === 'function') { + options.compilers(nanomatch.compiler); + } }; + /***/ }), -/* 741 */ +/* 767 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +var regexNot = __webpack_require__(665); +var toRegex = __webpack_require__(648); +var isOdd = __webpack_require__(768); + /** - * Local dependencies + * Characters to use in negation regex (we want to "not" match + * characters that are matched by other parsers) */ -var compilers = __webpack_require__(742); -var parsers = __webpack_require__(744); +var cached; +var NOT_REGEX = '[\\[!*+?$^"\'.\\\\/]+'; +var not = createTextRegex(NOT_REGEX); /** - * Module dependencies + * Nanomatch parsers */ -var debug = __webpack_require__(326)('expand-brackets'); -var extend = __webpack_require__(669); -var Snapdragon = __webpack_require__(654); -var toRegex = __webpack_require__(610); +module.exports = function(nanomatch, options) { + var parser = nanomatch.parser; + var opts = parser.options; -/** - * Parses the given POSIX character class `pattern` and returns a - * string that can be used for creating regular expressions for matching. - * - * @param {String} `pattern` - * @param {Object} `options` - * @return {Object} - * @api public - */ + parser.state = { + slashes: 0, + paths: [] + }; -function brackets(pattern, options) { - debug('initializing from <%s>', __filename); - var res = brackets.create(pattern, options); - return res.output; -} + parser.ast.state = parser.state; + parser -/** - * Takes an array of strings and a POSIX character class pattern, and returns a new - * array with only the strings that matched the pattern. - * - * ```js - * var brackets = require('expand-brackets'); - * console.log(brackets.match(['1', 'a', 'ab'], '[[:alpha:]]')); - * //=> ['a'] - * - * console.log(brackets.match(['1', 'a', 'ab'], '[[:alpha:]]+')); - * //=> ['a', 'ab'] - * ``` - * @param {Array} `arr` Array of strings to match - * @param {String} `pattern` POSIX character class pattern(s) - * @param {Object} `options` - * @return {Array} - * @api public - */ + /** + * Beginning-of-string + */ -brackets.match = function(arr, pattern, options) { - arr = [].concat(arr); - var opts = extend({}, options); - var isMatch = brackets.matcher(pattern, opts); - var len = arr.length; - var idx = -1; - var res = []; + .capture('prefix', function() { + if (this.parsed) return; + var m = this.match(/^\.[\\/]/); + if (!m) return; + this.state.strictOpen = !!this.options.strictOpen; + this.state.addPrefix = true; + }) - while (++idx < len) { - var ele = arr[idx]; - if (isMatch(ele)) { - res.push(ele); - } - } + /** + * Escape: "\\." + */ - if (res.length === 0) { - if (opts.failglob === true) { - throw new Error('no matches found for "' + pattern + '"'); - } + .capture('escape', function() { + if (this.isInside('bracket')) return; + var pos = this.position(); + var m = this.match(/^(?:\\(.)|([$^]))/); + if (!m) return; - if (opts.nonull === true || opts.nullglob === true) { - return [pattern.split('\\').join('')]; - } - } - return res; -}; + return pos({ + type: 'escape', + val: m[2] || m[1] + }); + }) -/** - * Returns true if the specified `string` matches the given - * brackets `pattern`. - * - * ```js - * var brackets = require('expand-brackets'); - * - * console.log(brackets.isMatch('a.a', '[[:alpha:]].[[:alpha:]]')); - * //=> true - * console.log(brackets.isMatch('1.2', '[[:alpha:]].[[:alpha:]]')); - * //=> false - * ``` - * @param {String} `string` String to match - * @param {String} `pattern` Poxis pattern - * @param {String} `options` - * @return {Boolean} - * @api public - */ + /** + * Quoted strings + */ -brackets.isMatch = function(str, pattern, options) { - return brackets.matcher(pattern, options)(str); -}; + .capture('quoted', function() { + var pos = this.position(); + var m = this.match(/^["']/); + if (!m) return; -/** - * Takes a POSIX character class pattern and returns a matcher function. The returned - * function takes the string to match as its only argument. - * - * ```js - * var brackets = require('expand-brackets'); - * var isMatch = brackets.matcher('[[:lower:]].[[:upper:]]'); - * - * console.log(isMatch('a.a')); - * //=> false - * console.log(isMatch('a.A')); - * //=> true - * ``` - * @param {String} `pattern` Poxis pattern - * @param {String} `options` - * @return {Boolean} - * @api public - */ + var quote = m[0]; + if (this.input.indexOf(quote) === -1) { + return pos({ + type: 'escape', + val: quote + }); + } -brackets.matcher = function(pattern, options) { - var re = brackets.makeRe(pattern, options); - return function(str) { - return re.test(str); - }; -}; + var tok = advanceTo(this.input, quote); + this.consume(tok.len); -/** - * Create a regular expression from the given `pattern`. - * - * ```js - * var brackets = require('expand-brackets'); - * var re = brackets.makeRe('[[:alpha:]]'); - * console.log(re); - * //=> /^(?:[a-zA-Z])$/ - * ``` - * @param {String} `pattern` The pattern to convert to regex. - * @param {Object} `options` - * @return {RegExp} - * @api public - */ + return pos({ + type: 'quoted', + val: tok.esc + }); + }) -brackets.makeRe = function(pattern, options) { - var res = brackets.create(pattern, options); - var opts = extend({strictErrors: false}, options); - return toRegex(res.output, opts); -}; + /** + * Negations: "!" + */ -/** - * Parses the given POSIX character class `pattern` and returns an object - * with the compiled `output` and optional source `map`. - * - * ```js - * var brackets = require('expand-brackets'); - * console.log(brackets('[[:alpha:]]')); - * // { options: { source: 'string' }, - * // input: '[[:alpha:]]', - * // state: {}, - * // compilers: - * // { eos: [Function], - * // noop: [Function], - * // bos: [Function], - * // not: [Function], - * // escape: [Function], - * // text: [Function], - * // posix: [Function], - * // bracket: [Function], - * // 'bracket.open': [Function], - * // 'bracket.inner': [Function], - * // 'bracket.literal': [Function], - * // 'bracket.close': [Function] }, - * // output: '[a-zA-Z]', - * // ast: - * // { type: 'root', - * // errors: [], - * // nodes: [ [Object], [Object], [Object] ] }, - * // parsingErrors: [] } - * ``` - * @param {String} `pattern` - * @param {Object} `options` - * @return {Object} - * @api public - */ + .capture('not', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(this.notRegex || /^!+/); + if (!m) return; + var val = m[0]; -brackets.create = function(pattern, options) { - var snapdragon = (options && options.snapdragon) || new Snapdragon(options); - compilers(snapdragon); - parsers(snapdragon); + var isNegated = isOdd(val.length); + if (parsed === '' && !isNegated) { + val = ''; + } - var ast = snapdragon.parse(pattern, options); - ast.input = pattern; - var res = snapdragon.compile(ast, options); - res.input = pattern; - return res; -}; + // if nothing has been parsed, we know `!` is at the start, + // so we need to wrap the result in a negation regex + if (parsed === '' && isNegated && this.options.nonegate !== true) { + this.bos.val = '(?!^(?:'; + this.append = ')$).*'; + val = ''; + } + return pos({ + type: 'not', + val: val + }); + }) -/** - * Expose `brackets` constructor, parsers and compilers - */ + /** + * Dot: "." + */ -brackets.compilers = compilers; -brackets.parsers = parsers; + .capture('dot', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(/^\.+/); + if (!m) return; + + var val = m[0]; + this.state.dot = val === '.' && (parsed === '' || parsed.slice(-1) === '/'); + + return pos({ + type: 'dot', + dotfiles: this.state.dot, + val: val + }); + }) + + /** + * Plus: "+" + */ + + .capture('plus', /^\+(?!\()/) + + /** + * Question mark: "?" + */ + + .capture('qmark', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(/^\?+(?!\()/); + if (!m) return; + + this.state.metachar = true; + this.state.qmark = true; + + return pos({ + type: 'qmark', + parsed: parsed, + val: m[0] + }); + }) -/** - * Expose `brackets` - * @type {Function} - */ + /** + * Globstar: "**" + */ -module.exports = brackets; + .capture('globstar', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(/^\*{2}(?![*(])(?=[,)/]|$)/); + if (!m) return; + var type = opts.noglobstar !== true ? 'globstar' : 'star'; + var node = pos({type: type, parsed: parsed}); + this.state.metachar = true; -/***/ }), -/* 742 */ -/***/ (function(module, exports, __webpack_require__) { + while (this.input.slice(0, 4) === '/**/') { + this.input = this.input.slice(3); + } -"use strict"; + node.isInside = { + brace: this.isInside('brace'), + paren: this.isInside('paren') + }; + if (type === 'globstar') { + this.state.globstar = true; + node.val = '**'; -var posix = __webpack_require__(743); + } else { + this.state.star = true; + node.val = '*'; + } -module.exports = function(brackets) { - brackets.compiler + return node; + }) /** - * Escaped characters + * Star: "*" */ - .set('escape', function(node) { - return this.emit('\\' + node.val.replace(/^\\/, ''), node); + .capture('star', function() { + var pos = this.position(); + var starRe = /^(?:\*(?![*(])|[*]{3,}(?!\()|[*]{2}(?![(/]|$)|\*(?=\*\())/; + var m = this.match(starRe); + if (!m) return; + + this.state.metachar = true; + this.state.star = true; + return pos({ + type: 'star', + val: m[0] + }); }) /** - * Text + * Slash: "/" */ - .set('text', function(node) { - return this.emit(node.val.replace(/([{}])/g, '\\$1'), node); + .capture('slash', function() { + var pos = this.position(); + var m = this.match(/^\//); + if (!m) return; + + this.state.slashes++; + return pos({ + type: 'slash', + val: m[0] + }); }) /** - * POSIX character classes + * Backslash: "\\" */ - .set('posix', function(node) { - if (node.val === '[::]') { - return this.emit('\\[::\\]', node); - } + .capture('backslash', function() { + var pos = this.position(); + var m = this.match(/^\\(?![*+?(){}[\]'"])/); + if (!m) return; - var val = posix[node.inner]; - if (typeof val === 'undefined') { - val = '[' + node.inner + ']'; + var val = m[0]; + + if (this.isInside('bracket')) { + val = '\\'; + } else if (val.length > 1) { + val = '\\\\'; } - return this.emit(val, node); + + return pos({ + type: 'backslash', + val: val + }); }) /** - * Non-posix brackets + * Square: "[.]" */ - .set('bracket', function(node) { - return this.mapVisit(node.nodes); - }) - .set('bracket.open', function(node) { - return this.emit(node.val, node); + .capture('square', function() { + if (this.isInside('bracket')) return; + var pos = this.position(); + var m = this.match(/^\[([^!^\\])\]/); + if (!m) return; + + return pos({ + type: 'square', + val: m[1] + }); }) - .set('bracket.inner', function(node) { - var inner = node.val; - if (inner === '[' || inner === ']') { - return this.emit('\\' + node.val, node); - } - if (inner === '^]') { - return this.emit('^\\]', node); - } - if (inner === '^') { - return this.emit('^', node); - } + /** + * Brackets: "[...]" (basic, this can be overridden by other parsers) + */ - if (/-/.test(inner) && !/(\d-\d|\w-\w)/.test(inner)) { - inner = inner.split('-').join('\\-'); - } + .capture('bracket', function() { + var pos = this.position(); + var m = this.match(/^(?:\[([!^]?)([^\]]+|\]-)(\]|[^*+?]+)|\[)/); + if (!m) return; - var isNegated = inner.charAt(0) === '^'; - // add slashes to negated brackets, per spec - if (isNegated && inner.indexOf('/') === -1) { - inner += '/'; + var val = m[0]; + var negated = m[1] ? '^' : ''; + var inner = (m[2] || '').replace(/\\\\+/, '\\\\'); + var close = m[3] || ''; + + if (m[2] && inner.length < m[2].length) { + val = val.replace(/\\\\+/, '\\\\'); } - if (isNegated && inner.indexOf('.') === -1) { - inner += '.'; + + var esc = this.input.slice(0, 2); + if (inner === '' && esc === '\\]') { + inner += esc; + this.consume(2); + + var str = this.input; + var idx = -1; + var ch; + + while ((ch = str[++idx])) { + this.consume(1); + if (ch === ']') { + close = ch; + break; + } + inner += ch; + } } - // don't unescape `0` (octal literal) - inner = inner.replace(/\\([1-9])/g, '$1'); - return this.emit(inner, node); + return pos({ + type: 'bracket', + val: val, + escaped: close !== ']', + negated: negated, + inner: inner, + close: close + }); }) - .set('bracket.close', function(node) { - var val = node.val.replace(/^\\/, ''); - if (node.parent.escaped === true) { - return this.emit('\\' + val, node); - } - return this.emit(val, node); + + /** + * Text + */ + + .capture('text', function() { + if (this.isInside('bracket')) return; + var pos = this.position(); + var m = this.match(not); + if (!m || !m[0]) return; + + return pos({ + type: 'text', + val: m[0] + }); }); + + /** + * Allow custom parsers to be passed on options + */ + + if (options && typeof options.parsers === 'function') { + options.parsers(nanomatch.parser); + } }; +/** + * Advance to the next non-escaped character + */ + +function advanceTo(input, endChar) { + var ch = input.charAt(0); + var tok = { len: 1, val: '', esc: '' }; + var idx = 0; + + function advance() { + if (ch !== '\\') { + tok.esc += '\\' + ch; + tok.val += ch; + } + + ch = input.charAt(++idx); + tok.len++; + + if (ch === '\\') { + advance(); + advance(); + } + } + + while (ch && ch !== endChar) { + advance(); + } + return tok; +} + +/** + * Create text regex + */ + +function createTextRegex(pattern) { + if (cached) return cached; + var opts = {contains: true, strictClose: false}; + var not = regexNot.create(pattern, opts); + var re = toRegex('^(?:[*]\\((?=.)|' + not + ')', opts); + return (cached = re); +} + +/** + * Expose negation string + */ + +module.exports.not = NOT_REGEX; + /***/ }), -/* 743 */ +/* 768 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +/*! + * is-odd + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ -/** - * POSIX character classes - */ -module.exports = { - alnum: 'a-zA-Z0-9', - alpha: 'a-zA-Z', - ascii: '\\x00-\\x7F', - blank: ' \\t', - cntrl: '\\x00-\\x1F\\x7F', - digit: '0-9', - graph: '\\x21-\\x7E', - lower: 'a-z', - print: '\\x20-\\x7E ', - punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~', - space: ' \\t\\r\\n\\v\\f', - upper: 'A-Z', - word: 'A-Za-z0-9_', - xdigit: 'A-Fa-f0-9' +var isNumber = __webpack_require__(769); + +module.exports = function isOdd(i) { + if (!isNumber(i)) { + throw new TypeError('is-odd expects a number.'); + } + if (Number(i) !== Math.floor(i)) { + throw new RangeError('is-odd expects an integer.'); + } + return !!(~~i & 1); }; /***/ }), -/* 744 */ +/* 769 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +/*! + * is-number + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ -var utils = __webpack_require__(745); -var define = __webpack_require__(685); -/** - * Text regex - */ +module.exports = function isNumber(num) { + var type = typeof num; -var TEXT_REGEX = '(\\[(?=.*\\])|\\])+'; -var not = utils.createRegex(TEXT_REGEX); + if (type === 'string' || num instanceof String) { + // an empty string would be coerced to true with the below logic + if (!num.trim()) return false; + } else if (type !== 'number' && !(num instanceof Number)) { + return false; + } -/** - * Brackets parsers - */ + return (num - num + 1) >= 0; +}; -function parsers(brackets) { - brackets.state = brackets.state || {}; - brackets.parser.sets.bracket = brackets.parser.sets.bracket || []; - brackets.parser - .capture('escape', function() { - if (this.isInside('bracket')) return; - var pos = this.position(); - var m = this.match(/^\\(.)/); - if (!m) return; +/***/ }), +/* 770 */ +/***/ (function(module, exports, __webpack_require__) { - return pos({ - type: 'escape', - val: m[0] - }); - }) +module.exports = new (__webpack_require__(771))(); - /** - * Text parser - */ - .capture('text', function() { - if (this.isInside('bracket')) return; - var pos = this.position(); - var m = this.match(not); - if (!m || !m[0]) return; +/***/ }), +/* 771 */ +/***/ (function(module, exports, __webpack_require__) { - return pos({ - type: 'text', - val: m[0] - }); - }) +"use strict"; +/*! + * fragment-cache + * + * Copyright (c) 2016-2017, Jon Schlinkert. + * Released under the MIT License. + */ - /** - * POSIX character classes: "[[:alpha:][:digits:]]" - */ - .capture('posix', function() { - var pos = this.position(); - var m = this.match(/^\[:(.*?):\](?=.*\])/); - if (!m) return; - var inside = this.isInside('bracket'); - if (inside) { - brackets.posix++; - } +var MapCache = __webpack_require__(758); - return pos({ - type: 'posix', - insideBracket: inside, - inner: m[1], - val: m[0] - }); - }) +/** + * Create a new `FragmentCache` with an optional object to use for `caches`. + * + * ```js + * var fragment = new FragmentCache(); + * ``` + * @name FragmentCache + * @param {String} `cacheName` + * @return {Object} Returns the [map-cache][] instance. + * @api public + */ - /** - * Bracket (noop) - */ +function FragmentCache(caches) { + this.caches = caches || {}; +} - .capture('bracket', function() {}) +/** + * Prototype + */ - /** - * Open: '[' - */ +FragmentCache.prototype = { - .capture('bracket.open', function() { - var parsed = this.parsed; - var pos = this.position(); - var m = this.match(/^\[(?=.*\])/); - if (!m) return; + /** + * Get cache `name` from the `fragment.caches` object. Creates a new + * `MapCache` if it doesn't already exist. + * + * ```js + * var cache = fragment.cache('files'); + * console.log(fragment.caches.hasOwnProperty('files')); + * //=> true + * ``` + * @name .cache + * @param {String} `cacheName` + * @return {Object} Returns the [map-cache][] instance. + * @api public + */ - var prev = this.prev(); - var last = utils.last(prev.nodes); + cache: function(cacheName) { + return this.caches[cacheName] || (this.caches[cacheName] = new MapCache()); + }, - if (parsed.slice(-1) === '\\' && !this.isInside('bracket')) { - last.val = last.val.slice(0, last.val.length - 1); - return pos({ - type: 'escape', - val: m[0] - }); - } + /** + * Set a value for property `key` on cache `name` + * + * ```js + * fragment.set('files', 'somefile.js', new File({path: 'somefile.js'})); + * ``` + * @name .set + * @param {String} `name` + * @param {String} `key` Property name to set + * @param {any} `val` The value of `key` + * @return {Object} The cache instance for chaining + * @api public + */ - var open = pos({ - type: 'bracket.open', - val: m[0] - }); + set: function(cacheName, key, val) { + var cache = this.cache(cacheName); + cache.set(key, val); + return cache; + }, - if (last.type === 'bracket.open' || this.isInside('bracket')) { - open.val = '\\' + open.val; - open.type = 'bracket.inner'; - open.escaped = true; - return open; - } + /** + * Returns true if a non-undefined value is set for `key` on fragment cache `name`. + * + * ```js + * var cache = fragment.cache('files'); + * cache.set('somefile.js'); + * + * console.log(cache.has('somefile.js')); + * //=> true + * + * console.log(cache.has('some-other-file.js')); + * //=> false + * ``` + * @name .has + * @param {String} `name` Cache name + * @param {String} `key` Optionally specify a property to check for on cache `name` + * @return {Boolean} + * @api public + */ + + has: function(cacheName, key) { + return typeof this.get(cacheName, key) !== 'undefined'; + }, + + /** + * Get `name`, or if specified, the value of `key`. Invokes the [cache]() method, + * so that cache `name` will be created it doesn't already exist. If `key` is not passed, + * the entire cache (`name`) is returned. + * + * ```js + * var Vinyl = require('vinyl'); + * var cache = fragment.cache('files'); + * cache.set('somefile.js', new Vinyl({path: 'somefile.js'})); + * console.log(cache.get('somefile.js')); + * //=> + * ``` + * @name .get + * @param {String} `name` + * @return {Object} Returns cache `name`, or the value of `key` if specified + * @api public + */ + + get: function(name, key) { + var cache = this.cache(name); + if (typeof key === 'string') { + return cache.get(key); + } + return cache; + } +}; + +/** + * Expose `FragmentCache` + */ - var node = pos({ - type: 'bracket', - nodes: [open] - }); +exports = module.exports = FragmentCache; - define(node, 'parent', prev); - define(open, 'parent', node); - this.push('bracket', node); - prev.nodes.push(node); - }) - /** - * Bracket text - */ +/***/ }), +/* 772 */ +/***/ (function(module, exports, __webpack_require__) { - .capture('bracket.inner', function() { - if (!this.isInside('bracket')) return; - var pos = this.position(); - var m = this.match(not); - if (!m || !m[0]) return; +"use strict"; - var next = this.input.charAt(0); - var val = m[0]; - var node = pos({ - type: 'bracket.inner', - val: val - }); +var utils = module.exports; +var path = __webpack_require__(4); - if (val === '\\\\') { - return node; - } +/** + * Module dependencies + */ - var first = val.charAt(0); - var last = val.slice(-1); +var isWindows = __webpack_require__(773)(); +var Snapdragon = __webpack_require__(692); +utils.define = __webpack_require__(774); +utils.diff = __webpack_require__(775); +utils.extend = __webpack_require__(764); +utils.pick = __webpack_require__(776); +utils.typeOf = __webpack_require__(658); +utils.unique = __webpack_require__(668); - if (first === '!') { - val = '^' + val.slice(1); - } +/** + * Returns true if the given value is effectively an empty string + */ - if (last === '\\' || (val === '^' && next === ']')) { - val += this.input[0]; - this.consume(1); - } +utils.isEmptyString = function(val) { + return String(val) === '' || String(val) === './'; +}; - node.val = val; - return node; - }) +/** + * Returns true if the platform is windows, or `path.sep` is `\\`. + * This is defined as a function to allow `path.sep` to be set in unit tests, + * or by the user, if there is a reason to do so. + * @return {Boolean} + */ - /** - * Close: ']' - */ +utils.isWindows = function() { + return path.sep === '\\' || isWindows === true; +}; - .capture('bracket.close', function() { - var parsed = this.parsed; - var pos = this.position(); - var m = this.match(/^\]/); - if (!m) return; +/** + * Return the last element from an array + */ - var prev = this.prev(); - var last = utils.last(prev.nodes); +utils.last = function(arr, n) { + return arr[arr.length - (n || 1)]; +}; - if (parsed.slice(-1) === '\\' && !this.isInside('bracket')) { - last.val = last.val.slice(0, last.val.length - 1); +/** + * Get the `Snapdragon` instance to use + */ - return pos({ - type: 'escape', - val: m[0] - }); - } +utils.instantiate = function(ast, options) { + var snapdragon; + // if an instance was created by `.parse`, use that instance + if (utils.typeOf(ast) === 'object' && ast.snapdragon) { + snapdragon = ast.snapdragon; + // if the user supplies an instance on options, use that instance + } else if (utils.typeOf(options) === 'object' && options.snapdragon) { + snapdragon = options.snapdragon; + // create a new instance + } else { + snapdragon = new Snapdragon(options); + } - var node = pos({ - type: 'bracket.close', - rest: this.input, - val: m[0] - }); + utils.define(snapdragon, 'parse', function(str, options) { + var parsed = Snapdragon.prototype.parse.call(this, str, options); + parsed.input = str; - if (last.type === 'bracket.open') { - node.type = 'bracket.inner'; - node.escaped = true; - return node; - } + // escape unmatched brace/bracket/parens + var last = this.parser.stack.pop(); + if (last && this.options.strictErrors !== true) { + var open = last.nodes[0]; + var inner = last.nodes[1]; + if (last.type === 'bracket') { + if (inner.val.charAt(0) === '[') { + inner.val = '\\' + inner.val; + } - var bracket = this.pop('bracket'); - if (!this.isType(bracket, 'bracket')) { - if (this.options.strict) { - throw new Error('missing opening "["'); + } else { + open.val = '\\' + open.val; + var sibling = open.parent.nodes[1]; + if (sibling.type === 'star') { + sibling.loose = true; } - node.type = 'bracket.inner'; - node.escaped = true; - return node; } + } - bracket.nodes.push(node); - define(node, 'parent', bracket); - }); -} + // add non-enumerable parser reference + utils.define(parsed, 'parser', this.parser); + return parsed; + }); + + return snapdragon; +}; /** - * Brackets parsers + * Create the key to use for memoization. The key is generated + * by iterating over the options and concatenating key-value pairs + * to the pattern string. */ -module.exports = parsers; +utils.createKey = function(pattern, options) { + if (typeof options === 'undefined') { + return pattern; + } + var key = pattern; + for (var prop in options) { + if (options.hasOwnProperty(prop)) { + key += ';' + prop + '=' + String(options[prop]); + } + } + return key; +}; /** - * Expose text regex + * Cast `val` to an array + * @return {Array} */ -module.exports.TEXT_REGEX = TEXT_REGEX; - +utils.arrayify = function(val) { + if (typeof val === 'string') return [val]; + return val ? (Array.isArray(val) ? val : [val]) : []; +}; -/***/ }), -/* 745 */ -/***/ (function(module, exports, __webpack_require__) { +/** + * Return true if `val` is a non-empty string + */ -"use strict"; +utils.isString = function(val) { + return typeof val === 'string'; +}; +/** + * Return true if `val` is a non-empty string + */ -var toRegex = __webpack_require__(610); -var regexNot = __webpack_require__(627); -var cached; +utils.isRegex = function(val) { + return utils.typeOf(val) === 'regexp'; +}; /** - * Get the last element from `array` - * @param {Array} `array` - * @return {*} + * Return true if `val` is a non-empty string */ -exports.last = function(arr) { - return arr[arr.length - 1]; +utils.isObject = function(val) { + return utils.typeOf(val) === 'object'; }; /** - * Create and cache regex to use for text nodes + * Escape regex characters in the given string */ -exports.createRegex = function(pattern, include) { - if (cached) return cached; - var opts = {contains: true, strictClose: false}; - var not = regexNot.create(pattern, opts); - var re; +utils.escapeRegex = function(str) { + return str.replace(/[-[\]{}()^$|*+?.\\/\s]/g, '\\$&'); +}; - if (typeof include === 'string') { - re = toRegex('^(?:' + include + '|' + not + ')', opts); - } else { - re = toRegex(not, opts); - } +/** + * Combines duplicate characters in the provided `input` string. + * @param {String} `input` + * @returns {String} + */ - return (cached = re); +utils.combineDupes = function(input, patterns) { + patterns = utils.arrayify(patterns).join('|').split('|'); + patterns = patterns.map(function(s) { + return s.replace(/\\?([+*\\/])/g, '\\$1'); + }); + var substr = patterns.join('|'); + var regex = new RegExp('(' + substr + ')(?=\\1)', 'g'); + return input.replace(regex, ''); }; +/** + * Returns true if the given `str` has special characters + */ -/***/ }), -/* 746 */ -/***/ (function(module, exports, __webpack_require__) { +utils.hasSpecialChars = function(str) { + return /(?:(?:(^|\/)[!.])|[*?+()|[\]{}]|[+@]\()/.test(str); +}; -"use strict"; +/** + * Normalize slashes in the given filepath. + * + * @param {String} `filepath` + * @return {String} + */ + +utils.toPosixPath = function(str) { + return str.replace(/\\+/g, '/'); +}; +/** + * Strip backslashes before special characters in a string. + * + * @param {String} `str` + * @return {String} + */ -var brackets = __webpack_require__(741); -var define = __webpack_require__(747); -var utils = __webpack_require__(748); +utils.unescape = function(str) { + return utils.toPosixPath(str.replace(/\\(?=[*+?!.])/g, '')); +}; /** - * Characters to use in text regex (we want to "not" match - * characters that are matched by other parsers) + * Strip the drive letter from a windows filepath + * @param {String} `fp` + * @return {String} */ -var TEXT_REGEX = '([!@*?+]?\\(|\\)|[*?.+\\\\]|\\[:?(?=.*\\])|:?\\])+'; -var not = utils.createRegex(TEXT_REGEX); +utils.stripDrive = function(fp) { + return utils.isWindows() ? fp.replace(/^[a-z]:[\\/]+?/i, '/') : fp; +}; /** - * Extglob parsers + * Strip the prefix from a filepath + * @param {String} `fp` + * @return {String} */ -function parsers(extglob) { - extglob.state = extglob.state || {}; +utils.stripPrefix = function(str) { + if (str.charAt(0) === '.' && (str.charAt(1) === '/' || str.charAt(1) === '\\')) { + return str.slice(2); + } + return str; +}; - /** - * Use `expand-brackets` parsers - */ +/** + * Returns true if `str` is a common character that doesn't need + * to be processed to be used for matching. + * @param {String} `str` + * @return {Boolean} + */ - extglob.use(brackets.parsers); - extglob.parser.sets.paren = extglob.parser.sets.paren || []; - extglob.parser +utils.isSimpleChar = function(str) { + return str.trim() === '' || str === '.'; +}; - /** - * Extglob open: "*(" - */ +/** + * Returns true if the given str is an escaped or + * unescaped path character + */ - .capture('paren.open', function() { - var parsed = this.parsed; - var pos = this.position(); - var m = this.match(/^([!@*?+])?\(/); - if (!m) return; +utils.isSlash = function(str) { + return str === '/' || str === '\\/' || str === '\\' || str === '\\\\'; +}; - var prev = this.prev(); - var prefix = m[1]; - var val = m[0]; +/** + * Returns a function that returns true if the given + * pattern matches or contains a `filepath` + * + * @param {String} `pattern` + * @return {Function} + */ - var open = pos({ - type: 'paren.open', - parsed: parsed, - val: val - }); +utils.matchPath = function(pattern, options) { + return (options && options.contains) + ? utils.containsPattern(pattern, options) + : utils.equalsPattern(pattern, options); +}; - var node = pos({ - type: 'paren', - prefix: prefix, - nodes: [open] - }); +/** + * Returns true if the given (original) filepath or unixified path are equal + * to the given pattern. + */ - // if nested negation extglobs, just cancel them out to simplify - if (prefix === '!' && prev.type === 'paren' && prev.prefix === '!') { - prev.prefix = '@'; - node.prefix = '@'; - } +utils._equals = function(filepath, unixPath, pattern) { + return pattern === filepath || pattern === unixPath; +}; - define(node, 'rest', this.input); - define(node, 'parsed', parsed); - define(node, 'parent', prev); - define(open, 'parent', node); +/** + * Returns true if the given (original) filepath or unixified path contain + * the given pattern. + */ - this.push('paren', node); - prev.nodes.push(node); - }) +utils._contains = function(filepath, unixPath, pattern) { + return filepath.indexOf(pattern) !== -1 || unixPath.indexOf(pattern) !== -1; +}; - /** - * Extglob close: ")" - */ +/** + * Returns a function that returns true if the given + * pattern is the same as a given `filepath` + * + * @param {String} `pattern` + * @return {Function} + */ - .capture('paren.close', function() { - var parsed = this.parsed; - var pos = this.position(); - var m = this.match(/^\)/); - if (!m) return; +utils.equalsPattern = function(pattern, options) { + var unixify = utils.unixify(options); + options = options || {}; - var parent = this.pop('paren'); - var node = pos({ - type: 'paren.close', - rest: this.input, - parsed: parsed, - val: m[0] - }); + return function fn(filepath) { + var equal = utils._equals(filepath, unixify(filepath), pattern); + if (equal === true || options.nocase !== true) { + return equal; + } + var lower = filepath.toLowerCase(); + return utils._equals(lower, unixify(lower), pattern); + }; +}; - if (!this.isType(parent, 'paren')) { - if (this.options.strict) { - throw new Error('missing opening paren: "("'); - } - node.escaped = true; - return node; - } +/** + * Returns a function that returns true if the given + * pattern contains a `filepath` + * + * @param {String} `pattern` + * @return {Function} + */ - node.prefix = parent.prefix; - parent.nodes.push(node); - define(node, 'parent', parent); - }) +utils.containsPattern = function(pattern, options) { + var unixify = utils.unixify(options); + options = options || {}; - /** - * Escape: "\\." - */ + return function(filepath) { + var contains = utils._contains(filepath, unixify(filepath), pattern); + if (contains === true || options.nocase !== true) { + return contains; + } + var lower = filepath.toLowerCase(); + return utils._contains(lower, unixify(lower), pattern); + }; +}; - .capture('escape', function() { - var pos = this.position(); - var m = this.match(/^\\(.)/); - if (!m) return; +/** + * Returns a function that returns true if the given + * regex matches the `filename` of a file path. + * + * @param {RegExp} `re` Matching regex + * @return {Function} + */ - return pos({ - type: 'escape', - val: m[0], - ch: m[1] - }); - }) +utils.matchBasename = function(re) { + return function(filepath) { + return re.test(filepath) || re.test(path.basename(filepath)); + }; +}; - /** - * Question marks: "?" - */ +/** + * Returns the given value unchanced. + * @return {any} + */ - .capture('qmark', function() { - var parsed = this.parsed; - var pos = this.position(); - var m = this.match(/^\?+(?!\()/); - if (!m) return; - extglob.state.metachar = true; - return pos({ - type: 'qmark', - rest: this.input, - parsed: parsed, - val: m[0] - }); - }) +utils.identity = function(val) { + return val; +}; - /** - * Character parsers - */ +/** + * Determines the filepath to return based on the provided options. + * @return {any} + */ - .capture('star', /^\*(?!\()/) - .capture('plus', /^\+(?!\()/) - .capture('dot', /^\./) - .capture('text', not); +utils.value = function(str, unixify, options) { + if (options && options.unixify === false) { + return str; + } + if (options && typeof options.unixify === 'function') { + return options.unixify(str); + } + return unixify(str); }; /** - * Expose text regex string + * Returns a function that normalizes slashes in a string to forward + * slashes, strips `./` from beginning of paths, and optionally unescapes + * special characters. + * @return {Function} */ -module.exports.TEXT_REGEX = TEXT_REGEX; +utils.unixify = function(options) { + var opts = options || {}; + return function(filepath) { + if (opts.stripPrefix !== false) { + filepath = utils.stripPrefix(filepath); + } + if (opts.unescape === true) { + filepath = utils.unescape(filepath); + } + if (opts.unixify === true || utils.isWindows()) { + filepath = utils.toPosixPath(filepath); + } + return filepath; + }; +}; + + +/***/ }), +/* 773 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * Extglob parsers +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! + * is-windows + * + * Copyright © 2015-2018, Jon Schlinkert. + * Released under the MIT License. */ -module.exports = parsers; +(function(factory) { + if (exports && typeof exports === 'object' && typeof module !== 'undefined') { + module.exports = factory(); + } else if (true) { + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} +})(function() { + 'use strict'; + return function isWindows() { + return process && (process.platform === 'win32' || /^(msys|cygwin)$/.test(process.env.OSTYPE)); + }; +}); /***/ }), -/* 747 */ +/* 774 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /*! * define-property * - * Copyright (c) 2015, 2017, Jon Schlinkert. + * Copyright (c) 2015-2018, Jon Schlinkert. * Released under the MIT License. */ -var isDescriptor = __webpack_require__(619); +var isobject = __webpack_require__(656); +var isDescriptor = __webpack_require__(657); +var define = (typeof Reflect !== 'undefined' && Reflect.defineProperty) + ? Reflect.defineProperty + : Object.defineProperty; -module.exports = function defineProperty(obj, prop, val) { - if (typeof obj !== 'object' && typeof obj !== 'function') { - throw new TypeError('expected an object or function.'); +module.exports = function defineProperty(obj, key, val) { + if (!isobject(obj) && typeof obj !== 'function' && !Array.isArray(obj)) { + throw new TypeError('expected an object, function, or array'); } - if (typeof prop !== 'string') { - throw new TypeError('expected `prop` to be a string.'); + if (typeof key !== 'string') { + throw new TypeError('expected "key" to be a string'); } - if (isDescriptor(val) && ('set' in val || 'get' in val)) { - return Object.defineProperty(obj, prop, val); + if (isDescriptor(val)) { + define(obj, key, val); + return obj; } - return Object.defineProperty(obj, prop, { + define(obj, key, { configurable: true, enumerable: false, writable: true, value: val }); + + return obj; }; /***/ }), -/* 748 */ +/* 775 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; - - -var regex = __webpack_require__(627); -var Cache = __webpack_require__(733); - -/** - * Utils +/*! + * arr-diff + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. */ -var utils = module.exports; -var cache = utils.cache = new Cache(); -/** - * Cast `val` to an array - * @return {Array} - */ -utils.arrayify = function(val) { - if (!Array.isArray(val)) { - return [val]; +module.exports = function diff(arr/*, arrays*/) { + var len = arguments.length; + var idx = 0; + while (++idx < len) { + arr = diffArray(arr, arguments[idx]); } - return val; + return arr; }; -/** - * Memoize a generated regex or function - */ - -utils.memoize = function(type, pattern, options, fn) { - var key = utils.createKey(type + pattern, options); - - if (cache.has(type, key)) { - return cache.get(type, key); - } - - var val = fn(pattern, options); - if (options && options.cache === false) { - return val; +function diffArray(one, two) { + if (!Array.isArray(two)) { + return one.slice(); } - cache.set(type, key, val); - return val; -}; + var tlen = two.length + var olen = one.length; + var idx = -1; + var arr = []; -/** - * Create the key to use for memoization. The key is generated - * by iterating over the options and concatenating key-value pairs - * to the pattern string. - */ + while (++idx < olen) { + var ele = one[idx]; -utils.createKey = function(pattern, options) { - var key = pattern; - if (typeof options === 'undefined') { - return key; - } - for (var prop in options) { - key += ';' + prop + '=' + String(options[prop]); - } - return key; -}; + var hasEle = false; + for (var i = 0; i < tlen; i++) { + var val = two[i]; -/** - * Create the regex to use for matching text - */ + if (ele === val) { + hasEle = true; + break; + } + } -utils.createRegex = function(str) { - var opts = {contains: true, strictClose: false}; - return regex(str, opts); -}; + if (hasEle === false) { + arr.push(ele); + } + } + return arr; +} /***/ }), -/* 749 */ +/* 776 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; - - -/** - * Module dependencies - */ - -var Snapdragon = __webpack_require__(654); -var define = __webpack_require__(747); -var extend = __webpack_require__(669); - -/** - * Local dependencies - */ - -var compilers = __webpack_require__(740); -var parsers = __webpack_require__(746); - -/** - * Customize Snapdragon parser and renderer +/*! + * object.pick + * + * Copyright (c) 2014-2015 Jon Schlinkert, contributors. + * Licensed under the MIT License */ -function Extglob(options) { - this.options = extend({source: 'extglob'}, options); - this.snapdragon = this.options.snapdragon || new Snapdragon(this.options); - this.snapdragon.patterns = this.snapdragon.patterns || {}; - this.compiler = this.snapdragon.compiler; - this.parser = this.snapdragon.parser; - compilers(this.snapdragon); - parsers(this.snapdragon); - /** - * Override Snapdragon `.parse` method - */ +var isObject = __webpack_require__(656); - define(this.snapdragon, 'parse', function(str, options) { - var parsed = Snapdragon.prototype.parse.apply(this, arguments); - parsed.input = str; +module.exports = function pick(obj, keys) { + if (!isObject(obj) && typeof obj !== 'function') { + return {}; + } - // escape unmatched brace/bracket/parens - var last = this.parser.stack.pop(); - if (last && this.options.strict !== true) { - var node = last.nodes[0]; - node.val = '\\' + node.val; - var sibling = node.parent.nodes[1]; - if (sibling.type === 'star') { - sibling.loose = true; - } + var res = {}; + if (typeof keys === 'string') { + if (keys in obj) { + res[keys] = obj[keys]; } + return res; + } - // add non-enumerable parser reference - define(parsed, 'parser', this.parser); - return parsed; - }); - - /** - * Decorate `.parse` method - */ - - define(this, 'parse', function(ast, options) { - return this.snapdragon.parse.apply(this.snapdragon, arguments); - }); - - /** - * Decorate `.compile` method - */ - - define(this, 'compile', function(ast, options) { - return this.snapdragon.compile.apply(this.snapdragon, arguments); - }); - -} - -/** - * Expose `Extglob` - */ + var len = keys.length; + var idx = -1; -module.exports = Extglob; + while (++idx < len) { + var key = keys[idx]; + if (key in obj) { + res[key] = obj[key]; + } + } + return res; +}; /***/ }), -/* 750 */ +/* 777 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var extglob = __webpack_require__(739); -var nanomatch = __webpack_require__(725); -var regexNot = __webpack_require__(627); -var toRegex = __webpack_require__(610); -var not; - /** - * Characters to use in negation regex (we want to "not" match - * characters that are matched by other parsers) + * Module dependencies */ -var TEXT = '([!@*?+]?\\(|\\)|\\[:?(?=.*?:?\\])|:?\\]|[*+?!^$.\\\\/])+'; -var createNotRegex = function(opts) { - return not || (not = textRegex(TEXT)); -}; +var extend = __webpack_require__(707); +var unique = __webpack_require__(668); +var toRegex = __webpack_require__(648); /** - * Parsers + * Local dependencies */ -module.exports = function(snapdragon) { - var parsers = snapdragon.parser.parsers; - - // register nanomatch parsers - snapdragon.use(nanomatch.parsers); - - // get references to some specific nanomatch parsers before they - // are overridden by the extglob and/or parsers - var escape = parsers.escape; - var slash = parsers.slash; - var qmark = parsers.qmark; - var plus = parsers.plus; - var star = parsers.star; - var dot = parsers.dot; - - // register extglob parsers - snapdragon.use(extglob.parsers); - - // custom micromatch parsers - snapdragon.parser - .use(function() { - // override "notRegex" created in nanomatch parser - this.notRegex = /^\!+(?!\()/; - }) - // reset the referenced parsers - .capture('escape', escape) - .capture('slash', slash) - .capture('qmark', qmark) - .capture('star', star) - .capture('plus', plus) - .capture('dot', dot) - - /** - * Override `text` parser - */ - - .capture('text', function() { - if (this.isInside('bracket')) return; - var pos = this.position(); - var m = this.match(createNotRegex(this.options)); - if (!m || !m[0]) return; - - // escape regex boundary characters and simple brackets - var val = m[0].replace(/([[\]^$])/g, '\\$1'); - - return pos({ - type: 'text', - val: val - }); - }); -}; +var compilers = __webpack_require__(778); +var parsers = __webpack_require__(784); +var Extglob = __webpack_require__(787); +var utils = __webpack_require__(786); +var MAX_LENGTH = 1024 * 64; /** - * Create text regex + * Convert the given `extglob` pattern into a regex-compatible string. Returns + * an object with the compiled result and the parsed AST. + * + * ```js + * var extglob = require('extglob'); + * console.log(extglob('*.!(*a)')); + * //=> '(?!\\.)[^/]*?\\.(?!(?!\\.)[^/]*?a\\b).*?' + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {String} + * @api public */ -function textRegex(pattern) { - var notStr = regexNot.create(pattern, {contains: true, strictClose: false}); - var prefix = '(?:[\\^]|\\\\|'; - return toRegex(prefix + notStr + ')', {strictClose: false}); +function extglob(pattern, options) { + return extglob.create(pattern, options).output; } +/** + * Takes an array of strings and an extglob pattern and returns a new + * array that contains only the strings that match the pattern. + * + * ```js + * var extglob = require('extglob'); + * console.log(extglob.match(['a.a', 'a.b', 'a.c'], '*.!(*a)')); + * //=> ['a.b', 'a.c'] + * ``` + * @param {Array} `list` Array of strings to match + * @param {String} `pattern` Extglob pattern + * @param {Object} `options` + * @return {Array} Returns an array of matches + * @api public + */ -/***/ }), -/* 751 */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = new (__webpack_require__(733))(); - - -/***/ }), -/* 752 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; +extglob.match = function(list, pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected pattern to be a string'); + } + list = utils.arrayify(list); + var isMatch = extglob.matcher(pattern, options); + var len = list.length; + var idx = -1; + var matches = []; -var utils = module.exports; -var path = __webpack_require__(4); + while (++idx < len) { + var ele = list[idx]; -/** - * Module dependencies - */ + if (isMatch(ele)) { + matches.push(ele); + } + } -var Snapdragon = __webpack_require__(654); -utils.define = __webpack_require__(753); -utils.diff = __webpack_require__(737); -utils.extend = __webpack_require__(722); -utils.pick = __webpack_require__(738); -utils.typeOf = __webpack_require__(620); -utils.unique = __webpack_require__(630); + // if no options were passed, uniquify results and return + if (typeof options === 'undefined') { + return unique(matches); + } -/** - * Returns true if the platform is windows, or `path.sep` is `\\`. - * This is defined as a function to allow `path.sep` to be set in unit tests, - * or by the user, if there is a reason to do so. - * @return {Boolean} - */ + if (matches.length === 0) { + if (options.failglob === true) { + throw new Error('no matches found for "' + pattern + '"'); + } + if (options.nonull === true || options.nullglob === true) { + return [pattern.split('\\').join('')]; + } + } -utils.isWindows = function() { - return path.sep === '\\' || process.platform === 'win32'; + return options.nodupes !== false ? unique(matches) : matches; }; /** - * Get the `Snapdragon` instance to use + * Returns true if the specified `string` matches the given + * extglob `pattern`. + * + * ```js + * var extglob = require('extglob'); + * + * console.log(extglob.isMatch('a.a', '*.!(*a)')); + * //=> false + * console.log(extglob.isMatch('a.b', '*.!(*a)')); + * //=> true + * ``` + * @param {String} `string` String to match + * @param {String} `pattern` Extglob pattern + * @param {String} `options` + * @return {Boolean} + * @api public */ -utils.instantiate = function(ast, options) { - var snapdragon; - // if an instance was created by `.parse`, use that instance - if (utils.typeOf(ast) === 'object' && ast.snapdragon) { - snapdragon = ast.snapdragon; - // if the user supplies an instance on options, use that instance - } else if (utils.typeOf(options) === 'object' && options.snapdragon) { - snapdragon = options.snapdragon; - // create a new instance - } else { - snapdragon = new Snapdragon(options); +extglob.isMatch = function(str, pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected pattern to be a string'); } - utils.define(snapdragon, 'parse', function(str, options) { - var parsed = Snapdragon.prototype.parse.apply(this, arguments); - parsed.input = str; - - // escape unmatched brace/bracket/parens - var last = this.parser.stack.pop(); - if (last && this.options.strictErrors !== true) { - var open = last.nodes[0]; - var inner = last.nodes[1]; - if (last.type === 'bracket') { - if (inner.val.charAt(0) === '[') { - inner.val = '\\' + inner.val; - } + if (typeof str !== 'string') { + throw new TypeError('expected a string'); + } - } else { - open.val = '\\' + open.val; - var sibling = open.parent.nodes[1]; - if (sibling.type === 'star') { - sibling.loose = true; - } - } - } + if (pattern === str) { + return true; + } - // add non-enumerable parser reference - utils.define(parsed, 'parser', this.parser); - return parsed; - }); + if (pattern === '' || pattern === ' ' || pattern === '.') { + return pattern === str; + } - return snapdragon; + var isMatch = utils.memoize('isMatch', pattern, options, extglob.matcher); + return isMatch(str); }; /** - * Create the key to use for memoization. The key is generated - * by iterating over the options and concatenating key-value pairs - * to the pattern string. + * Returns true if the given `string` contains the given pattern. Similar to `.isMatch` but + * the pattern can match any part of the string. + * + * ```js + * var extglob = require('extglob'); + * console.log(extglob.contains('aa/bb/cc', '*b')); + * //=> true + * console.log(extglob.contains('aa/bb/cc', '*d')); + * //=> false + * ``` + * @param {String} `str` The string to match. + * @param {String} `pattern` Glob pattern to use for matching. + * @param {Object} `options` + * @return {Boolean} Returns true if the patter matches any part of `str`. + * @api public */ -utils.createKey = function(pattern, options) { - if (utils.typeOf(options) !== 'object') { - return pattern; - } - var val = pattern; - var keys = Object.keys(options); - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - val += ';' + key + '=' + String(options[key]); +extglob.contains = function(str, pattern, options) { + if (typeof str !== 'string') { + throw new TypeError('expected a string'); } - return val; -}; -/** - * Cast `val` to an array - * @return {Array} - */ + if (pattern === '' || pattern === ' ' || pattern === '.') { + return pattern === str; + } -utils.arrayify = function(val) { - if (typeof val === 'string') return [val]; - return val ? (Array.isArray(val) ? val : [val]) : []; + var opts = extend({}, options, {contains: true}); + opts.strictClose = false; + opts.strictOpen = false; + return extglob.isMatch(str, pattern, opts); }; /** - * Return true if `val` is a non-empty string + * Takes an extglob pattern and returns a matcher function. The returned + * function takes the string to match as its only argument. + * + * ```js + * var extglob = require('extglob'); + * var isMatch = extglob.matcher('*.!(*a)'); + * + * console.log(isMatch('a.a')); + * //=> false + * console.log(isMatch('a.b')); + * //=> true + * ``` + * @param {String} `pattern` Extglob pattern + * @param {String} `options` + * @return {Boolean} + * @api public */ -utils.isString = function(val) { - return typeof val === 'string'; -}; +extglob.matcher = function(pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected pattern to be a string'); + } -/** - * Return true if `val` is a non-empty string - */ + function matcher() { + var re = extglob.makeRe(pattern, options); + return function(str) { + return re.test(str); + }; + } -utils.isObject = function(val) { - return utils.typeOf(val) === 'object'; + return utils.memoize('matcher', pattern, options, matcher); }; /** - * Returns true if the given `str` has special characters + * Convert the given `extglob` pattern into a regex-compatible string. Returns + * an object with the compiled result and the parsed AST. + * + * ```js + * var extglob = require('extglob'); + * console.log(extglob.create('*.!(*a)').output); + * //=> '(?!\\.)[^/]*?\\.(?!(?!\\.)[^/]*?a\\b).*?' + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {String} + * @api public */ -utils.hasSpecialChars = function(str) { - return /(?:(?:(^|\/)[!.])|[*?+()|\[\]{}]|[+@]\()/.test(str); -}; +extglob.create = function(pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected pattern to be a string'); + } -/** - * Escape regex characters in the given string - */ + function create() { + var ext = new Extglob(options); + var ast = ext.parse(pattern, options); + return ext.compile(ast, options); + } -utils.escapeRegex = function(str) { - return str.replace(/[-[\]{}()^$|*+?.\\\/\s]/g, '\\$&'); + return utils.memoize('create', pattern, options, create); }; /** - * Normalize slashes in the given filepath. + * Returns an array of matches captured by `pattern` in `string`, or `null` + * if the pattern did not match. * - * @param {String} `filepath` - * @return {String} + * ```js + * var extglob = require('extglob'); + * extglob.capture(pattern, string[, options]); + * + * console.log(extglob.capture('test/*.js', 'test/foo.js')); + * //=> ['foo'] + * console.log(extglob.capture('test/*.js', 'foo/bar.css')); + * //=> null + * ``` + * @param {String} `pattern` Glob pattern to use for matching. + * @param {String} `string` String to match + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns an array of captures if the string matches the glob pattern, otherwise `null`. + * @api public */ -utils.toPosixPath = function(str) { - return str.replace(/\\+/g, '/'); +extglob.capture = function(pattern, str, options) { + var re = extglob.makeRe(pattern, extend({capture: true}, options)); + + function match() { + return function(string) { + var match = re.exec(string); + if (!match) { + return null; + } + + return match.slice(1); + }; + } + + var capture = utils.memoize('capture', pattern, options, match); + return capture(str); }; /** - * Strip backslashes before special characters in a string. + * Create a regular expression from the given `pattern` and `options`. * - * @param {String} `str` - * @return {String} + * ```js + * var extglob = require('extglob'); + * var re = extglob.makeRe('*.!(*a)'); + * console.log(re); + * //=> /^[^\/]*?\.(?![^\/]*?a)[^\/]*?$/ + * ``` + * @param {String} `pattern` The pattern to convert to regex. + * @param {Object} `options` + * @return {RegExp} + * @api public */ -utils.unescape = function(str) { - return utils.toPosixPath(str.replace(/\\(?=[*+?!.])/g, '')); -}; +extglob.makeRe = function(pattern, options) { + if (pattern instanceof RegExp) { + return pattern; + } -/** - * Strip the prefix from a filepath - * @param {String} `fp` - * @return {String} - */ + if (typeof pattern !== 'string') { + throw new TypeError('expected pattern to be a string'); + } -utils.stripPrefix = function(str) { - if (str.charAt(0) !== '.') { - return str; + if (pattern.length > MAX_LENGTH) { + throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters'); } - var ch = str.charAt(1); - if (utils.isSlash(ch)) { - return str.slice(2); + + function makeRe() { + var opts = extend({strictErrors: false}, options); + if (opts.strictErrors === true) opts.strict = true; + var res = extglob.create(pattern, opts); + return toRegex(res.output, opts); } - return str; -}; -/** - * Returns true if the given str is an escaped or - * unescaped path character - */ + var regex = utils.memoize('makeRe', pattern, options, makeRe); + if (regex.source.length > MAX_LENGTH) { + throw new SyntaxError('potentially malicious regex detected'); + } -utils.isSlash = function(str) { - return str === '/' || str === '\\/' || str === '\\' || str === '\\\\'; + return regex; }; /** - * Returns a function that returns true if the given - * pattern matches or contains a `filepath` - * - * @param {String} `pattern` - * @return {Function} + * Cache */ -utils.matchPath = function(pattern, options) { - return (options && options.contains) - ? utils.containsPattern(pattern, options) - : utils.equalsPattern(pattern, options); +extglob.cache = utils.cache; +extglob.clearCache = function() { + extglob.cache.__data__ = {}; }; /** - * Returns true if the given (original) filepath or unixified path are equal - * to the given pattern. + * Expose `Extglob` constructor, parsers and compilers */ -utils._equals = function(filepath, unixPath, pattern) { - return pattern === filepath || pattern === unixPath; -}; +extglob.Extglob = Extglob; +extglob.compilers = compilers; +extglob.parsers = parsers; /** - * Returns true if the given (original) filepath or unixified path contain - * the given pattern. + * Expose `extglob` + * @type {Function} */ -utils._contains = function(filepath, unixPath, pattern) { - return filepath.indexOf(pattern) !== -1 || unixPath.indexOf(pattern) !== -1; -}; +module.exports = extglob; -/** - * Returns a function that returns true if the given - * pattern is the same as a given `filepath` - * - * @param {String} `pattern` - * @return {Function} - */ -utils.equalsPattern = function(pattern, options) { - var unixify = utils.unixify(options); - options = options || {}; +/***/ }), +/* 778 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; - return function fn(filepath) { - var equal = utils._equals(filepath, unixify(filepath), pattern); - if (equal === true || options.nocase !== true) { - return equal; - } - var lower = filepath.toLowerCase(); - return utils._equals(lower, unixify(lower), pattern); - }; -}; + +var brackets = __webpack_require__(779); /** - * Returns a function that returns true if the given - * pattern contains a `filepath` - * - * @param {String} `pattern` - * @return {Function} + * Extglob compilers */ -utils.containsPattern = function(pattern, options) { - var unixify = utils.unixify(options); - options = options || {}; - - return function(filepath) { - var contains = utils._contains(filepath, unixify(filepath), pattern); - if (contains === true || options.nocase !== true) { - return contains; +module.exports = function(extglob) { + function star() { + if (typeof extglob.options.star === 'function') { + return extglob.options.star.apply(this, arguments); } - var lower = filepath.toLowerCase(); - return utils._contains(lower, unixify(lower), pattern); - }; -}; + if (typeof extglob.options.star === 'string') { + return extglob.options.star; + } + return '.*?'; + } -/** - * Returns a function that returns true if the given - * regex matches the `filename` of a file path. - * - * @param {RegExp} `re` Matching regex - * @return {Function} - */ + /** + * Use `expand-brackets` compilers + */ -utils.matchBasename = function(re) { - return function(filepath) { - return re.test(path.basename(filepath)); - }; -}; + extglob.use(brackets.compilers); + extglob.compiler -/** - * Determines the filepath to return based on the provided options. - * @return {any} - */ + /** + * Escaped: "\\*" + */ -utils.value = function(str, unixify, options) { - if (options && options.unixify === false) { - return str; - } - return unixify(str); -}; + .set('escape', function(node) { + return this.emit(node.val, node); + }) -/** - * Returns a function that normalizes slashes in a string to forward - * slashes, strips `./` from beginning of paths, and optionally unescapes - * special characters. - * @return {Function} - */ + /** + * Dot: "." + */ -utils.unixify = function(options) { - options = options || {}; - return function(filepath) { - if (utils.isWindows() || options.unixify === true) { - filepath = utils.toPosixPath(filepath); - } - if (options.stripPrefix !== false) { - filepath = utils.stripPrefix(filepath); - } - if (options.unescape === true) { - filepath = utils.unescape(filepath); - } - return filepath; - }; -}; + .set('dot', function(node) { + return this.emit('\\' + node.val, node); + }) + /** + * Question mark: "?" + */ -/***/ }), -/* 753 */ -/***/ (function(module, exports, __webpack_require__) { + .set('qmark', function(node) { + var val = '[^\\\\/.]'; + var prev = this.prev(); -"use strict"; -/*! - * define-property - * - * Copyright (c) 2015-2018, Jon Schlinkert. - * Released under the MIT License. - */ + if (node.parsed.slice(-1) === '(') { + var ch = node.rest.charAt(0); + if (ch !== '!' && ch !== '=' && ch !== ':') { + return this.emit(val, node); + } + return this.emit(node.val, node); + } + if (prev.type === 'text' && prev.val) { + return this.emit(val, node); + } + if (node.val.length > 1) { + val += '{' + node.val.length + '}'; + } + return this.emit(val, node); + }) -var isobject = __webpack_require__(618); -var isDescriptor = __webpack_require__(619); -var define = (typeof Reflect !== 'undefined' && Reflect.defineProperty) - ? Reflect.defineProperty - : Object.defineProperty; + /** + * Plus: "+" + */ -module.exports = function defineProperty(obj, key, val) { - if (!isobject(obj) && typeof obj !== 'function' && !Array.isArray(obj)) { - throw new TypeError('expected an object, function, or array'); - } + .set('plus', function(node) { + var prev = node.parsed.slice(-1); + if (prev === ']' || prev === ')') { + return this.emit(node.val, node); + } + var ch = this.output.slice(-1); + if (!this.output || (/[?*+]/.test(ch) && node.parent.type !== 'bracket')) { + return this.emit('\\+', node); + } + if (/\w/.test(ch) && !node.inside) { + return this.emit('+\\+?', node); + } + return this.emit('+', node); + }) - if (typeof key !== 'string') { - throw new TypeError('expected "key" to be a string'); - } + /** + * Star: "*" + */ - if (isDescriptor(val)) { - define(obj, key, val); - return obj; - } + .set('star', function(node) { + var prev = this.prev(); + var prefix = prev.type !== 'text' && prev.type !== 'escape' + ? '(?!\\.)' + : ''; - define(obj, key, { - configurable: true, - enumerable: false, - writable: true, - value: val - }); + return this.emit(prefix + star.call(this, node), node); + }) - return obj; -}; + /** + * Parens + */ + .set('paren', function(node) { + return this.mapVisit(node.nodes); + }) + .set('paren.open', function(node) { + var capture = this.options.capture ? '(' : ''; -/***/ }), -/* 754 */ -/***/ (function(module, exports, __webpack_require__) { + switch (node.parent.prefix) { + case '!': + case '^': + return this.emit(capture + '(?:(?!(?:', node); + case '*': + case '+': + case '?': + case '@': + return this.emit(capture + '(?:', node); + default: { + var val = node.val; + if (this.options.bash === true) { + val = '\\' + val; + } else if (!this.options.capture && val === '(' && node.parent.rest[0] !== '?') { + val += '?:'; + } -"use strict"; - -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -var readdir = __webpack_require__(755); -var reader_1 = __webpack_require__(768); -var fs_stream_1 = __webpack_require__(772); -var ReaderAsync = /** @class */ (function (_super) { - __extends(ReaderAsync, _super); - function ReaderAsync() { - return _super !== null && _super.apply(this, arguments) || this; - } - Object.defineProperty(ReaderAsync.prototype, "fsAdapter", { - /** - * Returns FileSystem adapter. - */ - get: function () { - return new fs_stream_1.default(this.options); - }, - enumerable: true, - configurable: true - }); - /** - * Use async API to read entries for Task. - */ - ReaderAsync.prototype.read = function (task) { - var _this = this; - var root = this.getRootDirectory(task); - var options = this.getReaderOptions(task); - var entries = []; - return new Promise(function (resolve, reject) { - var stream = _this.api(root, task, options); - stream.on('error', function (err) { - _this.isEnoentCodeError(err) ? resolve([]) : reject(err); - stream.pause(); - }); - stream.on('data', function (entry) { return entries.push(_this.transform(entry)); }); - stream.on('end', function () { return resolve(entries); }); - }); - }; - /** - * Returns founded paths. - */ - ReaderAsync.prototype.api = function (root, task, options) { - if (task.dynamic) { - return this.dynamicApi(root, options); - } - return this.staticApi(task, options); - }; - /** - * Api for dynamic tasks. - */ - ReaderAsync.prototype.dynamicApi = function (root, options) { - return readdir.readdirStreamStat(root, options); - }; - /** - * Api for static tasks. - */ - ReaderAsync.prototype.staticApi = function (task, options) { - return this.fsAdapter.read(task.patterns, options.filter); - }; - return ReaderAsync; -}(reader_1.default)); -exports.default = ReaderAsync; + return this.emit(val, node); + } + } + }) + .set('paren.close', function(node) { + var capture = this.options.capture ? ')' : ''; + + switch (node.prefix) { + case '!': + case '^': + var prefix = /^(\)|$)/.test(node.rest) ? '$' : ''; + var str = star.call(this, node); + + // if the extglob has a slash explicitly defined, we know the user wants + // to match slashes, so we need to ensure the "star" regex allows for it + if (node.parent.hasSlash && !this.options.star && this.options.slash !== false) { + str = '.*?'; + } + + return this.emit(prefix + ('))' + str + ')') + capture, node); + case '*': + case '+': + case '?': + return this.emit(')' + node.prefix + capture, node); + case '@': + return this.emit(')' + capture, node); + default: { + var val = (this.options.bash === true ? '\\' : '') + ')'; + return this.emit(val, node); + } + } + }) + + /** + * Text + */ + + .set('text', function(node) { + var val = node.val.replace(/[\[\]]/g, '\\$&'); + return this.emit(val, node); + }); +}; /***/ }), -/* 755 */ +/* 779 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const readdirSync = __webpack_require__(756); -const readdirAsync = __webpack_require__(764); -const readdirStream = __webpack_require__(767); +/** + * Local dependencies + */ -module.exports = exports = readdirAsyncPath; -exports.readdir = exports.readdirAsync = exports.async = readdirAsyncPath; -exports.readdirAsyncStat = exports.async.stat = readdirAsyncStat; -exports.readdirStream = exports.stream = readdirStreamPath; -exports.readdirStreamStat = exports.stream.stat = readdirStreamStat; -exports.readdirSync = exports.sync = readdirSyncPath; -exports.readdirSyncStat = exports.sync.stat = readdirSyncStat; +var compilers = __webpack_require__(780); +var parsers = __webpack_require__(782); /** - * Synchronous readdir that returns an array of string paths. - * - * @param {string} dir - * @param {object} [options] - * @returns {string[]} + * Module dependencies */ -function readdirSyncPath (dir, options) { - return readdirSync(dir, options, {}); -} + +var debug = __webpack_require__(326)('expand-brackets'); +var extend = __webpack_require__(707); +var Snapdragon = __webpack_require__(692); +var toRegex = __webpack_require__(648); /** - * Synchronous readdir that returns results as an array of {@link fs.Stats} objects + * Parses the given POSIX character class `pattern` and returns a + * string that can be used for creating regular expressions for matching. * - * @param {string} dir - * @param {object} [options] - * @returns {fs.Stats[]} + * @param {String} `pattern` + * @param {Object} `options` + * @return {Object} + * @api public */ -function readdirSyncStat (dir, options) { - return readdirSync(dir, options, { stats: true }); + +function brackets(pattern, options) { + debug('initializing from <%s>', __filename); + var res = brackets.create(pattern, options); + return res.output; } /** - * Aynchronous readdir (accepts an error-first callback or returns a {@link Promise}). - * Results are an array of path strings. + * Takes an array of strings and a POSIX character class pattern, and returns a new + * array with only the strings that matched the pattern. * - * @param {string} dir - * @param {object} [options] - * @param {function} [callback] - * @returns {Promise} + * ```js + * var brackets = require('expand-brackets'); + * console.log(brackets.match(['1', 'a', 'ab'], '[[:alpha:]]')); + * //=> ['a'] + * + * console.log(brackets.match(['1', 'a', 'ab'], '[[:alpha:]]+')); + * //=> ['a', 'ab'] + * ``` + * @param {Array} `arr` Array of strings to match + * @param {String} `pattern` POSIX character class pattern(s) + * @param {Object} `options` + * @return {Array} + * @api public */ -function readdirAsyncPath (dir, options, callback) { - return readdirAsync(dir, options, callback, {}); -} + +brackets.match = function(arr, pattern, options) { + arr = [].concat(arr); + var opts = extend({}, options); + var isMatch = brackets.matcher(pattern, opts); + var len = arr.length; + var idx = -1; + var res = []; + + while (++idx < len) { + var ele = arr[idx]; + if (isMatch(ele)) { + res.push(ele); + } + } + + if (res.length === 0) { + if (opts.failglob === true) { + throw new Error('no matches found for "' + pattern + '"'); + } + + if (opts.nonull === true || opts.nullglob === true) { + return [pattern.split('\\').join('')]; + } + } + return res; +}; /** - * Aynchronous readdir (accepts an error-first callback or returns a {@link Promise}). - * Results are an array of {@link fs.Stats} objects. + * Returns true if the specified `string` matches the given + * brackets `pattern`. * - * @param {string} dir - * @param {object} [options] - * @param {function} [callback] - * @returns {Promise} + * ```js + * var brackets = require('expand-brackets'); + * + * console.log(brackets.isMatch('a.a', '[[:alpha:]].[[:alpha:]]')); + * //=> true + * console.log(brackets.isMatch('1.2', '[[:alpha:]].[[:alpha:]]')); + * //=> false + * ``` + * @param {String} `string` String to match + * @param {String} `pattern` Poxis pattern + * @param {String} `options` + * @return {Boolean} + * @api public */ -function readdirAsyncStat (dir, options, callback) { - return readdirAsync(dir, options, callback, { stats: true }); -} + +brackets.isMatch = function(str, pattern, options) { + return brackets.matcher(pattern, options)(str); +}; /** - * Aynchronous readdir that returns a {@link stream.Readable} (which is also an {@link EventEmitter}). - * All stream data events ("data", "file", "directory", "symlink") are passed a path string. + * Takes a POSIX character class pattern and returns a matcher function. The returned + * function takes the string to match as its only argument. * - * @param {string} dir - * @param {object} [options] - * @returns {stream.Readable} + * ```js + * var brackets = require('expand-brackets'); + * var isMatch = brackets.matcher('[[:lower:]].[[:upper:]]'); + * + * console.log(isMatch('a.a')); + * //=> false + * console.log(isMatch('a.A')); + * //=> true + * ``` + * @param {String} `pattern` Poxis pattern + * @param {String} `options` + * @return {Boolean} + * @api public */ -function readdirStreamPath (dir, options) { - return readdirStream(dir, options, {}); -} + +brackets.matcher = function(pattern, options) { + var re = brackets.makeRe(pattern, options); + return function(str) { + return re.test(str); + }; +}; /** - * Aynchronous readdir that returns a {@link stream.Readable} (which is also an {@link EventEmitter}) - * All stream data events ("data", "file", "directory", "symlink") are passed an {@link fs.Stats} object. + * Create a regular expression from the given `pattern`. * - * @param {string} dir - * @param {object} [options] - * @returns {stream.Readable} + * ```js + * var brackets = require('expand-brackets'); + * var re = brackets.makeRe('[[:alpha:]]'); + * console.log(re); + * //=> /^(?:[a-zA-Z])$/ + * ``` + * @param {String} `pattern` The pattern to convert to regex. + * @param {Object} `options` + * @return {RegExp} + * @api public */ -function readdirStreamStat (dir, options) { - return readdirStream(dir, options, { stats: true }); -} - - -/***/ }), -/* 756 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; +brackets.makeRe = function(pattern, options) { + var res = brackets.create(pattern, options); + var opts = extend({strictErrors: false}, options); + return toRegex(res.output, opts); +}; -module.exports = readdirSync; +/** + * Parses the given POSIX character class `pattern` and returns an object + * with the compiled `output` and optional source `map`. + * + * ```js + * var brackets = require('expand-brackets'); + * console.log(brackets('[[:alpha:]]')); + * // { options: { source: 'string' }, + * // input: '[[:alpha:]]', + * // state: {}, + * // compilers: + * // { eos: [Function], + * // noop: [Function], + * // bos: [Function], + * // not: [Function], + * // escape: [Function], + * // text: [Function], + * // posix: [Function], + * // bracket: [Function], + * // 'bracket.open': [Function], + * // 'bracket.inner': [Function], + * // 'bracket.literal': [Function], + * // 'bracket.close': [Function] }, + * // output: '[a-zA-Z]', + * // ast: + * // { type: 'root', + * // errors: [], + * // nodes: [ [Object], [Object], [Object] ] }, + * // parsingErrors: [] } + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {Object} + * @api public + */ -const DirectoryReader = __webpack_require__(757); +brackets.create = function(pattern, options) { + var snapdragon = (options && options.snapdragon) || new Snapdragon(options); + compilers(snapdragon); + parsers(snapdragon); -let syncFacade = { - fs: __webpack_require__(762), - forEach: __webpack_require__(763), - sync: true + var ast = snapdragon.parse(pattern, options); + ast.input = pattern; + var res = snapdragon.compile(ast, options); + res.input = pattern; + return res; }; /** - * Returns the buffered output from a synchronous {@link DirectoryReader}. - * - * @param {string} dir - * @param {object} [options] - * @param {object} internalOptions + * Expose `brackets` constructor, parsers and compilers */ -function readdirSync (dir, options, internalOptions) { - internalOptions.facade = syncFacade; - let reader = new DirectoryReader(dir, options, internalOptions); - let stream = reader.stream; +brackets.compilers = compilers; +brackets.parsers = parsers; - let results = []; - let data = stream.read(); - while (data !== null) { - results.push(data); - data = stream.read(); - } +/** + * Expose `brackets` + * @type {Function} + */ - return results; -} +module.exports = brackets; /***/ }), -/* 757 */ +/* 780 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const Readable = __webpack_require__(294).Readable; -const EventEmitter = __webpack_require__(285).EventEmitter; -const path = __webpack_require__(4); -const normalizeOptions = __webpack_require__(758); -const stat = __webpack_require__(760); -const call = __webpack_require__(761); +var posix = __webpack_require__(781); -/** - * Asynchronously reads the contents of a directory and streams the results - * via a {@link stream.Readable}. - */ -class DirectoryReader { - /** - * @param {string} dir - The absolute or relative directory path to read - * @param {object} [options] - User-specified options, if any (see {@link normalizeOptions}) - * @param {object} internalOptions - Internal options that aren't part of the public API - * @class - */ - constructor (dir, options, internalOptions) { - this.options = options = normalizeOptions(options, internalOptions); +module.exports = function(brackets) { + brackets.compiler - // Indicates whether we should keep reading - // This is set false if stream.Readable.push() returns false. - this.shouldRead = true; + /** + * Escaped characters + */ - // The directories to read - // (initialized with the top-level directory) - this.queue = [{ - path: dir, - basePath: options.basePath, - posixBasePath: options.posixBasePath, - depth: 0 - }]; + .set('escape', function(node) { + return this.emit('\\' + node.val.replace(/^\\/, ''), node); + }) - // The number of directories that are currently being processed - this.pending = 0; + /** + * Text + */ - // The data that has been read, but not yet emitted - this.buffer = []; + .set('text', function(node) { + return this.emit(node.val.replace(/([{}])/g, '\\$1'), node); + }) - this.stream = new Readable({ objectMode: true }); - this.stream._read = () => { - // Start (or resume) reading - this.shouldRead = true; + /** + * POSIX character classes + */ - // If we have data in the buffer, then send the next chunk - if (this.buffer.length > 0) { - this.pushFromBuffer(); + .set('posix', function(node) { + if (node.val === '[::]') { + return this.emit('\\[::\\]', node); } - // If we have directories queued, then start processing the next one - if (this.queue.length > 0) { - if (this.options.facade.sync) { - while (this.queue.length > 0) { - this.readNextDirectory(); - } - } - else { - this.readNextDirectory(); - } + var val = posix[node.inner]; + if (typeof val === 'undefined') { + val = '[' + node.inner + ']'; } + return this.emit(val, node); + }) - this.checkForEOF(); - }; - } + /** + * Non-posix brackets + */ - /** - * Reads the next directory in the queue - */ - readNextDirectory () { - let facade = this.options.facade; - let dir = this.queue.shift(); - this.pending++; + .set('bracket', function(node) { + return this.mapVisit(node.nodes); + }) + .set('bracket.open', function(node) { + return this.emit(node.val, node); + }) + .set('bracket.inner', function(node) { + var inner = node.val; - // Read the directory listing - call.safe(facade.fs.readdir, dir.path, (err, items) => { - if (err) { - // fs.readdir threw an error - this.emit('error', err); - return this.finishedReadingDirectory(); + if (inner === '[' || inner === ']') { + return this.emit('\\' + node.val, node); + } + if (inner === '^]') { + return this.emit('^\\]', node); + } + if (inner === '^') { + return this.emit('^', node); } - try { - // Process each item in the directory (simultaneously, if async) - facade.forEach( - items, - this.processItem.bind(this, dir), - this.finishedReadingDirectory.bind(this, dir) - ); + if (/-/.test(inner) && !/(\d-\d|\w-\w)/.test(inner)) { + inner = inner.split('-').join('\\-'); } - catch (err2) { - // facade.forEach threw an error - // (probably because fs.readdir returned an invalid result) - this.emit('error', err2); - this.finishedReadingDirectory(); + + var isNegated = inner.charAt(0) === '^'; + // add slashes to negated brackets, per spec + if (isNegated && inner.indexOf('/') === -1) { + inner += '/'; + } + if (isNegated && inner.indexOf('.') === -1) { + inner += '.'; } + + // don't unescape `0` (octal literal) + inner = inner.replace(/\\([1-9])/g, '$1'); + return this.emit(inner, node); + }) + .set('bracket.close', function(node) { + var val = node.val.replace(/^\\/, ''); + if (node.parent.escaped === true) { + return this.emit('\\' + val, node); + } + return this.emit(val, node); }); - } +}; - /** - * This method is called after all items in a directory have been processed. - * - * NOTE: This does not necessarily mean that the reader is finished, since there may still - * be other directories queued or pending. - */ - finishedReadingDirectory () { - this.pending--; - if (this.shouldRead) { - // If we have directories queued, then start processing the next one - if (this.queue.length > 0 && this.options.facade.async) { - this.readNextDirectory(); - } +/***/ }), +/* 781 */ +/***/ (function(module, exports, __webpack_require__) { - this.checkForEOF(); - } - } +"use strict"; - /** - * Determines whether the reader has finished processing all items in all directories. - * If so, then the "end" event is fired (via {@Readable#push}) - */ - checkForEOF () { - if (this.buffer.length === 0 && // The stuff we've already read - this.pending === 0 && // The stuff we're currently reading - this.queue.length === 0) { // The stuff we haven't read yet - // There's no more stuff! - this.stream.push(null); - } - } - /** - * Processes a single item in a directory. - * - * If the item is a directory, and `option.deep` is enabled, then the item will be added - * to the directory queue. - * - * If the item meets the filter criteria, then it will be emitted to the reader's stream. - * - * @param {object} dir - A directory object from the queue - * @param {string} item - The name of the item (name only, no path) - * @param {function} done - A callback function that is called after the item has been processed - */ - processItem (dir, item, done) { - let stream = this.stream; - let options = this.options; +/** + * POSIX character classes + */ - let itemPath = dir.basePath + item; - let posixPath = dir.posixBasePath + item; - let fullPath = path.join(dir.path, item); +module.exports = { + alnum: 'a-zA-Z0-9', + alpha: 'a-zA-Z', + ascii: '\\x00-\\x7F', + blank: ' \\t', + cntrl: '\\x00-\\x1F\\x7F', + digit: '0-9', + graph: '\\x21-\\x7E', + lower: 'a-z', + print: '\\x20-\\x7E ', + punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~', + space: ' \\t\\r\\n\\v\\f', + upper: 'A-Z', + word: 'A-Za-z0-9_', + xdigit: 'A-Fa-f0-9' +}; + + +/***/ }), +/* 782 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var utils = __webpack_require__(783); +var define = __webpack_require__(723); + +/** + * Text regex + */ + +var TEXT_REGEX = '(\\[(?=.*\\])|\\])+'; +var not = utils.createRegex(TEXT_REGEX); + +/** + * Brackets parsers + */ + +function parsers(brackets) { + brackets.state = brackets.state || {}; + brackets.parser.sets.bracket = brackets.parser.sets.bracket || []; + brackets.parser + + .capture('escape', function() { + if (this.isInside('bracket')) return; + var pos = this.position(); + var m = this.match(/^\\(.)/); + if (!m) return; + + return pos({ + type: 'escape', + val: m[0] + }); + }) + + /** + * Text parser + */ + + .capture('text', function() { + if (this.isInside('bracket')) return; + var pos = this.position(); + var m = this.match(not); + if (!m || !m[0]) return; - // If `options.deep` is a number, and we've already recursed to the max depth, - // then there's no need to check fs.Stats to know if it's a directory. - // If `options.deep` is a function, then we'll need fs.Stats - let maxDepthReached = dir.depth >= options.recurseDepth; + return pos({ + type: 'text', + val: m[0] + }); + }) - // Do we need to call `fs.stat`? - let needStats = - !maxDepthReached || // we need the fs.Stats to know if it's a directory - options.stats || // the user wants fs.Stats objects returned - options.recurseFn || // we need fs.Stats for the recurse function - options.filterFn || // we need fs.Stats for the filter function - EventEmitter.listenerCount(stream, 'file') || // we need the fs.Stats to know if it's a file - EventEmitter.listenerCount(stream, 'directory') || // we need the fs.Stats to know if it's a directory - EventEmitter.listenerCount(stream, 'symlink'); // we need the fs.Stats to know if it's a symlink + /** + * POSIX character classes: "[[:alpha:][:digits:]]" + */ - // If we don't need stats, then exit early - if (!needStats) { - if (this.filter(itemPath, posixPath)) { - this.pushOrBuffer({ data: itemPath }); - } - return done(); - } + .capture('posix', function() { + var pos = this.position(); + var m = this.match(/^\[:(.*?):\](?=.*\])/); + if (!m) return; - // Get the fs.Stats object for this path - stat(options.facade.fs, fullPath, (err, stats) => { - if (err) { - // fs.stat threw an error - this.emit('error', err); - return done(); + var inside = this.isInside('bracket'); + if (inside) { + brackets.posix++; } - try { - // Add the item's path to the fs.Stats object - // The base of this path, and its separators are determined by the options - // (i.e. options.basePath and options.sep) - stats.path = itemPath; + return pos({ + type: 'posix', + insideBracket: inside, + inner: m[1], + val: m[0] + }); + }) - // Add depth of the path to the fs.Stats object for use this in the filter function - stats.depth = dir.depth; + /** + * Bracket (noop) + */ - if (this.shouldRecurse(stats, posixPath, maxDepthReached)) { - // Add this subdirectory to the queue - this.queue.push({ - path: fullPath, - basePath: itemPath + options.sep, - posixBasePath: posixPath + '/', - depth: dir.depth + 1, - }); - } + .capture('bracket', function() {}) - // Determine whether this item matches the filter criteria - if (this.filter(stats, posixPath)) { - this.pushOrBuffer({ - data: options.stats ? stats : itemPath, - file: stats.isFile(), - directory: stats.isDirectory(), - symlink: stats.isSymbolicLink(), - }); - } + /** + * Open: '[' + */ - done(); + .capture('bracket.open', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(/^\[(?=.*\])/); + if (!m) return; + + var prev = this.prev(); + var last = utils.last(prev.nodes); + + if (parsed.slice(-1) === '\\' && !this.isInside('bracket')) { + last.val = last.val.slice(0, last.val.length - 1); + return pos({ + type: 'escape', + val: m[0] + }); } - catch (err2) { - // An error occurred while processing the item - // (probably during a user-specified function, such as options.deep, options.filter, etc.) - this.emit('error', err2); - done(); + + var open = pos({ + type: 'bracket.open', + val: m[0] + }); + + if (last.type === 'bracket.open' || this.isInside('bracket')) { + open.val = '\\' + open.val; + open.type = 'bracket.inner'; + open.escaped = true; + return open; } - }); - } - /** - * Pushes the given chunk of data to the stream, or adds it to the buffer, - * depending on the state of the stream. - * - * @param {object} chunk - */ - pushOrBuffer (chunk) { - // Add the chunk to the buffer - this.buffer.push(chunk); + var node = pos({ + type: 'bracket', + nodes: [open] + }); - // If we're still reading, then immediately emit the next chunk in the buffer - // (which may or may not be the chunk that we just added) - if (this.shouldRead) { - this.pushFromBuffer(); - } - } + define(node, 'parent', prev); + define(open, 'parent', node); + this.push('bracket', node); + prev.nodes.push(node); + }) - /** - * Immediately pushes the next chunk in the buffer to the reader's stream. - * The "data" event will always be fired (via {@link Readable#push}). - * In addition, the "file", "directory", and/or "symlink" events may be fired, - * depending on the type of properties of the chunk. - */ - pushFromBuffer () { - let stream = this.stream; - let chunk = this.buffer.shift(); + /** + * Bracket text + */ - // Stream the data - try { - this.shouldRead = stream.push(chunk.data); - } - catch (err) { - this.emit('error', err); - } + .capture('bracket.inner', function() { + if (!this.isInside('bracket')) return; + var pos = this.position(); + var m = this.match(not); + if (!m || !m[0]) return; - // Also emit specific events, based on the type of chunk - chunk.file && this.emit('file', chunk.data); - chunk.symlink && this.emit('symlink', chunk.data); - chunk.directory && this.emit('directory', chunk.data); - } + var next = this.input.charAt(0); + var val = m[0]; - /** - * Determines whether the given directory meets the user-specified recursion criteria. - * If the user didn't specify recursion criteria, then this function will default to true. - * - * @param {fs.Stats} stats - The directory's {@link fs.Stats} object - * @param {string} posixPath - The item's POSIX path (used for glob matching) - * @param {boolean} maxDepthReached - Whether we've already crawled the user-specified depth - * @returns {boolean} - */ - shouldRecurse (stats, posixPath, maxDepthReached) { - let options = this.options; + var node = pos({ + type: 'bracket.inner', + val: val + }); - if (maxDepthReached) { - // We've already crawled to the maximum depth. So no more recursion. - return false; - } - else if (!stats.isDirectory()) { - // It's not a directory. So don't try to crawl it. - return false; - } - else if (options.recurseGlob) { - // Glob patterns are always tested against the POSIX path, even on Windows - // https://github.com/isaacs/node-glob#windows - return options.recurseGlob.test(posixPath); - } - else if (options.recurseRegExp) { - // Regular expressions are tested against the normal path - // (based on the OS or options.sep) - return options.recurseRegExp.test(stats.path); - } - else if (options.recurseFn) { - try { - // Run the user-specified recursion criteria - return options.recurseFn.call(null, stats); - } - catch (err) { - // An error occurred in the user's code. - // In Sync and Async modes, this will return an error. - // In Streaming mode, we emit an "error" event, but continue processing - this.emit('error', err); + if (val === '\\\\') { + return node; } - } - else { - // No recursion function was specified, and we're within the maximum depth. - // So crawl this directory. - return true; - } - } - /** - * Determines whether the given item meets the user-specified filter criteria. - * If the user didn't specify a filter, then this function will always return true. - * - * @param {string|fs.Stats} value - Either the item's path, or the item's {@link fs.Stats} object - * @param {string} posixPath - The item's POSIX path (used for glob matching) - * @returns {boolean} - */ - filter (value, posixPath) { - let options = this.options; + var first = val.charAt(0); + var last = val.slice(-1); - if (options.filterGlob) { - // Glob patterns are always tested against the POSIX path, even on Windows - // https://github.com/isaacs/node-glob#windows - return options.filterGlob.test(posixPath); - } - else if (options.filterRegExp) { - // Regular expressions are tested against the normal path - // (based on the OS or options.sep) - return options.filterRegExp.test(value.path || value); - } - else if (options.filterFn) { - try { - // Run the user-specified filter function - return options.filterFn.call(null, value); + if (first === '!') { + val = '^' + val.slice(1); } - catch (err) { - // An error occurred in the user's code. - // In Sync and Async modes, this will return an error. - // In Streaming mode, we emit an "error" event, but continue processing - this.emit('error', err); + + if (last === '\\' || (val === '^' && next === ']')) { + val += this.input[0]; + this.consume(1); } - } - else { - // No filter was specified, so match everything - return true; - } - } - /** - * Emits an event. If one of the event listeners throws an error, - * then an "error" event is emitted. - * - * @param {string} eventName - * @param {*} data - */ - emit (eventName, data) { - let stream = this.stream; + node.val = val; + return node; + }) - try { - stream.emit(eventName, data); - } - catch (err) { - if (eventName === 'error') { - // Don't recursively emit "error" events. - // If the first one fails, then just throw - throw err; - } - else { - stream.emit('error', err); - } - } - } -} + /** + * Close: ']' + */ -module.exports = DirectoryReader; + .capture('bracket.close', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(/^\]/); + if (!m) return; + var prev = this.prev(); + var last = utils.last(prev.nodes); -/***/ }), -/* 758 */ -/***/ (function(module, exports, __webpack_require__) { + if (parsed.slice(-1) === '\\' && !this.isInside('bracket')) { + last.val = last.val.slice(0, last.val.length - 1); -"use strict"; + return pos({ + type: 'escape', + val: m[0] + }); + } + var node = pos({ + type: 'bracket.close', + rest: this.input, + val: m[0] + }); -const path = __webpack_require__(4); -const globToRegExp = __webpack_require__(759); + if (last.type === 'bracket.open') { + node.type = 'bracket.inner'; + node.escaped = true; + return node; + } -module.exports = normalizeOptions; + var bracket = this.pop('bracket'); + if (!this.isType(bracket, 'bracket')) { + if (this.options.strict) { + throw new Error('missing opening "["'); + } + node.type = 'bracket.inner'; + node.escaped = true; + return node; + } -let isWindows = /^win/.test(process.platform); + bracket.nodes.push(node); + define(node, 'parent', bracket); + }); +} /** - * @typedef {Object} FSFacade - * @property {fs.readdir} readdir - * @property {fs.stat} stat - * @property {fs.lstat} lstat + * Brackets parsers */ +module.exports = parsers; + /** - * Validates and normalizes the options argument - * - * @param {object} [options] - User-specified options, if any - * @param {object} internalOptions - Internal options that aren't part of the public API - * - * @param {number|boolean|function} [options.deep] - * The number of directories to recursively traverse. Any falsy value or negative number will - * default to zero, so only the top-level contents will be returned. Set to `true` or `Infinity` - * to traverse all subdirectories. Or provide a function that accepts a {@link fs.Stats} object - * and returns a truthy value if the directory's contents should be crawled. - * - * @param {function|string|RegExp} [options.filter] - * A function that accepts a {@link fs.Stats} object and returns a truthy value if the data should - * be returned. Or a RegExp or glob string pattern, to filter by file name. - * - * @param {string} [options.sep] - * The path separator to use. By default, the OS-specific separator will be used, but this can be - * set to a specific value to ensure consistency across platforms. - * - * @param {string} [options.basePath] - * The base path to prepend to each result. If empty, then all results will be relative to `dir`. - * - * @param {FSFacade} [options.fs] - * Synchronous or asynchronous facades for Node.js File System module - * - * @param {object} [internalOptions.facade] - * Synchronous or asynchronous facades for various methods, including for the Node.js File System module - * - * @param {boolean} [internalOptions.emit] - * Indicates whether the reader should emit "file", "directory", and "symlink" events - * - * @param {boolean} [internalOptions.stats] - * Indicates whether the reader should emit {@link fs.Stats} objects instead of path strings - * - * @returns {object} + * Expose text regex */ -function normalizeOptions (options, internalOptions) { - if (options === null || options === undefined) { - options = {}; - } - else if (typeof options !== 'object') { - throw new TypeError('options must be an object'); - } - let recurseDepth, recurseFn, recurseRegExp, recurseGlob, deep = options.deep; - if (deep === null || deep === undefined) { - recurseDepth = 0; - } - else if (typeof deep === 'boolean') { - recurseDepth = deep ? Infinity : 0; - } - else if (typeof deep === 'number') { - if (deep < 0 || isNaN(deep)) { - throw new Error('options.deep must be a positive number'); - } - else if (Math.floor(deep) !== deep) { - throw new Error('options.deep must be an integer'); - } - else { - recurseDepth = deep; - } - } - else if (typeof deep === 'function') { - recurseDepth = Infinity; - recurseFn = deep; - } - else if (deep instanceof RegExp) { - recurseDepth = Infinity; - recurseRegExp = deep; - } - else if (typeof deep === 'string' && deep.length > 0) { - recurseDepth = Infinity; - recurseGlob = globToRegExp(deep, { extended: true, globstar: true }); - } - else { - throw new TypeError('options.deep must be a boolean, number, function, regular expression, or glob pattern'); - } +module.exports.TEXT_REGEX = TEXT_REGEX; - let filterFn, filterRegExp, filterGlob, filter = options.filter; - if (filter !== null && filter !== undefined) { - if (typeof filter === 'function') { - filterFn = filter; - } - else if (filter instanceof RegExp) { - filterRegExp = filter; - } - else if (typeof filter === 'string' && filter.length > 0) { - filterGlob = globToRegExp(filter, { extended: true, globstar: true }); - } - else { - throw new TypeError('options.filter must be a function, regular expression, or glob pattern'); - } - } - let sep = options.sep; - if (sep === null || sep === undefined) { - sep = path.sep; - } - else if (typeof sep !== 'string') { - throw new TypeError('options.sep must be a string'); - } +/***/ }), +/* 783 */ +/***/ (function(module, exports, __webpack_require__) { - let basePath = options.basePath; - if (basePath === null || basePath === undefined) { - basePath = ''; - } - else if (typeof basePath === 'string') { - // Append a path separator to the basePath, if necessary - if (basePath && basePath.substr(-1) !== sep) { - basePath += sep; - } - } - else { - throw new TypeError('options.basePath must be a string'); - } +"use strict"; - // Convert the basePath to POSIX (forward slashes) - // so that glob pattern matching works consistently, even on Windows - let posixBasePath = basePath; - if (posixBasePath && sep !== '/') { - posixBasePath = posixBasePath.replace(new RegExp('\\' + sep, 'g'), '/'); - /* istanbul ignore if */ - if (isWindows) { - // Convert Windows root paths (C:\) and UNCs (\\) to POSIX root paths - posixBasePath = posixBasePath.replace(/^([a-zA-Z]\:\/|\/\/)/, '/'); - } - } +var toRegex = __webpack_require__(648); +var regexNot = __webpack_require__(665); +var cached; - // Determine which facade methods to use - let facade; - if (options.fs === null || options.fs === undefined) { - // The user didn't provide their own facades, so use our internal ones - facade = internalOptions.facade; - } - else if (typeof options.fs === 'object') { - // Merge the internal facade methods with the user-provided `fs` facades - facade = Object.assign({}, internalOptions.facade); - facade.fs = Object.assign({}, internalOptions.facade.fs, options.fs); - } - else { - throw new TypeError('options.fs must be an object'); +/** + * Get the last element from `array` + * @param {Array} `array` + * @return {*} + */ + +exports.last = function(arr) { + return arr[arr.length - 1]; +}; + +/** + * Create and cache regex to use for text nodes + */ + +exports.createRegex = function(pattern, include) { + if (cached) return cached; + var opts = {contains: true, strictClose: false}; + var not = regexNot.create(pattern, opts); + var re; + + if (typeof include === 'string') { + re = toRegex('^(?:' + include + '|' + not + ')', opts); + } else { + re = toRegex(not, opts); } - return { - recurseDepth, - recurseFn, - recurseRegExp, - recurseGlob, - filterFn, - filterRegExp, - filterGlob, - sep, - basePath, - posixBasePath, - facade, - emit: !!internalOptions.emit, - stats: !!internalOptions.stats, - }; -} + return (cached = re); +}; /***/ }), -/* 759 */ -/***/ (function(module, exports) { +/* 784 */ +/***/ (function(module, exports, __webpack_require__) { -module.exports = function (glob, opts) { - if (typeof glob !== 'string') { - throw new TypeError('Expected a string'); - } +"use strict"; - var str = String(glob); - // The regexp we are building, as a string. - var reStr = ""; +var brackets = __webpack_require__(779); +var define = __webpack_require__(785); +var utils = __webpack_require__(786); - // Whether we are matching so called "extended" globs (like bash) and should - // support single character matching, matching ranges of characters, group - // matching, etc. - var extended = opts ? !!opts.extended : false; +/** + * Characters to use in text regex (we want to "not" match + * characters that are matched by other parsers) + */ - // When globstar is _false_ (default), '/foo/*' is translated a regexp like - // '^\/foo\/.*$' which will match any string beginning with '/foo/' - // When globstar is _true_, '/foo/*' is translated to regexp like - // '^\/foo\/[^/]*$' which will match any string beginning with '/foo/' BUT - // which does not have a '/' to the right of it. - // E.g. with '/foo/*' these will match: '/foo/bar', '/foo/bar.txt' but - // these will not '/foo/bar/baz', '/foo/bar/baz.txt' - // Lastely, when globstar is _true_, '/foo/**' is equivelant to '/foo/*' when - // globstar is _false_ - var globstar = opts ? !!opts.globstar : false; +var TEXT_REGEX = '([!@*?+]?\\(|\\)|[*?.+\\\\]|\\[:?(?=.*\\])|:?\\])+'; +var not = utils.createRegex(TEXT_REGEX); - // If we are doing extended matching, this boolean is true when we are inside - // a group (eg {*.html,*.js}), and false otherwise. - var inGroup = false; +/** + * Extglob parsers + */ - // RegExp flags (eg "i" ) to pass in to RegExp constructor. - var flags = opts && typeof( opts.flags ) === "string" ? opts.flags : ""; +function parsers(extglob) { + extglob.state = extglob.state || {}; - var c; - for (var i = 0, len = str.length; i < len; i++) { - c = str[i]; + /** + * Use `expand-brackets` parsers + */ - switch (c) { - case "\\": - case "/": - case "$": - case "^": - case "+": - case ".": - case "(": - case ")": - case "=": - case "!": - case "|": - reStr += "\\" + c; - break; + extglob.use(brackets.parsers); + extglob.parser.sets.paren = extglob.parser.sets.paren || []; + extglob.parser - case "?": - if (extended) { - reStr += "."; - break; - } + /** + * Extglob open: "*(" + */ - case "[": - case "]": - if (extended) { - reStr += c; - break; - } + .capture('paren.open', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(/^([!@*?+])?\(/); + if (!m) return; - case "{": - if (extended) { - inGroup = true; - reStr += "("; - break; - } + var prev = this.prev(); + var prefix = m[1]; + var val = m[0]; - case "}": - if (extended) { - inGroup = false; - reStr += ")"; - break; - } + var open = pos({ + type: 'paren.open', + parsed: parsed, + val: val + }); - case ",": - if (inGroup) { - reStr += "|"; - break; - } - reStr += "\\" + c; - break; + var node = pos({ + type: 'paren', + prefix: prefix, + nodes: [open] + }); - case "*": - // Move over all consecutive "*"'s. - // Also store the previous and next characters - var prevChar = str[i - 1]; - var starCount = 1; - while(str[i + 1] === "*") { - starCount++; - i++; + // if nested negation extglobs, just cancel them out to simplify + if (prefix === '!' && prev.type === 'paren' && prev.prefix === '!') { + prev.prefix = '@'; + node.prefix = '@'; } - var nextChar = str[i + 1]; - if (!globstar) { - // globstar is disabled, so treat any number of "*" as one - reStr += ".*"; - } else { - // globstar is enabled, so determine if this is a globstar segment - var isGlobstar = starCount > 1 // multiple "*"'s - && (prevChar === "/" || prevChar === undefined) // from the start of the segment - && (nextChar === "/" || nextChar === undefined) // to the end of the segment + define(node, 'rest', this.input); + define(node, 'parsed', parsed); + define(node, 'parent', prev); + define(open, 'parent', node); - if (isGlobstar) { - // it's a globstar, so match zero or more path segments - reStr += "(?:[^/]*(?:\/|$))*"; - i++; // move over the "/" - } else { - // it's not a globstar, so only match one path segment - reStr += "[^/]*"; + this.push('paren', node); + prev.nodes.push(node); + }) + + /** + * Extglob close: ")" + */ + + .capture('paren.close', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(/^\)/); + if (!m) return; + + var parent = this.pop('paren'); + var node = pos({ + type: 'paren.close', + rest: this.input, + parsed: parsed, + val: m[0] + }); + + if (!this.isType(parent, 'paren')) { + if (this.options.strict) { + throw new Error('missing opening paren: "("'); } + node.escaped = true; + return node; } - break; - default: - reStr += c; - } - } + node.prefix = parent.prefix; + parent.nodes.push(node); + define(node, 'parent', parent); + }) - // When regexp 'g' flag is specified don't - // constrain the regular expression with ^ & $ - if (!flags || !~flags.indexOf('g')) { - reStr = "^" + reStr + "$"; - } + /** + * Escape: "\\." + */ - return new RegExp(reStr, flags); -}; + .capture('escape', function() { + var pos = this.position(); + var m = this.match(/^\\(.)/); + if (!m) return; + return pos({ + type: 'escape', + val: m[0], + ch: m[1] + }); + }) -/***/ }), -/* 760 */ -/***/ (function(module, exports, __webpack_require__) { + /** + * Question marks: "?" + */ -"use strict"; + .capture('qmark', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(/^\?+(?!\()/); + if (!m) return; + extglob.state.metachar = true; + return pos({ + type: 'qmark', + rest: this.input, + parsed: parsed, + val: m[0] + }); + }) + + /** + * Character parsers + */ + .capture('star', /^\*(?!\()/) + .capture('plus', /^\+(?!\()/) + .capture('dot', /^\./) + .capture('text', not); +}; -const call = __webpack_require__(761); +/** + * Expose text regex string + */ -module.exports = stat; +module.exports.TEXT_REGEX = TEXT_REGEX; /** - * Retrieves the {@link fs.Stats} for the given path. If the path is a symbolic link, - * then the Stats of the symlink's target are returned instead. If the symlink is broken, - * then the Stats of the symlink itself are returned. - * - * @param {object} fs - Synchronous or Asynchronouse facade for the "fs" module - * @param {string} path - The path to return stats for - * @param {function} callback + * Extglob parsers */ -function stat (fs, path, callback) { - let isSymLink = false; - call.safe(fs.lstat, path, (err, lstats) => { - if (err) { - // fs.lstat threw an eror - return callback(err); - } +module.exports = parsers; - try { - isSymLink = lstats.isSymbolicLink(); - } - catch (err2) { - // lstats.isSymbolicLink() threw an error - // (probably because fs.lstat returned an invalid result) - return callback(err2); - } - if (isSymLink) { - // Try to resolve the symlink - symlinkStat(fs, path, lstats, callback); - } - else { - // It's not a symlink, so return the stats as-is - callback(null, lstats); - } - }); -} +/***/ }), +/* 785 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * Retrieves the {@link fs.Stats} for the target of the given symlink. - * If the symlink is broken, then the Stats of the symlink itself are returned. +"use strict"; +/*! + * define-property * - * @param {object} fs - Synchronous or Asynchronouse facade for the "fs" module - * @param {string} path - The path of the symlink to return stats for - * @param {object} lstats - The stats of the symlink - * @param {function} callback + * Copyright (c) 2015, 2017, Jon Schlinkert. + * Released under the MIT License. */ -function symlinkStat (fs, path, lstats, callback) { - call.safe(fs.stat, path, (err, stats) => { - if (err) { - // The symlink is broken, so return the stats for the link itself - return callback(null, lstats); - } - try { - // Return the stats for the resolved symlink target, - // and override the `isSymbolicLink` method to indicate that it's a symlink - stats.isSymbolicLink = () => true; - } - catch (err2) { - // Setting stats.isSymbolicLink threw an error - // (probably because fs.stat returned an invalid result) - return callback(err2); - } - callback(null, stats); + +var isDescriptor = __webpack_require__(657); + +module.exports = function defineProperty(obj, prop, val) { + if (typeof obj !== 'object' && typeof obj !== 'function') { + throw new TypeError('expected an object or function.'); + } + + if (typeof prop !== 'string') { + throw new TypeError('expected `prop` to be a string.'); + } + + if (isDescriptor(val) && ('set' in val || 'get' in val)) { + return Object.defineProperty(obj, prop, val); + } + + return Object.defineProperty(obj, prop, { + configurable: true, + enumerable: false, + writable: true, + value: val }); -} +}; /***/ }), -/* 761 */ +/* 786 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -let call = module.exports = { - safe: safeCall, - once: callOnce, +var regex = __webpack_require__(665); +var Cache = __webpack_require__(771); + +/** + * Utils + */ + +var utils = module.exports; +var cache = utils.cache = new Cache(); + +/** + * Cast `val` to an array + * @return {Array} + */ + +utils.arrayify = function(val) { + if (!Array.isArray(val)) { + return [val]; + } + return val; }; /** - * Calls a function with the given arguments, and ensures that the error-first callback is _always_ - * invoked exactly once, even if the function throws an error. - * - * @param {function} fn - The function to invoke - * @param {...*} args - The arguments to pass to the function. The final argument must be a callback function. + * Memoize a generated regex or function */ -function safeCall (fn, args) { - // Get the function arguments as an array - args = Array.prototype.slice.call(arguments, 1); - // Replace the callback function with a wrapper that ensures it will only be called once - let callback = call.once(args.pop()); - args.push(callback); +utils.memoize = function(type, pattern, options, fn) { + var key = utils.createKey(type + pattern, options); - try { - fn.apply(null, args); + if (cache.has(type, key)) { + return cache.get(type, key); } - catch (err) { - callback(err); + + var val = fn(pattern, options); + if (options && options.cache === false) { + return val; } -} + + cache.set(type, key, val); + return val; +}; /** - * Returns a wrapper function that ensures the given callback function is only called once. - * Subsequent calls are ignored, unless the first argument is an Error, in which case the - * error is thrown. - * - * @param {function} fn - The function that should only be called once - * @returns {function} + * Create the key to use for memoization. The key is generated + * by iterating over the options and concatenating key-value pairs + * to the pattern string. */ -function callOnce (fn) { - let fulfilled = false; - return function onceWrapper (err) { - if (!fulfilled) { - fulfilled = true; - return fn.apply(this, arguments); - } - else if (err) { - // The callback has already been called, but now an error has occurred - // (most likely inside the callback function). So re-throw the error, - // so it gets handled further up the call stack - throw err; - } - }; -} +utils.createKey = function(pattern, options) { + var key = pattern; + if (typeof options === 'undefined') { + return key; + } + for (var prop in options) { + key += ';' + prop + '=' + String(options[prop]); + } + return key; +}; + +/** + * Create the regex to use for matching text + */ + +utils.createRegex = function(str) { + var opts = {contains: true, strictClose: false}; + return regex(str, opts); +}; /***/ }), -/* 762 */ +/* 787 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const fs = __webpack_require__(253); -const call = __webpack_require__(761); +/** + * Module dependencies + */ + +var Snapdragon = __webpack_require__(692); +var define = __webpack_require__(785); +var extend = __webpack_require__(707); /** - * A facade around {@link fs.readdirSync} that allows it to be called - * the same way as {@link fs.readdir}. - * - * @param {string} dir - * @param {function} callback + * Local dependencies */ -exports.readdir = function (dir, callback) { - // Make sure the callback is only called once - callback = call.once(callback); - try { - let items = fs.readdirSync(dir); - callback(null, items); - } - catch (err) { - callback(err); - } -}; +var compilers = __webpack_require__(778); +var parsers = __webpack_require__(784); + +/** + * Customize Snapdragon parser and renderer + */ + +function Extglob(options) { + this.options = extend({source: 'extglob'}, options); + this.snapdragon = this.options.snapdragon || new Snapdragon(this.options); + this.snapdragon.patterns = this.snapdragon.patterns || {}; + this.compiler = this.snapdragon.compiler; + this.parser = this.snapdragon.parser; + + compilers(this.snapdragon); + parsers(this.snapdragon); + + /** + * Override Snapdragon `.parse` method + */ + + define(this.snapdragon, 'parse', function(str, options) { + var parsed = Snapdragon.prototype.parse.apply(this, arguments); + parsed.input = str; + + // escape unmatched brace/bracket/parens + var last = this.parser.stack.pop(); + if (last && this.options.strict !== true) { + var node = last.nodes[0]; + node.val = '\\' + node.val; + var sibling = node.parent.nodes[1]; + if (sibling.type === 'star') { + sibling.loose = true; + } + } + + // add non-enumerable parser reference + define(parsed, 'parser', this.parser); + return parsed; + }); + + /** + * Decorate `.parse` method + */ + + define(this, 'parse', function(ast, options) { + return this.snapdragon.parse.apply(this.snapdragon, arguments); + }); + + /** + * Decorate `.compile` method + */ -/** - * A facade around {@link fs.statSync} that allows it to be called - * the same way as {@link fs.stat}. - * - * @param {string} path - * @param {function} callback - */ -exports.stat = function (path, callback) { - // Make sure the callback is only called once - callback = call.once(callback); + define(this, 'compile', function(ast, options) { + return this.snapdragon.compile.apply(this.snapdragon, arguments); + }); - try { - let stats = fs.statSync(path); - callback(null, stats); - } - catch (err) { - callback(err); - } -}; +} /** - * A facade around {@link fs.lstatSync} that allows it to be called - * the same way as {@link fs.lstat}. - * - * @param {string} path - * @param {function} callback + * Expose `Extglob` */ -exports.lstat = function (path, callback) { - // Make sure the callback is only called once - callback = call.once(callback); - try { - let stats = fs.lstatSync(path); - callback(null, stats); - } - catch (err) { - callback(err); - } -}; +module.exports = Extglob; /***/ }), -/* 763 */ +/* 788 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -module.exports = syncForEach; +var extglob = __webpack_require__(777); +var nanomatch = __webpack_require__(763); +var regexNot = __webpack_require__(665); +var toRegex = __webpack_require__(648); +var not; /** - * A facade that allows {@link Array.forEach} to be called as though it were asynchronous. - * - * @param {array} array - The array to iterate over - * @param {function} iterator - The function to call for each item in the array - * @param {function} done - The function to call when all iterators have completed + * Characters to use in negation regex (we want to "not" match + * characters that are matched by other parsers) */ -function syncForEach (array, iterator, done) { - array.forEach(item => { - iterator(item, () => { - // Note: No error-handling here because this is currently only ever called - // by DirectoryReader, which never passes an `error` parameter to the callback. - // Instead, DirectoryReader emits an "error" event if an error occurs. - }); - }); - done(); -} +var TEXT = '([!@*?+]?\\(|\\)|\\[:?(?=.*?:?\\])|:?\\]|[*+?!^$.\\\\/])+'; +var createNotRegex = function(opts) { + return not || (not = textRegex(TEXT)); +}; +/** + * Parsers + */ -/***/ }), -/* 764 */ -/***/ (function(module, exports, __webpack_require__) { +module.exports = function(snapdragon) { + var parsers = snapdragon.parser.parsers; -"use strict"; + // register nanomatch parsers + snapdragon.use(nanomatch.parsers); + + // get references to some specific nanomatch parsers before they + // are overridden by the extglob and/or parsers + var escape = parsers.escape; + var slash = parsers.slash; + var qmark = parsers.qmark; + var plus = parsers.plus; + var star = parsers.star; + var dot = parsers.dot; + // register extglob parsers + snapdragon.use(extglob.parsers); -module.exports = readdirAsync; + // custom micromatch parsers + snapdragon.parser + .use(function() { + // override "notRegex" created in nanomatch parser + this.notRegex = /^\!+(?!\()/; + }) + // reset the referenced parsers + .capture('escape', escape) + .capture('slash', slash) + .capture('qmark', qmark) + .capture('star', star) + .capture('plus', plus) + .capture('dot', dot) -const maybe = __webpack_require__(765); -const DirectoryReader = __webpack_require__(757); + /** + * Override `text` parser + */ -let asyncFacade = { - fs: __webpack_require__(253), - forEach: __webpack_require__(766), - async: true + .capture('text', function() { + if (this.isInside('bracket')) return; + var pos = this.position(); + var m = this.match(createNotRegex(this.options)); + if (!m || !m[0]) return; + + // escape regex boundary characters and simple brackets + var val = m[0].replace(/([[\]^$])/g, '\\$1'); + + return pos({ + type: 'text', + val: val + }); + }); }; /** - * Returns the buffered output from an asynchronous {@link DirectoryReader}, - * via an error-first callback or a {@link Promise}. - * - * @param {string} dir - * @param {object} [options] - * @param {function} [callback] - * @param {object} internalOptions + * Create text regex */ -function readdirAsync (dir, options, callback, internalOptions) { - if (typeof options === 'function') { - callback = options; - options = undefined; - } - return maybe(callback, new Promise(((resolve, reject) => { - let results = []; +function textRegex(pattern) { + var notStr = regexNot.create(pattern, {contains: true, strictClose: false}); + var prefix = '(?:[\\^]|\\\\|'; + return toRegex(prefix + notStr + ')', {strictClose: false}); +} - internalOptions.facade = asyncFacade; - let reader = new DirectoryReader(dir, options, internalOptions); - let stream = reader.stream; +/***/ }), +/* 789 */ +/***/ (function(module, exports, __webpack_require__) { - stream.on('error', err => { - reject(err); - stream.pause(); - }); - stream.on('data', result => { - results.push(result); - }); - stream.on('end', () => { - resolve(results); - }); - }))); -} +module.exports = new (__webpack_require__(771))(); /***/ }), -/* 765 */ +/* 790 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var next = (global.process && process.nextTick) || global.setImmediate || function (f) { - setTimeout(f, 0) -} - -module.exports = function maybe (cb, promise) { - if (cb) { - promise - .then(function (result) { - next(function () { cb(null, result) }) - }, function (err) { - next(function () { cb(err) }) - }) - return undefined - } - else { - return promise - } -} - +var utils = module.exports; +var path = __webpack_require__(4); -/***/ }), -/* 766 */ -/***/ (function(module, exports, __webpack_require__) { +/** + * Module dependencies + */ -"use strict"; +var Snapdragon = __webpack_require__(692); +utils.define = __webpack_require__(791); +utils.diff = __webpack_require__(775); +utils.extend = __webpack_require__(760); +utils.pick = __webpack_require__(776); +utils.typeOf = __webpack_require__(658); +utils.unique = __webpack_require__(668); +/** + * Returns true if the platform is windows, or `path.sep` is `\\`. + * This is defined as a function to allow `path.sep` to be set in unit tests, + * or by the user, if there is a reason to do so. + * @return {Boolean} + */ -module.exports = asyncForEach; +utils.isWindows = function() { + return path.sep === '\\' || process.platform === 'win32'; +}; /** - * Simultaneously processes all items in the given array. - * - * @param {array} array - The array to iterate over - * @param {function} iterator - The function to call for each item in the array - * @param {function} done - The function to call when all iterators have completed + * Get the `Snapdragon` instance to use */ -function asyncForEach (array, iterator, done) { - if (array.length === 0) { - // NOTE: Normally a bad idea to mix sync and async, but it's safe here because - // of the way that this method is currently used by DirectoryReader. - done(); - return; - } - // Simultaneously process all items in the array. - let pending = array.length; - array.forEach(item => { - iterator(item, () => { - if (--pending === 0) { - done(); - } - }); - }); -} +utils.instantiate = function(ast, options) { + var snapdragon; + // if an instance was created by `.parse`, use that instance + if (utils.typeOf(ast) === 'object' && ast.snapdragon) { + snapdragon = ast.snapdragon; + // if the user supplies an instance on options, use that instance + } else if (utils.typeOf(options) === 'object' && options.snapdragon) { + snapdragon = options.snapdragon; + // create a new instance + } else { + snapdragon = new Snapdragon(options); + } + utils.define(snapdragon, 'parse', function(str, options) { + var parsed = Snapdragon.prototype.parse.apply(this, arguments); + parsed.input = str; -/***/ }), -/* 767 */ -/***/ (function(module, exports, __webpack_require__) { + // escape unmatched brace/bracket/parens + var last = this.parser.stack.pop(); + if (last && this.options.strictErrors !== true) { + var open = last.nodes[0]; + var inner = last.nodes[1]; + if (last.type === 'bracket') { + if (inner.val.charAt(0) === '[') { + inner.val = '\\' + inner.val; + } -"use strict"; + } else { + open.val = '\\' + open.val; + var sibling = open.parent.nodes[1]; + if (sibling.type === 'star') { + sibling.loose = true; + } + } + } + // add non-enumerable parser reference + utils.define(parsed, 'parser', this.parser); + return parsed; + }); -module.exports = readdirStream; + return snapdragon; +}; -const DirectoryReader = __webpack_require__(757); +/** + * Create the key to use for memoization. The key is generated + * by iterating over the options and concatenating key-value pairs + * to the pattern string. + */ -let streamFacade = { - fs: __webpack_require__(253), - forEach: __webpack_require__(766), - async: true +utils.createKey = function(pattern, options) { + if (utils.typeOf(options) !== 'object') { + return pattern; + } + var val = pattern; + var keys = Object.keys(options); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + val += ';' + key + '=' + String(options[key]); + } + return val; }; /** - * Returns the {@link stream.Readable} of an asynchronous {@link DirectoryReader}. - * - * @param {string} dir - * @param {object} [options] - * @param {object} internalOptions + * Cast `val` to an array + * @return {Array} */ -function readdirStream (dir, options, internalOptions) { - internalOptions.facade = streamFacade; - let reader = new DirectoryReader(dir, options, internalOptions); - return reader.stream; -} +utils.arrayify = function(val) { + if (typeof val === 'string') return [val]; + return val ? (Array.isArray(val) ? val : [val]) : []; +}; +/** + * Return true if `val` is a non-empty string + */ -/***/ }), -/* 768 */ -/***/ (function(module, exports, __webpack_require__) { +utils.isString = function(val) { + return typeof val === 'string'; +}; -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var path = __webpack_require__(4); -var deep_1 = __webpack_require__(769); -var entry_1 = __webpack_require__(771); -var pathUtil = __webpack_require__(770); -var Reader = /** @class */ (function () { - function Reader(options) { - this.options = options; - this.micromatchOptions = this.getMicromatchOptions(); - this.entryFilter = new entry_1.default(options, this.micromatchOptions); - this.deepFilter = new deep_1.default(options, this.micromatchOptions); - } - /** - * Returns root path to scanner. - */ - Reader.prototype.getRootDirectory = function (task) { - return path.resolve(this.options.cwd, task.base); - }; - /** - * Returns options for reader. - */ - Reader.prototype.getReaderOptions = function (task) { - return { - basePath: task.base === '.' ? '' : task.base, - filter: this.entryFilter.getFilter(task.positive, task.negative), - deep: this.deepFilter.getFilter(task.positive, task.negative), - sep: '/' - }; - }; - /** - * Returns options for micromatch. - */ - Reader.prototype.getMicromatchOptions = function () { - return { - dot: this.options.dot, - nobrace: !this.options.brace, - noglobstar: !this.options.globstar, - noext: !this.options.extension, - nocase: !this.options.case, - matchBase: this.options.matchBase - }; - }; - /** - * Returns transformed entry. - */ - Reader.prototype.transform = function (entry) { - if (this.options.absolute) { - entry.path = pathUtil.makeAbsolute(this.options.cwd, entry.path); - } - if (this.options.markDirectories && entry.isDirectory()) { - entry.path += '/'; - } - var item = this.options.stats ? entry : entry.path; - if (this.options.transform === null) { - return item; - } - return this.options.transform(item); - }; - /** - * Returns true if error has ENOENT code. - */ - Reader.prototype.isEnoentCodeError = function (err) { - return err.code === 'ENOENT'; - }; - return Reader; -}()); -exports.default = Reader; +/** + * Return true if `val` is a non-empty string + */ +utils.isObject = function(val) { + return utils.typeOf(val) === 'object'; +}; -/***/ }), -/* 769 */ -/***/ (function(module, exports, __webpack_require__) { +/** + * Returns true if the given `str` has special characters + */ -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var pathUtils = __webpack_require__(770); -var patternUtils = __webpack_require__(604); -var DeepFilter = /** @class */ (function () { - function DeepFilter(options, micromatchOptions) { - this.options = options; - this.micromatchOptions = micromatchOptions; - } - /** - * Returns filter for directories. - */ - DeepFilter.prototype.getFilter = function (positive, negative) { - var _this = this; - var maxPatternDepth = this.getMaxPatternDepth(positive); - var negativeRe = this.getNegativePatternsRe(negative); - return function (entry) { return _this.filter(entry, negativeRe, maxPatternDepth); }; - }; - /** - * Returns max depth of the provided patterns. - */ - DeepFilter.prototype.getMaxPatternDepth = function (patterns) { - var globstar = patterns.some(patternUtils.hasGlobStar); - return globstar ? Infinity : patternUtils.getMaxNaivePatternsDepth(patterns); - }; - /** - * Returns RegExp's for patterns that can affect the depth of reading. - */ - DeepFilter.prototype.getNegativePatternsRe = function (patterns) { - var affectDepthOfReadingPatterns = patterns.filter(patternUtils.isAffectDepthOfReadingPattern); - return patternUtils.convertPatternsToRe(affectDepthOfReadingPatterns, this.micromatchOptions); - }; - /** - * Returns «true» for directory that should be read. - */ - DeepFilter.prototype.filter = function (entry, negativeRe, maxPatternDepth) { - if (this.isSkippedByDeepOption(entry.depth)) { - return false; - } - if (this.isSkippedByMaxPatternDepth(entry.depth, maxPatternDepth)) { - return false; - } - if (this.isSkippedSymlinkedDirectory(entry)) { - return false; - } - if (this.isSkippedDotDirectory(entry)) { - return false; - } - return this.isSkippedByNegativePatterns(entry, negativeRe); - }; - /** - * Returns «true» when the «deep» option is disabled or number and depth of the entry is greater that the option value. - */ - DeepFilter.prototype.isSkippedByDeepOption = function (entryDepth) { - return !this.options.deep || (typeof this.options.deep === 'number' && entryDepth >= this.options.deep); - }; - /** - * Returns «true» when depth parameter is not an Infinity and entry depth greater that the parameter value. - */ - DeepFilter.prototype.isSkippedByMaxPatternDepth = function (entryDepth, maxPatternDepth) { - return maxPatternDepth !== Infinity && entryDepth >= maxPatternDepth; - }; - /** - * Returns «true» for symlinked directory if the «followSymlinkedDirectories» option is disabled. - */ - DeepFilter.prototype.isSkippedSymlinkedDirectory = function (entry) { - return !this.options.followSymlinkedDirectories && entry.isSymbolicLink(); - }; - /** - * Returns «true» for a directory whose name starts with a period if «dot» option is disabled. - */ - DeepFilter.prototype.isSkippedDotDirectory = function (entry) { - return !this.options.dot && pathUtils.isDotDirectory(entry.path); - }; - /** - * Returns «true» for a directory whose path math to any negative pattern. - */ - DeepFilter.prototype.isSkippedByNegativePatterns = function (entry, negativeRe) { - return !patternUtils.matchAny(entry.path, negativeRe); - }; - return DeepFilter; -}()); -exports.default = DeepFilter; +utils.hasSpecialChars = function(str) { + return /(?:(?:(^|\/)[!.])|[*?+()|\[\]{}]|[+@]\()/.test(str); +}; +/** + * Escape regex characters in the given string + */ -/***/ }), -/* 770 */ -/***/ (function(module, exports, __webpack_require__) { +utils.escapeRegex = function(str) { + return str.replace(/[-[\]{}()^$|*+?.\\\/\s]/g, '\\$&'); +}; -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var path = __webpack_require__(4); -/** - * Returns «true» if the last partial of the path starting with a period. - */ -function isDotDirectory(filepath) { - return path.basename(filepath).startsWith('.'); -} -exports.isDotDirectory = isDotDirectory; -/** - * Convert a windows-like path to a unix-style path. - */ -function normalize(filepath) { - return filepath.replace(/\\/g, '/'); -} -exports.normalize = normalize; -/** - * Returns normalized absolute path of provided filepath. - */ -function makeAbsolute(cwd, filepath) { - return normalize(path.resolve(cwd, filepath)); -} -exports.makeAbsolute = makeAbsolute; +/** + * Normalize slashes in the given filepath. + * + * @param {String} `filepath` + * @return {String} + */ +utils.toPosixPath = function(str) { + return str.replace(/\\+/g, '/'); +}; -/***/ }), -/* 771 */ -/***/ (function(module, exports, __webpack_require__) { +/** + * Strip backslashes before special characters in a string. + * + * @param {String} `str` + * @return {String} + */ -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var pathUtils = __webpack_require__(770); -var patternUtils = __webpack_require__(604); -var EntryFilter = /** @class */ (function () { - function EntryFilter(options, micromatchOptions) { - this.options = options; - this.micromatchOptions = micromatchOptions; - this.index = new Map(); - } - /** - * Returns filter for directories. - */ - EntryFilter.prototype.getFilter = function (positive, negative) { - var _this = this; - var positiveRe = patternUtils.convertPatternsToRe(positive, this.micromatchOptions); - var negativeRe = patternUtils.convertPatternsToRe(negative, this.micromatchOptions); - return function (entry) { return _this.filter(entry, positiveRe, negativeRe); }; - }; - /** - * Returns true if entry must be added to result. - */ - EntryFilter.prototype.filter = function (entry, positiveRe, negativeRe) { - // Exclude duplicate results - if (this.options.unique) { - if (this.isDuplicateEntry(entry)) { - return false; - } - this.createIndexRecord(entry); - } - // Filter files and directories by options - if (this.onlyFileFilter(entry) || this.onlyDirectoryFilter(entry)) { - return false; - } - if (this.isSkippedByAbsoluteNegativePatterns(entry, negativeRe)) { - return false; - } - return this.isMatchToPatterns(entry.path, positiveRe) && !this.isMatchToPatterns(entry.path, negativeRe); - }; - /** - * Return true if the entry already has in the cross reader index. - */ - EntryFilter.prototype.isDuplicateEntry = function (entry) { - return this.index.has(entry.path); - }; - /** - * Create record in the cross reader index. - */ - EntryFilter.prototype.createIndexRecord = function (entry) { - this.index.set(entry.path, undefined); - }; - /** - * Returns true for non-files if the «onlyFiles» option is enabled. - */ - EntryFilter.prototype.onlyFileFilter = function (entry) { - return this.options.onlyFiles && !entry.isFile(); - }; - /** - * Returns true for non-directories if the «onlyDirectories» option is enabled. - */ - EntryFilter.prototype.onlyDirectoryFilter = function (entry) { - return this.options.onlyDirectories && !entry.isDirectory(); - }; - /** - * Return true when `absolute` option is enabled and matched to the negative patterns. - */ - EntryFilter.prototype.isSkippedByAbsoluteNegativePatterns = function (entry, negativeRe) { - if (!this.options.absolute) { - return false; - } - var fullpath = pathUtils.makeAbsolute(this.options.cwd, entry.path); - return this.isMatchToPatterns(fullpath, negativeRe); - }; - /** - * Return true when entry match to provided patterns. - * - * First, just trying to apply patterns to the path. - * Second, trying to apply patterns to the path with final slash (need to micromatch to support «directory/**» patterns). - */ - EntryFilter.prototype.isMatchToPatterns = function (filepath, patternsRe) { - return patternUtils.matchAny(filepath, patternsRe) || patternUtils.matchAny(filepath + '/', patternsRe); - }; - return EntryFilter; -}()); -exports.default = EntryFilter; +utils.unescape = function(str) { + return utils.toPosixPath(str.replace(/\\(?=[*+?!.])/g, '')); +}; +/** + * Strip the prefix from a filepath + * @param {String} `fp` + * @return {String} + */ -/***/ }), -/* 772 */ -/***/ (function(module, exports, __webpack_require__) { +utils.stripPrefix = function(str) { + if (str.charAt(0) !== '.') { + return str; + } + var ch = str.charAt(1); + if (utils.isSlash(ch)) { + return str.slice(2); + } + return str; +}; -"use strict"; - -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -var stream = __webpack_require__(294); -var fsStat = __webpack_require__(773); -var fs_1 = __webpack_require__(777); -var FileSystemStream = /** @class */ (function (_super) { - __extends(FileSystemStream, _super); - function FileSystemStream() { - return _super !== null && _super.apply(this, arguments) || this; - } - /** - * Use stream API to read entries for Task. - */ - FileSystemStream.prototype.read = function (patterns, filter) { - var _this = this; - var filepaths = patterns.map(this.getFullEntryPath, this); - var transform = new stream.Transform({ objectMode: true }); - transform._transform = function (index, _enc, done) { - return _this.getEntry(filepaths[index], patterns[index]).then(function (entry) { - if (entry !== null && filter(entry)) { - transform.push(entry); - } - if (index === filepaths.length - 1) { - transform.end(); - } - done(); - }); - }; - for (var i = 0; i < filepaths.length; i++) { - transform.write(i); - } - return transform; - }; - /** - * Return entry for the provided path. - */ - FileSystemStream.prototype.getEntry = function (filepath, pattern) { - var _this = this; - return this.getStat(filepath) - .then(function (stat) { return _this.makeEntry(stat, pattern); }) - .catch(function () { return null; }); - }; - /** - * Return fs.Stats for the provided path. - */ - FileSystemStream.prototype.getStat = function (filepath) { - return fsStat.stat(filepath, { throwErrorOnBrokenSymlinks: false }); - }; - return FileSystemStream; -}(fs_1.default)); -exports.default = FileSystemStream; +/** + * Returns true if the given str is an escaped or + * unescaped path character + */ +utils.isSlash = function(str) { + return str === '/' || str === '\\/' || str === '\\' || str === '\\\\'; +}; -/***/ }), -/* 773 */ -/***/ (function(module, exports, __webpack_require__) { +/** + * Returns a function that returns true if the given + * pattern matches or contains a `filepath` + * + * @param {String} `pattern` + * @return {Function} + */ -"use strict"; +utils.matchPath = function(pattern, options) { + return (options && options.contains) + ? utils.containsPattern(pattern, options) + : utils.equalsPattern(pattern, options); +}; -Object.defineProperty(exports, "__esModule", { value: true }); -const optionsManager = __webpack_require__(774); -const statProvider = __webpack_require__(776); /** - * Asynchronous API. + * Returns true if the given (original) filepath or unixified path are equal + * to the given pattern. */ -function stat(path, opts) { - return new Promise((resolve, reject) => { - statProvider.async(path, optionsManager.prepare(opts), (err, stats) => err ? reject(err) : resolve(stats)); - }); -} -exports.stat = stat; -function statCallback(path, optsOrCallback, callback) { - if (typeof optsOrCallback === 'function') { - callback = optsOrCallback; /* tslint:disable-line: no-parameter-reassignment */ - optsOrCallback = undefined; /* tslint:disable-line: no-parameter-reassignment */ - } - if (typeof callback === 'undefined') { - throw new TypeError('The "callback" argument must be of type Function.'); - } - statProvider.async(path, optionsManager.prepare(optsOrCallback), callback); -} -exports.statCallback = statCallback; + +utils._equals = function(filepath, unixPath, pattern) { + return pattern === filepath || pattern === unixPath; +}; + /** - * Synchronous API. + * Returns true if the given (original) filepath or unixified path contain + * the given pattern. */ -function statSync(path, opts) { - return statProvider.sync(path, optionsManager.prepare(opts)); -} -exports.statSync = statSync; +utils._contains = function(filepath, unixPath, pattern) { + return filepath.indexOf(pattern) !== -1 || unixPath.indexOf(pattern) !== -1; +}; -/***/ }), -/* 774 */ -/***/ (function(module, exports, __webpack_require__) { +/** + * Returns a function that returns true if the given + * pattern is the same as a given `filepath` + * + * @param {String} `pattern` + * @return {Function} + */ -"use strict"; +utils.equalsPattern = function(pattern, options) { + var unixify = utils.unixify(options); + options = options || {}; -Object.defineProperty(exports, "__esModule", { value: true }); -const fsAdapter = __webpack_require__(775); -function prepare(opts) { - const options = Object.assign({ - fs: fsAdapter.getFileSystemAdapter(opts ? opts.fs : undefined), - throwErrorOnBrokenSymlinks: true, - followSymlinks: true - }, opts); - return options; -} -exports.prepare = prepare; + return function fn(filepath) { + var equal = utils._equals(filepath, unixify(filepath), pattern); + if (equal === true || options.nocase !== true) { + return equal; + } + var lower = filepath.toLowerCase(); + return utils._equals(lower, unixify(lower), pattern); + }; +}; +/** + * Returns a function that returns true if the given + * pattern contains a `filepath` + * + * @param {String} `pattern` + * @return {Function} + */ -/***/ }), -/* 775 */ -/***/ (function(module, exports, __webpack_require__) { +utils.containsPattern = function(pattern, options) { + var unixify = utils.unixify(options); + options = options || {}; -"use strict"; + return function(filepath) { + var contains = utils._contains(filepath, unixify(filepath), pattern); + if (contains === true || options.nocase !== true) { + return contains; + } + var lower = filepath.toLowerCase(); + return utils._contains(lower, unixify(lower), pattern); + }; +}; -Object.defineProperty(exports, "__esModule", { value: true }); -const fs = __webpack_require__(253); -exports.FILE_SYSTEM_ADAPTER = { - lstat: fs.lstat, - stat: fs.stat, - lstatSync: fs.lstatSync, - statSync: fs.statSync +/** + * Returns a function that returns true if the given + * regex matches the `filename` of a file path. + * + * @param {RegExp} `re` Matching regex + * @return {Function} + */ + +utils.matchBasename = function(re) { + return function(filepath) { + return re.test(path.basename(filepath)); + }; }; -function getFileSystemAdapter(fsMethods) { - if (!fsMethods) { - return exports.FILE_SYSTEM_ADAPTER; - } - return Object.assign({}, exports.FILE_SYSTEM_ADAPTER, fsMethods); -} -exports.getFileSystemAdapter = getFileSystemAdapter; +/** + * Determines the filepath to return based on the provided options. + * @return {any} + */ -/***/ }), -/* 776 */ -/***/ (function(module, exports, __webpack_require__) { +utils.value = function(str, unixify, options) { + if (options && options.unixify === false) { + return str; + } + return unixify(str); +}; -"use strict"; +/** + * Returns a function that normalizes slashes in a string to forward + * slashes, strips `./` from beginning of paths, and optionally unescapes + * special characters. + * @return {Function} + */ -Object.defineProperty(exports, "__esModule", { value: true }); -function sync(path, options) { - const lstat = options.fs.lstatSync(path); - if (!isFollowedSymlink(lstat, options)) { - return lstat; +utils.unixify = function(options) { + options = options || {}; + return function(filepath) { + if (utils.isWindows() || options.unixify === true) { + filepath = utils.toPosixPath(filepath); } - try { - const stat = options.fs.statSync(path); - stat.isSymbolicLink = () => true; - return stat; + if (options.stripPrefix !== false) { + filepath = utils.stripPrefix(filepath); } - catch (err) { - if (!options.throwErrorOnBrokenSymlinks) { - return lstat; - } - throw err; + if (options.unescape === true) { + filepath = utils.unescape(filepath); } -} -exports.sync = sync; -function async(path, options, callback) { - options.fs.lstat(path, (err0, lstat) => { - if (err0) { - return callback(err0, undefined); - } - if (!isFollowedSymlink(lstat, options)) { - return callback(null, lstat); - } - options.fs.stat(path, (err1, stat) => { - if (err1) { - return options.throwErrorOnBrokenSymlinks ? callback(err1) : callback(null, lstat); - } - stat.isSymbolicLink = () => true; - callback(null, stat); - }); - }); -} -exports.async = async; -/** - * Returns `true` for followed symlink. - */ -function isFollowedSymlink(stat, options) { - return stat.isSymbolicLink() && options.followSymlinks; -} -exports.isFollowedSymlink = isFollowedSymlink; + return filepath; + }; +}; /***/ }), -/* 777 */ +/* 791 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var path = __webpack_require__(4); -var FileSystem = /** @class */ (function () { - function FileSystem(options) { - this.options = options; - } - /** - * Return full path to entry. - */ - FileSystem.prototype.getFullEntryPath = function (filepath) { - return path.resolve(this.options.cwd, filepath); - }; - /** - * Return an implementation of the Entry interface. - */ - FileSystem.prototype.makeEntry = function (stat, pattern) { - stat.path = pattern; - stat.depth = pattern.split('/').length; - return stat; - }; - return FileSystem; -}()); -exports.default = FileSystem; +/*! + * define-property + * + * Copyright (c) 2015-2018, Jon Schlinkert. + * Released under the MIT License. + */ -/***/ }), -/* 778 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; - -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -var stream = __webpack_require__(294); -var readdir = __webpack_require__(755); -var reader_1 = __webpack_require__(768); -var fs_stream_1 = __webpack_require__(772); -var TransformStream = /** @class */ (function (_super) { - __extends(TransformStream, _super); - function TransformStream(reader) { - var _this = _super.call(this, { objectMode: true }) || this; - _this.reader = reader; - return _this; - } - TransformStream.prototype._transform = function (entry, _encoding, callback) { - callback(null, this.reader.transform(entry)); - }; - return TransformStream; -}(stream.Transform)); -var ReaderStream = /** @class */ (function (_super) { - __extends(ReaderStream, _super); - function ReaderStream() { - return _super !== null && _super.apply(this, arguments) || this; - } - Object.defineProperty(ReaderStream.prototype, "fsAdapter", { - /** - * Returns FileSystem adapter. - */ - get: function () { - return new fs_stream_1.default(this.options); - }, - enumerable: true, - configurable: true - }); - /** - * Use stream API to read entries for Task. - */ - ReaderStream.prototype.read = function (task) { - var _this = this; - var root = this.getRootDirectory(task); - var options = this.getReaderOptions(task); - var transform = new TransformStream(this); - var readable = this.api(root, task, options); - return readable - .on('error', function (err) { return _this.isEnoentCodeError(err) ? null : transform.emit('error', err); }) - .pipe(transform); - }; - /** - * Returns founded paths. - */ - ReaderStream.prototype.api = function (root, task, options) { - if (task.dynamic) { - return this.dynamicApi(root, options); - } - return this.staticApi(task, options); - }; - /** - * Api for dynamic tasks. - */ - ReaderStream.prototype.dynamicApi = function (root, options) { - return readdir.readdirStreamStat(root, options); - }; - /** - * Api for static tasks. - */ - ReaderStream.prototype.staticApi = function (task, options) { - return this.fsAdapter.read(task.patterns, options.filter); - }; - return ReaderStream; -}(reader_1.default)); -exports.default = ReaderStream; +var isobject = __webpack_require__(656); +var isDescriptor = __webpack_require__(657); +var define = (typeof Reflect !== 'undefined' && Reflect.defineProperty) + ? Reflect.defineProperty + : Object.defineProperty; + +module.exports = function defineProperty(obj, key, val) { + if (!isobject(obj) && typeof obj !== 'function' && !Array.isArray(obj)) { + throw new TypeError('expected an object, function, or array'); + } + + if (typeof key !== 'string') { + throw new TypeError('expected "key" to be a string'); + } + + if (isDescriptor(val)) { + define(obj, key, val); + return obj; + } + + define(obj, key, { + configurable: true, + enumerable: false, + writable: true, + value: val + }); + + return obj; +}; /***/ }), -/* 779 */ +/* 792 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -82708,45 +83206,46 @@ var __extends = (this && this.__extends) || (function () { }; })(); Object.defineProperty(exports, "__esModule", { value: true }); -var readdir = __webpack_require__(755); -var reader_1 = __webpack_require__(768); -var fs_sync_1 = __webpack_require__(780); -var ReaderSync = /** @class */ (function (_super) { - __extends(ReaderSync, _super); - function ReaderSync() { +var readdir = __webpack_require__(793); +var reader_1 = __webpack_require__(806); +var fs_stream_1 = __webpack_require__(810); +var ReaderAsync = /** @class */ (function (_super) { + __extends(ReaderAsync, _super); + function ReaderAsync() { return _super !== null && _super.apply(this, arguments) || this; } - Object.defineProperty(ReaderSync.prototype, "fsAdapter", { + Object.defineProperty(ReaderAsync.prototype, "fsAdapter", { /** * Returns FileSystem adapter. */ get: function () { - return new fs_sync_1.default(this.options); + return new fs_stream_1.default(this.options); }, enumerable: true, configurable: true }); /** - * Use sync API to read entries for Task. + * Use async API to read entries for Task. */ - ReaderSync.prototype.read = function (task) { + ReaderAsync.prototype.read = function (task) { + var _this = this; var root = this.getRootDirectory(task); var options = this.getReaderOptions(task); - try { - var entries = this.api(root, task, options); - return entries.map(this.transform, this); - } - catch (err) { - if (this.isEnoentCodeError(err)) { - return []; - } - throw err; - } + var entries = []; + return new Promise(function (resolve, reject) { + var stream = _this.api(root, task, options); + stream.on('error', function (err) { + _this.isEnoentCodeError(err) ? resolve([]) : reject(err); + stream.pause(); + }); + stream.on('data', function (entry) { return entries.push(_this.transform(entry)); }); + stream.on('end', function () { return resolve(entries); }); + }); }; /** * Returns founded paths. */ - ReaderSync.prototype.api = function (root, task, options) { + ReaderAsync.prototype.api = function (root, task, options) { if (task.dynamic) { return this.dynamicApi(root, options); } @@ -82755,5647 +83254,5568 @@ var ReaderSync = /** @class */ (function (_super) { /** * Api for dynamic tasks. */ - ReaderSync.prototype.dynamicApi = function (root, options) { - return readdir.readdirSyncStat(root, options); + ReaderAsync.prototype.dynamicApi = function (root, options) { + return readdir.readdirStreamStat(root, options); }; /** * Api for static tasks. */ - ReaderSync.prototype.staticApi = function (task, options) { + ReaderAsync.prototype.staticApi = function (task, options) { return this.fsAdapter.read(task.patterns, options.filter); }; - return ReaderSync; + return ReaderAsync; }(reader_1.default)); -exports.default = ReaderSync; - - -/***/ }), -/* 780 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -var fsStat = __webpack_require__(773); -var fs_1 = __webpack_require__(777); -var FileSystemSync = /** @class */ (function (_super) { - __extends(FileSystemSync, _super); - function FileSystemSync() { - return _super !== null && _super.apply(this, arguments) || this; - } - /** - * Use sync API to read entries for Task. - */ - FileSystemSync.prototype.read = function (patterns, filter) { - var _this = this; - var entries = []; - patterns.forEach(function (pattern) { - var filepath = _this.getFullEntryPath(pattern); - var entry = _this.getEntry(filepath, pattern); - if (entry === null || !filter(entry)) { - return; - } - entries.push(entry); - }); - return entries; - }; - /** - * Return entry for the provided path. - */ - FileSystemSync.prototype.getEntry = function (filepath, pattern) { - try { - var stat = this.getStat(filepath); - return this.makeEntry(stat, pattern); - } - catch (err) { - return null; - } - }; - /** - * Return fs.Stats for the provided path. - */ - FileSystemSync.prototype.getStat = function (filepath) { - return fsStat.statSync(filepath, { throwErrorOnBrokenSymlinks: false }); - }; - return FileSystemSync; -}(fs_1.default)); -exports.default = FileSystemSync; - - -/***/ }), -/* 781 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Flatten nested arrays (max depth is 2) into a non-nested array of non-array items. - */ -function flatten(items) { - return items.reduce(function (collection, item) { return [].concat(collection, item); }, []); -} -exports.flatten = flatten; - - -/***/ }), -/* 782 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -var merge2 = __webpack_require__(364); -/** - * Merge multiple streams and propagate their errors into one stream in parallel. - */ -function merge(streams) { - var mergedStream = merge2(streams); - streams.forEach(function (stream) { - stream.on('error', function (err) { return mergedStream.emit('error', err); }); - }); - return mergedStream; -} -exports.merge = merge; - - -/***/ }), -/* 783 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -const path = __webpack_require__(4); -const pathType = __webpack_require__(784); - -const getExtensions = extensions => extensions.length > 1 ? `{${extensions.join(',')}}` : extensions[0]; - -const getPath = (filepath, cwd) => { - const pth = filepath[0] === '!' ? filepath.slice(1) : filepath; - return path.isAbsolute(pth) ? pth : path.join(cwd, pth); -}; - -const addExtensions = (file, extensions) => { - if (path.extname(file)) { - return `**/${file}`; - } - - return `**/${file}.${getExtensions(extensions)}`; -}; - -const getGlob = (dir, opts) => { - if (opts.files && !Array.isArray(opts.files)) { - throw new TypeError(`Expected \`files\` to be of type \`Array\` but received type \`${typeof opts.files}\``); - } - - if (opts.extensions && !Array.isArray(opts.extensions)) { - throw new TypeError(`Expected \`extensions\` to be of type \`Array\` but received type \`${typeof opts.extensions}\``); - } - - if (opts.files && opts.extensions) { - return opts.files.map(x => path.join(dir, addExtensions(x, opts.extensions))); - } - - if (opts.files) { - return opts.files.map(x => path.join(dir, `**/${x}`)); - } - - if (opts.extensions) { - return [path.join(dir, `**/*.${getExtensions(opts.extensions)}`)]; - } - - return [path.join(dir, '**')]; -}; - -module.exports = (input, opts) => { - opts = Object.assign({cwd: process.cwd()}, opts); - - if (typeof opts.cwd !== 'string') { - return Promise.reject(new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof opts.cwd}\``)); - } - - return Promise.all([].concat(input).map(x => pathType.dir(getPath(x, opts.cwd)) - .then(isDir => isDir ? getGlob(x, opts) : x))) - .then(globs => [].concat.apply([], globs)); -}; - -module.exports.sync = (input, opts) => { - opts = Object.assign({cwd: process.cwd()}, opts); - - if (typeof opts.cwd !== 'string') { - throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof opts.cwd}\``); - } - - const globs = [].concat(input).map(x => pathType.dirSync(getPath(x, opts.cwd)) ? getGlob(x, opts) : x); - return [].concat.apply([], globs); -}; +exports.default = ReaderAsync; /***/ }), -/* 784 */ +/* 793 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const fs = __webpack_require__(253); -const pify = __webpack_require__(785); -function type(fn, fn2, fp) { - if (typeof fp !== 'string') { - return Promise.reject(new TypeError(`Expected a string, got ${typeof fp}`)); - } +const readdirSync = __webpack_require__(794); +const readdirAsync = __webpack_require__(802); +const readdirStream = __webpack_require__(805); - return pify(fs[fn])(fp) - .then(stats => stats[fn2]()) - .catch(err => { - if (err.code === 'ENOENT') { - return false; - } +module.exports = exports = readdirAsyncPath; +exports.readdir = exports.readdirAsync = exports.async = readdirAsyncPath; +exports.readdirAsyncStat = exports.async.stat = readdirAsyncStat; +exports.readdirStream = exports.stream = readdirStreamPath; +exports.readdirStreamStat = exports.stream.stat = readdirStreamStat; +exports.readdirSync = exports.sync = readdirSyncPath; +exports.readdirSyncStat = exports.sync.stat = readdirSyncStat; - throw err; - }); +/** + * Synchronous readdir that returns an array of string paths. + * + * @param {string} dir + * @param {object} [options] + * @returns {string[]} + */ +function readdirSyncPath (dir, options) { + return readdirSync(dir, options, {}); } -function typeSync(fn, fn2, fp) { - if (typeof fp !== 'string') { - throw new TypeError(`Expected a string, got ${typeof fp}`); - } - - try { - return fs[fn](fp)[fn2](); - } catch (err) { - if (err.code === 'ENOENT') { - return false; - } - - throw err; - } +/** + * Synchronous readdir that returns results as an array of {@link fs.Stats} objects + * + * @param {string} dir + * @param {object} [options] + * @returns {fs.Stats[]} + */ +function readdirSyncStat (dir, options) { + return readdirSync(dir, options, { stats: true }); } -exports.file = type.bind(null, 'stat', 'isFile'); -exports.dir = type.bind(null, 'stat', 'isDirectory'); -exports.symlink = type.bind(null, 'lstat', 'isSymbolicLink'); -exports.fileSync = typeSync.bind(null, 'statSync', 'isFile'); -exports.dirSync = typeSync.bind(null, 'statSync', 'isDirectory'); -exports.symlinkSync = typeSync.bind(null, 'lstatSync', 'isSymbolicLink'); - - -/***/ }), -/* 785 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const processFn = (fn, opts) => function () { - const P = opts.promiseModule; - const args = new Array(arguments.length); - - for (let i = 0; i < arguments.length; i++) { - args[i] = arguments[i]; - } - - return new P((resolve, reject) => { - if (opts.errorFirst) { - args.push(function (err, result) { - if (opts.multiArgs) { - const results = new Array(arguments.length - 1); - - for (let i = 1; i < arguments.length; i++) { - results[i - 1] = arguments[i]; - } - - if (err) { - results.unshift(err); - reject(results); - } else { - resolve(results); - } - } else if (err) { - reject(err); - } else { - resolve(result); - } - }); - } else { - args.push(function (result) { - if (opts.multiArgs) { - const results = new Array(arguments.length - 1); - - for (let i = 0; i < arguments.length; i++) { - results[i] = arguments[i]; - } - - resolve(results); - } else { - resolve(result); - } - }); - } - - fn.apply(this, args); - }); -}; - -module.exports = (obj, opts) => { - opts = Object.assign({ - exclude: [/.+(Sync|Stream)$/], - errorFirst: true, - promiseModule: Promise - }, opts); - - const filter = key => { - const match = pattern => typeof pattern === 'string' ? key === pattern : pattern.test(key); - return opts.include ? opts.include.some(match) : !opts.exclude.some(match); - }; - - let ret; - if (typeof obj === 'function') { - ret = function () { - if (opts.excludeMain) { - return obj.apply(this, arguments); - } +/** + * Aynchronous readdir (accepts an error-first callback or returns a {@link Promise}). + * Results are an array of path strings. + * + * @param {string} dir + * @param {object} [options] + * @param {function} [callback] + * @returns {Promise} + */ +function readdirAsyncPath (dir, options, callback) { + return readdirAsync(dir, options, callback, {}); +} - return processFn(obj, opts).apply(this, arguments); - }; - } else { - ret = Object.create(Object.getPrototypeOf(obj)); - } +/** + * Aynchronous readdir (accepts an error-first callback or returns a {@link Promise}). + * Results are an array of {@link fs.Stats} objects. + * + * @param {string} dir + * @param {object} [options] + * @param {function} [callback] + * @returns {Promise} + */ +function readdirAsyncStat (dir, options, callback) { + return readdirAsync(dir, options, callback, { stats: true }); +} - for (const key in obj) { // eslint-disable-line guard-for-in - const x = obj[key]; - ret[key] = typeof x === 'function' && filter(key) ? processFn(x, opts) : x; - } +/** + * Aynchronous readdir that returns a {@link stream.Readable} (which is also an {@link EventEmitter}). + * All stream data events ("data", "file", "directory", "symlink") are passed a path string. + * + * @param {string} dir + * @param {object} [options] + * @returns {stream.Readable} + */ +function readdirStreamPath (dir, options) { + return readdirStream(dir, options, {}); +} - return ret; -}; +/** + * Aynchronous readdir that returns a {@link stream.Readable} (which is also an {@link EventEmitter}) + * All stream data events ("data", "file", "directory", "symlink") are passed an {@link fs.Stats} object. + * + * @param {string} dir + * @param {object} [options] + * @returns {stream.Readable} + */ +function readdirStreamStat (dir, options) { + return readdirStream(dir, options, { stats: true }); +} /***/ }), -/* 786 */ +/* 794 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; - -const fs = __webpack_require__(253); -const path = __webpack_require__(4); -const fastGlob = __webpack_require__(600); -const gitIgnore = __webpack_require__(787); -const pify = __webpack_require__(526); -const slash = __webpack_require__(788); - -const DEFAULT_IGNORE = [ - '**/node_modules/**', - '**/bower_components/**', - '**/flow-typed/**', - '**/coverage/**', - '**/.git' -]; - -const readFileP = pify(fs.readFile); - -const mapGitIgnorePatternTo = base => ignore => { - if (ignore.startsWith('!')) { - return '!' + path.posix.join(base, ignore.slice(1)); - } - - return path.posix.join(base, ignore); -}; - -const parseGitIgnore = (content, options) => { - const base = slash(path.relative(options.cwd, path.dirname(options.fileName))); - - return content - .split(/\r?\n/) - .filter(Boolean) - .filter(line => line.charAt(0) !== '#') - .map(mapGitIgnorePatternTo(base)); -}; - -const reduceIgnore = files => { - return files.reduce((ignores, file) => { - ignores.add(parseGitIgnore(file.content, { - cwd: file.cwd, - fileName: file.filePath - })); - return ignores; - }, gitIgnore()); -}; - -const getIsIgnoredPredecate = (ignores, cwd) => { - return p => ignores.ignores(slash(path.relative(cwd, p))); -}; - -const getFile = (file, cwd) => { - const filePath = path.join(cwd, file); - return readFileP(filePath, 'utf8') - .then(content => ({ - content, - cwd, - filePath - })); -}; - -const getFileSync = (file, cwd) => { - const filePath = path.join(cwd, file); - const content = fs.readFileSync(filePath, 'utf8'); - - return { - content, - cwd, - filePath - }; -}; - -const normalizeOptions = (options = {}) => { - const ignore = options.ignore || []; - const cwd = options.cwd || process.cwd(); - return {ignore, cwd}; -}; +"use strict"; -module.exports = options => { - options = normalizeOptions(options); - return fastGlob('**/.gitignore', { - ignore: DEFAULT_IGNORE.concat(options.ignore), - cwd: options.cwd - }) - .then(paths => Promise.all(paths.map(file => getFile(file, options.cwd)))) - .then(files => reduceIgnore(files)) - .then(ignores => getIsIgnoredPredecate(ignores, options.cwd)); +module.exports = readdirSync; + +const DirectoryReader = __webpack_require__(795); + +let syncFacade = { + fs: __webpack_require__(800), + forEach: __webpack_require__(801), + sync: true }; -module.exports.sync = options => { - options = normalizeOptions(options); +/** + * Returns the buffered output from a synchronous {@link DirectoryReader}. + * + * @param {string} dir + * @param {object} [options] + * @param {object} internalOptions + */ +function readdirSync (dir, options, internalOptions) { + internalOptions.facade = syncFacade; - const paths = fastGlob.sync('**/.gitignore', { - ignore: DEFAULT_IGNORE.concat(options.ignore), - cwd: options.cwd - }); - const files = paths.map(file => getFileSync(file, options.cwd)); - const ignores = reduceIgnore(files); + let reader = new DirectoryReader(dir, options, internalOptions); + let stream = reader.stream; - return getIsIgnoredPredecate(ignores, options.cwd); -}; + let results = []; + let data = stream.read(); + while (data !== null) { + results.push(data); + data = stream.read(); + } + + return results; +} /***/ }), -/* 787 */ -/***/ (function(module, exports) { +/* 795 */ +/***/ (function(module, exports, __webpack_require__) { -// A simple implementation of make-array -function make_array (subject) { - return Array.isArray(subject) - ? subject - : [subject] -} +"use strict"; -const REGEX_BLANK_LINE = /^\s+$/ -const REGEX_LEADING_EXCAPED_EXCLAMATION = /^\\!/ -const REGEX_LEADING_EXCAPED_HASH = /^\\#/ -const SLASH = '/' -const KEY_IGNORE = typeof Symbol !== 'undefined' - ? Symbol.for('node-ignore') - /* istanbul ignore next */ - : 'node-ignore' -const define = (object, key, value) => - Object.defineProperty(object, key, {value}) +const Readable = __webpack_require__(294).Readable; +const EventEmitter = __webpack_require__(285).EventEmitter; +const path = __webpack_require__(4); +const normalizeOptions = __webpack_require__(796); +const stat = __webpack_require__(798); +const call = __webpack_require__(799); -const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g +/** + * Asynchronously reads the contents of a directory and streams the results + * via a {@link stream.Readable}. + */ +class DirectoryReader { + /** + * @param {string} dir - The absolute or relative directory path to read + * @param {object} [options] - User-specified options, if any (see {@link normalizeOptions}) + * @param {object} internalOptions - Internal options that aren't part of the public API + * @class + */ + constructor (dir, options, internalOptions) { + this.options = options = normalizeOptions(options, internalOptions); -// Sanitize the range of a regular expression -// The cases are complicated, see test cases for details -const sanitizeRange = range => range.replace( - REGEX_REGEXP_RANGE, - (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) - ? match - // Invalid range (out of order) which is ok for gitignore rules but - // fatal for JavaScript regular expression, so eliminate it. - : '' -) + // Indicates whether we should keep reading + // This is set false if stream.Readable.push() returns false. + this.shouldRead = true; -// > If the pattern ends with a slash, -// > it is removed for the purpose of the following description, -// > but it would only find a match with a directory. -// > In other words, foo/ will match a directory foo and paths underneath it, -// > but will not match a regular file or a symbolic link foo -// > (this is consistent with the way how pathspec works in general in Git). -// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`' -// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call -// you could use option `mark: true` with `glob` + // The directories to read + // (initialized with the top-level directory) + this.queue = [{ + path: dir, + basePath: options.basePath, + posixBasePath: options.posixBasePath, + depth: 0 + }]; -// '`foo/`' should not continue with the '`..`' -const DEFAULT_REPLACER_PREFIX = [ + // The number of directories that are currently being processed + this.pending = 0; - // > Trailing spaces are ignored unless they are quoted with backslash ("\") - [ - // (a\ ) -> (a ) - // (a ) -> (a) - // (a \ ) -> (a ) - /\\?\s+$/, - match => match.indexOf('\\') === 0 - ? ' ' - : '' - ], + // The data that has been read, but not yet emitted + this.buffer = []; - // replace (\ ) with ' ' - [ - /\\\s/g, - () => ' ' - ], + this.stream = new Readable({ objectMode: true }); + this.stream._read = () => { + // Start (or resume) reading + this.shouldRead = true; - // Escape metacharacters - // which is written down by users but means special for regular expressions. + // If we have data in the buffer, then send the next chunk + if (this.buffer.length > 0) { + this.pushFromBuffer(); + } - // > There are 12 characters with special meanings: - // > - the backslash \, - // > - the caret ^, - // > - the dollar sign $, - // > - the period or dot ., - // > - the vertical bar or pipe symbol |, - // > - the question mark ?, - // > - the asterisk or star *, - // > - the plus sign +, - // > - the opening parenthesis (, - // > - the closing parenthesis ), - // > - and the opening square bracket [, - // > - the opening curly brace {, - // > These special characters are often called "metacharacters". - [ - /[\\^$.|*+(){]/g, - match => `\\${match}` - ], + // If we have directories queued, then start processing the next one + if (this.queue.length > 0) { + if (this.options.facade.sync) { + while (this.queue.length > 0) { + this.readNextDirectory(); + } + } + else { + this.readNextDirectory(); + } + } - [ - // > [abc] matches any character inside the brackets - // > (in this case a, b, or c); - /\[([^\]/]*)($|\])/g, - (match, p1, p2) => p2 === ']' - ? `[${sanitizeRange(p1)}]` - : `\\${match}` - ], + this.checkForEOF(); + }; + } - [ - // > a question mark (?) matches a single character - /(?!\\)\?/g, - () => '[^/]' - ], + /** + * Reads the next directory in the queue + */ + readNextDirectory () { + let facade = this.options.facade; + let dir = this.queue.shift(); + this.pending++; - // leading slash - [ + // Read the directory listing + call.safe(facade.fs.readdir, dir.path, (err, items) => { + if (err) { + // fs.readdir threw an error + this.emit('error', err); + return this.finishedReadingDirectory(); + } - // > A leading slash matches the beginning of the pathname. - // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c". - // A leading slash matches the beginning of the pathname - /^\//, - () => '^' - ], + try { + // Process each item in the directory (simultaneously, if async) + facade.forEach( + items, + this.processItem.bind(this, dir), + this.finishedReadingDirectory.bind(this, dir) + ); + } + catch (err2) { + // facade.forEach threw an error + // (probably because fs.readdir returned an invalid result) + this.emit('error', err2); + this.finishedReadingDirectory(); + } + }); + } - // replace special metacharacter slash after the leading slash - [ - /\//g, - () => '\\/' - ], + /** + * This method is called after all items in a directory have been processed. + * + * NOTE: This does not necessarily mean that the reader is finished, since there may still + * be other directories queued or pending. + */ + finishedReadingDirectory () { + this.pending--; - [ - // > A leading "**" followed by a slash means match in all directories. - // > For example, "**/foo" matches file or directory "foo" anywhere, - // > the same as pattern "foo". - // > "**/foo/bar" matches file or directory "bar" anywhere that is directly - // > under directory "foo". - // Notice that the '*'s have been replaced as '\\*' - /^\^*\\\*\\\*\\\//, + if (this.shouldRead) { + // If we have directories queued, then start processing the next one + if (this.queue.length > 0 && this.options.facade.async) { + this.readNextDirectory(); + } - // '**/foo' <-> 'foo' - () => '^(?:.*\\/)?' - ] -] + this.checkForEOF(); + } + } -const DEFAULT_REPLACER_SUFFIX = [ - // starting - [ - // there will be no leading '/' - // (which has been replaced by section "leading slash") - // If starts with '**', adding a '^' to the regular expression also works - /^(?=[^^])/, - function startingReplacer () { - return !/\/(?!$)/.test(this) - // > If the pattern does not contain a slash /, - // > Git treats it as a shell glob pattern - // Actually, if there is only a trailing slash, - // git also treats it as a shell glob pattern - ? '(?:^|\\/)' + /** + * Determines whether the reader has finished processing all items in all directories. + * If so, then the "end" event is fired (via {@Readable#push}) + */ + checkForEOF () { + if (this.buffer.length === 0 && // The stuff we've already read + this.pending === 0 && // The stuff we're currently reading + this.queue.length === 0) { // The stuff we haven't read yet + // There's no more stuff! + this.stream.push(null); + } + } - // > Otherwise, Git treats the pattern as a shell glob suitable for - // > consumption by fnmatch(3) - : '^' + /** + * Processes a single item in a directory. + * + * If the item is a directory, and `option.deep` is enabled, then the item will be added + * to the directory queue. + * + * If the item meets the filter criteria, then it will be emitted to the reader's stream. + * + * @param {object} dir - A directory object from the queue + * @param {string} item - The name of the item (name only, no path) + * @param {function} done - A callback function that is called after the item has been processed + */ + processItem (dir, item, done) { + let stream = this.stream; + let options = this.options; + + let itemPath = dir.basePath + item; + let posixPath = dir.posixBasePath + item; + let fullPath = path.join(dir.path, item); + + // If `options.deep` is a number, and we've already recursed to the max depth, + // then there's no need to check fs.Stats to know if it's a directory. + // If `options.deep` is a function, then we'll need fs.Stats + let maxDepthReached = dir.depth >= options.recurseDepth; + + // Do we need to call `fs.stat`? + let needStats = + !maxDepthReached || // we need the fs.Stats to know if it's a directory + options.stats || // the user wants fs.Stats objects returned + options.recurseFn || // we need fs.Stats for the recurse function + options.filterFn || // we need fs.Stats for the filter function + EventEmitter.listenerCount(stream, 'file') || // we need the fs.Stats to know if it's a file + EventEmitter.listenerCount(stream, 'directory') || // we need the fs.Stats to know if it's a directory + EventEmitter.listenerCount(stream, 'symlink'); // we need the fs.Stats to know if it's a symlink + + // If we don't need stats, then exit early + if (!needStats) { + if (this.filter(itemPath, posixPath)) { + this.pushOrBuffer({ data: itemPath }); + } + return done(); } - ], - // two globstars - [ - // Use lookahead assertions so that we could match more than one `'/**'` - /\\\/\\\*\\\*(?=\\\/|$)/g, + // Get the fs.Stats object for this path + stat(options.facade.fs, fullPath, (err, stats) => { + if (err) { + // fs.stat threw an error + this.emit('error', err); + return done(); + } - // Zero, one or several directories - // should not use '*', or it will be replaced by the next replacer + try { + // Add the item's path to the fs.Stats object + // The base of this path, and its separators are determined by the options + // (i.e. options.basePath and options.sep) + stats.path = itemPath; - // Check if it is not the last `'/**'` - (match, index, str) => index + 6 < str.length + // Add depth of the path to the fs.Stats object for use this in the filter function + stats.depth = dir.depth; - // case: /**/ - // > A slash followed by two consecutive asterisks then a slash matches - // > zero or more directories. - // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on. - // '/**/' - ? '(?:\\/[^\\/]+)*' + if (this.shouldRecurse(stats, posixPath, maxDepthReached)) { + // Add this subdirectory to the queue + this.queue.push({ + path: fullPath, + basePath: itemPath + options.sep, + posixBasePath: posixPath + '/', + depth: dir.depth + 1, + }); + } - // case: /** - // > A trailing `"/**"` matches everything inside. + // Determine whether this item matches the filter criteria + if (this.filter(stats, posixPath)) { + this.pushOrBuffer({ + data: options.stats ? stats : itemPath, + file: stats.isFile(), + directory: stats.isDirectory(), + symlink: stats.isSymbolicLink(), + }); + } - // #21: everything inside but it should not include the current folder - : '\\/.+' - ], + done(); + } + catch (err2) { + // An error occurred while processing the item + // (probably during a user-specified function, such as options.deep, options.filter, etc.) + this.emit('error', err2); + done(); + } + }); + } - // intermediate wildcards - [ - // Never replace escaped '*' - // ignore rule '\*' will match the path '*' + /** + * Pushes the given chunk of data to the stream, or adds it to the buffer, + * depending on the state of the stream. + * + * @param {object} chunk + */ + pushOrBuffer (chunk) { + // Add the chunk to the buffer + this.buffer.push(chunk); - // 'abc.*/' -> go - // 'abc.*' -> skip this rule - /(^|[^\\]+)\\\*(?=.+)/g, + // If we're still reading, then immediately emit the next chunk in the buffer + // (which may or may not be the chunk that we just added) + if (this.shouldRead) { + this.pushFromBuffer(); + } + } - // '*.js' matches '.js' - // '*.js' doesn't match 'abc' - (match, p1) => `${p1}[^\\/]*` - ], + /** + * Immediately pushes the next chunk in the buffer to the reader's stream. + * The "data" event will always be fired (via {@link Readable#push}). + * In addition, the "file", "directory", and/or "symlink" events may be fired, + * depending on the type of properties of the chunk. + */ + pushFromBuffer () { + let stream = this.stream; + let chunk = this.buffer.shift(); - // trailing wildcard - [ - /(\^|\\\/)?\\\*$/, - (match, p1) => { - const prefix = p1 - // '\^': - // '/*' does not match '' - // '/*' does not match everything + // Stream the data + try { + this.shouldRead = stream.push(chunk.data); + } + catch (err) { + this.emit('error', err); + } - // '\\\/': - // 'abc/*' does not match 'abc/' - ? `${p1}[^/]+` + // Also emit specific events, based on the type of chunk + chunk.file && this.emit('file', chunk.data); + chunk.symlink && this.emit('symlink', chunk.data); + chunk.directory && this.emit('directory', chunk.data); + } - // 'a*' matches 'a' - // 'a*' matches 'aa' - : '[^/]*' + /** + * Determines whether the given directory meets the user-specified recursion criteria. + * If the user didn't specify recursion criteria, then this function will default to true. + * + * @param {fs.Stats} stats - The directory's {@link fs.Stats} object + * @param {string} posixPath - The item's POSIX path (used for glob matching) + * @param {boolean} maxDepthReached - Whether we've already crawled the user-specified depth + * @returns {boolean} + */ + shouldRecurse (stats, posixPath, maxDepthReached) { + let options = this.options; + + if (maxDepthReached) { + // We've already crawled to the maximum depth. So no more recursion. + return false; + } + else if (!stats.isDirectory()) { + // It's not a directory. So don't try to crawl it. + return false; + } + else if (options.recurseGlob) { + // Glob patterns are always tested against the POSIX path, even on Windows + // https://github.com/isaacs/node-glob#windows + return options.recurseGlob.test(posixPath); + } + else if (options.recurseRegExp) { + // Regular expressions are tested against the normal path + // (based on the OS or options.sep) + return options.recurseRegExp.test(stats.path); + } + else if (options.recurseFn) { + try { + // Run the user-specified recursion criteria + return options.recurseFn.call(null, stats); + } + catch (err) { + // An error occurred in the user's code. + // In Sync and Async modes, this will return an error. + // In Streaming mode, we emit an "error" event, but continue processing + this.emit('error', err); + } + } + else { + // No recursion function was specified, and we're within the maximum depth. + // So crawl this directory. + return true; + } + } + + /** + * Determines whether the given item meets the user-specified filter criteria. + * If the user didn't specify a filter, then this function will always return true. + * + * @param {string|fs.Stats} value - Either the item's path, or the item's {@link fs.Stats} object + * @param {string} posixPath - The item's POSIX path (used for glob matching) + * @returns {boolean} + */ + filter (value, posixPath) { + let options = this.options; - return `${prefix}(?=$|\\/$)` + if (options.filterGlob) { + // Glob patterns are always tested against the POSIX path, even on Windows + // https://github.com/isaacs/node-glob#windows + return options.filterGlob.test(posixPath); } - ], + else if (options.filterRegExp) { + // Regular expressions are tested against the normal path + // (based on the OS or options.sep) + return options.filterRegExp.test(value.path || value); + } + else if (options.filterFn) { + try { + // Run the user-specified filter function + return options.filterFn.call(null, value); + } + catch (err) { + // An error occurred in the user's code. + // In Sync and Async modes, this will return an error. + // In Streaming mode, we emit an "error" event, but continue processing + this.emit('error', err); + } + } + else { + // No filter was specified, so match everything + return true; + } + } - [ - // unescape - /\\\\\\/g, - () => '\\' - ] -] + /** + * Emits an event. If one of the event listeners throws an error, + * then an "error" event is emitted. + * + * @param {string} eventName + * @param {*} data + */ + emit (eventName, data) { + let stream = this.stream; -const POSITIVE_REPLACERS = [ - ...DEFAULT_REPLACER_PREFIX, + try { + stream.emit(eventName, data); + } + catch (err) { + if (eventName === 'error') { + // Don't recursively emit "error" events. + // If the first one fails, then just throw + throw err; + } + else { + stream.emit('error', err); + } + } + } +} - // 'f' - // matches - // - /f(end) - // - /f/ - // - (start)f(end) - // - (start)f/ - // doesn't match - // - oof - // - foo - // pseudo: - // -> (^|/)f(/|$) +module.exports = DirectoryReader; - // ending - [ - // 'js' will not match 'js.' - // 'ab' will not match 'abc' - /(?:[^*/])$/, - // 'js*' will not match 'a.js' - // 'js/' will not match 'a.js' - // 'js' will match 'a.js' and 'a.js/' - match => `${match}(?=$|\\/)` - ], +/***/ }), +/* 796 */ +/***/ (function(module, exports, __webpack_require__) { - ...DEFAULT_REPLACER_SUFFIX -] +"use strict"; -const NEGATIVE_REPLACERS = [ - ...DEFAULT_REPLACER_PREFIX, - // #24, #38 - // The MISSING rule of [gitignore docs](https://git-scm.com/docs/gitignore) - // A negative pattern without a trailing wildcard should not - // re-include the things inside that directory. +const path = __webpack_require__(4); +const globToRegExp = __webpack_require__(797); - // eg: - // ['node_modules/*', '!node_modules'] - // should ignore `node_modules/a.js` - [ - /(?:[^*])$/, - match => `${match}(?=$|\\/$)` - ], +module.exports = normalizeOptions; - ...DEFAULT_REPLACER_SUFFIX -] +let isWindows = /^win/.test(process.platform); -// A simple cache, because an ignore rule only has only one certain meaning -const cache = Object.create(null) +/** + * @typedef {Object} FSFacade + * @property {fs.readdir} readdir + * @property {fs.stat} stat + * @property {fs.lstat} lstat + */ -// @param {pattern} -const make_regex = (pattern, negative, ignorecase) => { - const r = cache[pattern] - if (r) { - return r +/** + * Validates and normalizes the options argument + * + * @param {object} [options] - User-specified options, if any + * @param {object} internalOptions - Internal options that aren't part of the public API + * + * @param {number|boolean|function} [options.deep] + * The number of directories to recursively traverse. Any falsy value or negative number will + * default to zero, so only the top-level contents will be returned. Set to `true` or `Infinity` + * to traverse all subdirectories. Or provide a function that accepts a {@link fs.Stats} object + * and returns a truthy value if the directory's contents should be crawled. + * + * @param {function|string|RegExp} [options.filter] + * A function that accepts a {@link fs.Stats} object and returns a truthy value if the data should + * be returned. Or a RegExp or glob string pattern, to filter by file name. + * + * @param {string} [options.sep] + * The path separator to use. By default, the OS-specific separator will be used, but this can be + * set to a specific value to ensure consistency across platforms. + * + * @param {string} [options.basePath] + * The base path to prepend to each result. If empty, then all results will be relative to `dir`. + * + * @param {FSFacade} [options.fs] + * Synchronous or asynchronous facades for Node.js File System module + * + * @param {object} [internalOptions.facade] + * Synchronous or asynchronous facades for various methods, including for the Node.js File System module + * + * @param {boolean} [internalOptions.emit] + * Indicates whether the reader should emit "file", "directory", and "symlink" events + * + * @param {boolean} [internalOptions.stats] + * Indicates whether the reader should emit {@link fs.Stats} objects instead of path strings + * + * @returns {object} + */ +function normalizeOptions (options, internalOptions) { + if (options === null || options === undefined) { + options = {}; + } + else if (typeof options !== 'object') { + throw new TypeError('options must be an object'); } - const replacers = negative - ? NEGATIVE_REPLACERS - : POSITIVE_REPLACERS - - const source = replacers.reduce( - (prev, current) => prev.replace(current[0], current[1].bind(pattern)), - pattern - ) - - return cache[pattern] = ignorecase - ? new RegExp(source, 'i') - : new RegExp(source) -} - -// > A blank line matches no files, so it can serve as a separator for readability. -const checkPattern = pattern => pattern - && typeof pattern === 'string' - && !REGEX_BLANK_LINE.test(pattern) - - // > A line starting with # serves as a comment. - && pattern.indexOf('#') !== 0 + let recurseDepth, recurseFn, recurseRegExp, recurseGlob, deep = options.deep; + if (deep === null || deep === undefined) { + recurseDepth = 0; + } + else if (typeof deep === 'boolean') { + recurseDepth = deep ? Infinity : 0; + } + else if (typeof deep === 'number') { + if (deep < 0 || isNaN(deep)) { + throw new Error('options.deep must be a positive number'); + } + else if (Math.floor(deep) !== deep) { + throw new Error('options.deep must be an integer'); + } + else { + recurseDepth = deep; + } + } + else if (typeof deep === 'function') { + recurseDepth = Infinity; + recurseFn = deep; + } + else if (deep instanceof RegExp) { + recurseDepth = Infinity; + recurseRegExp = deep; + } + else if (typeof deep === 'string' && deep.length > 0) { + recurseDepth = Infinity; + recurseGlob = globToRegExp(deep, { extended: true, globstar: true }); + } + else { + throw new TypeError('options.deep must be a boolean, number, function, regular expression, or glob pattern'); + } -const createRule = (pattern, ignorecase) => { - const origin = pattern - let negative = false + let filterFn, filterRegExp, filterGlob, filter = options.filter; + if (filter !== null && filter !== undefined) { + if (typeof filter === 'function') { + filterFn = filter; + } + else if (filter instanceof RegExp) { + filterRegExp = filter; + } + else if (typeof filter === 'string' && filter.length > 0) { + filterGlob = globToRegExp(filter, { extended: true, globstar: true }); + } + else { + throw new TypeError('options.filter must be a function, regular expression, or glob pattern'); + } + } - // > An optional prefix "!" which negates the pattern; - if (pattern.indexOf('!') === 0) { - negative = true - pattern = pattern.substr(1) + let sep = options.sep; + if (sep === null || sep === undefined) { + sep = path.sep; + } + else if (typeof sep !== 'string') { + throw new TypeError('options.sep must be a string'); } - pattern = pattern - // > Put a backslash ("\") in front of the first "!" for patterns that - // > begin with a literal "!", for example, `"\!important!.txt"`. - .replace(REGEX_LEADING_EXCAPED_EXCLAMATION, '!') - // > Put a backslash ("\") in front of the first hash for patterns that - // > begin with a hash. - .replace(REGEX_LEADING_EXCAPED_HASH, '#') + let basePath = options.basePath; + if (basePath === null || basePath === undefined) { + basePath = ''; + } + else if (typeof basePath === 'string') { + // Append a path separator to the basePath, if necessary + if (basePath && basePath.substr(-1) !== sep) { + basePath += sep; + } + } + else { + throw new TypeError('options.basePath must be a string'); + } - const regex = make_regex(pattern, negative, ignorecase) + // Convert the basePath to POSIX (forward slashes) + // so that glob pattern matching works consistently, even on Windows + let posixBasePath = basePath; + if (posixBasePath && sep !== '/') { + posixBasePath = posixBasePath.replace(new RegExp('\\' + sep, 'g'), '/'); - return { - origin, - pattern, - negative, - regex + /* istanbul ignore if */ + if (isWindows) { + // Convert Windows root paths (C:\) and UNCs (\\) to POSIX root paths + posixBasePath = posixBasePath.replace(/^([a-zA-Z]\:\/|\/\/)/, '/'); + } } -} -class IgnoreBase { - constructor ({ - ignorecase = true - } = {}) { - this._rules = [] - this._ignorecase = ignorecase - define(this, KEY_IGNORE, true) - this._initCache() + // Determine which facade methods to use + let facade; + if (options.fs === null || options.fs === undefined) { + // The user didn't provide their own facades, so use our internal ones + facade = internalOptions.facade; } - - _initCache () { - this._cache = Object.create(null) + else if (typeof options.fs === 'object') { + // Merge the internal facade methods with the user-provided `fs` facades + facade = Object.assign({}, internalOptions.facade); + facade.fs = Object.assign({}, internalOptions.facade.fs, options.fs); + } + else { + throw new TypeError('options.fs must be an object'); } - // @param {Array.|string|Ignore} pattern - add (pattern) { - this._added = false - - if (typeof pattern === 'string') { - pattern = pattern.split(/\r?\n/g) - } + return { + recurseDepth, + recurseFn, + recurseRegExp, + recurseGlob, + filterFn, + filterRegExp, + filterGlob, + sep, + basePath, + posixBasePath, + facade, + emit: !!internalOptions.emit, + stats: !!internalOptions.stats, + }; +} - make_array(pattern).forEach(this._addPattern, this) - // Some rules have just added to the ignore, - // making the behavior changed. - if (this._added) { - this._initCache() - } +/***/ }), +/* 797 */ +/***/ (function(module, exports) { - return this +module.exports = function (glob, opts) { + if (typeof glob !== 'string') { + throw new TypeError('Expected a string'); } - // legacy - addPattern (pattern) { - return this.add(pattern) - } + var str = String(glob); - _addPattern (pattern) { - // #32 - if (pattern && pattern[KEY_IGNORE]) { - this._rules = this._rules.concat(pattern._rules) - this._added = true - return - } + // The regexp we are building, as a string. + var reStr = ""; - if (checkPattern(pattern)) { - const rule = createRule(pattern, this._ignorecase) - this._added = true - this._rules.push(rule) - } - } + // Whether we are matching so called "extended" globs (like bash) and should + // support single character matching, matching ranges of characters, group + // matching, etc. + var extended = opts ? !!opts.extended : false; - filter (paths) { - return make_array(paths).filter(path => this._filter(path)) - } + // When globstar is _false_ (default), '/foo/*' is translated a regexp like + // '^\/foo\/.*$' which will match any string beginning with '/foo/' + // When globstar is _true_, '/foo/*' is translated to regexp like + // '^\/foo\/[^/]*$' which will match any string beginning with '/foo/' BUT + // which does not have a '/' to the right of it. + // E.g. with '/foo/*' these will match: '/foo/bar', '/foo/bar.txt' but + // these will not '/foo/bar/baz', '/foo/bar/baz.txt' + // Lastely, when globstar is _true_, '/foo/**' is equivelant to '/foo/*' when + // globstar is _false_ + var globstar = opts ? !!opts.globstar : false; - createFilter () { - return path => this._filter(path) - } + // If we are doing extended matching, this boolean is true when we are inside + // a group (eg {*.html,*.js}), and false otherwise. + var inGroup = false; - ignores (path) { - return !this._filter(path) - } + // RegExp flags (eg "i" ) to pass in to RegExp constructor. + var flags = opts && typeof( opts.flags ) === "string" ? opts.flags : ""; - // @returns `Boolean` true if the `path` is NOT ignored - _filter (path, slices) { - if (!path) { - return false - } + var c; + for (var i = 0, len = str.length; i < len; i++) { + c = str[i]; - if (path in this._cache) { - return this._cache[path] - } + switch (c) { + case "\\": + case "/": + case "$": + case "^": + case "+": + case ".": + case "(": + case ")": + case "=": + case "!": + case "|": + reStr += "\\" + c; + break; - if (!slices) { - // path/to/a.js - // ['path', 'to', 'a.js'] - slices = path.split(SLASH) - } + case "?": + if (extended) { + reStr += "."; + break; + } - slices.pop() + case "[": + case "]": + if (extended) { + reStr += c; + break; + } - return this._cache[path] = slices.length - // > It is not possible to re-include a file if a parent directory of - // > that file is excluded. - // If the path contains a parent directory, check the parent first - ? this._filter(slices.join(SLASH) + SLASH, slices) - && this._test(path) + case "{": + if (extended) { + inGroup = true; + reStr += "("; + break; + } - // Or only test the path - : this._test(path) - } + case "}": + if (extended) { + inGroup = false; + reStr += ")"; + break; + } - // @returns {Boolean} true if a file is NOT ignored - _test (path) { - // Explicitly define variable type by setting matched to `0` - let matched = 0 + case ",": + if (inGroup) { + reStr += "|"; + break; + } + reStr += "\\" + c; + break; - this._rules.forEach(rule => { - // if matched = true, then we only test negative rules - // if matched = false, then we test non-negative rules - if (!(matched ^ rule.negative)) { - matched = rule.negative ^ rule.regex.test(path) + case "*": + // Move over all consecutive "*"'s. + // Also store the previous and next characters + var prevChar = str[i - 1]; + var starCount = 1; + while(str[i + 1] === "*") { + starCount++; + i++; } - }) + var nextChar = str[i + 1]; - return !matched - } -} + if (!globstar) { + // globstar is disabled, so treat any number of "*" as one + reStr += ".*"; + } else { + // globstar is enabled, so determine if this is a globstar segment + var isGlobstar = starCount > 1 // multiple "*"'s + && (prevChar === "/" || prevChar === undefined) // from the start of the segment + && (nextChar === "/" || nextChar === undefined) // to the end of the segment -// Windows -// -------------------------------------------------------------- -/* istanbul ignore if */ -if ( - // Detect `process` so that it can run in browsers. - typeof process !== 'undefined' - && ( - process.env && process.env.IGNORE_TEST_WIN32 - || process.platform === 'win32' - ) -) { - const filter = IgnoreBase.prototype._filter + if (isGlobstar) { + // it's a globstar, so match zero or more path segments + reStr += "(?:[^/]*(?:\/|$))*"; + i++; // move over the "/" + } else { + // it's not a globstar, so only match one path segment + reStr += "[^/]*"; + } + } + break; - /* eslint no-control-regex: "off" */ - const make_posix = str => /^\\\\\?\\/.test(str) - || /[^\x00-\x80]+/.test(str) - ? str - : str.replace(/\\/g, '/') + default: + reStr += c; + } + } - IgnoreBase.prototype._filter = function filterWin32 (path, slices) { - path = make_posix(path) - return filter.call(this, path, slices) + // When regexp 'g' flag is specified don't + // constrain the regular expression with ^ & $ + if (!flags || !~flags.indexOf('g')) { + reStr = "^" + reStr + "$"; } -} -module.exports = options => new IgnoreBase(options) + return new RegExp(reStr, flags); +}; /***/ }), -/* 788 */ +/* 798 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -module.exports = input => { - const isExtendedLengthPath = /^\\\\\?\\/.test(input); - const hasNonAscii = /[^\u0000-\u0080]+/.test(input); // eslint-disable-line no-control-regex - - if (isExtendedLengthPath || hasNonAscii) { - return input; - } - - return input.replace(/\\/g, '/'); -}; +const call = __webpack_require__(799); -/***/ }), -/* 789 */ -/***/ (function(module, exports, __webpack_require__) { +module.exports = stat; -"use strict"; -/*! - * has-glob +/** + * Retrieves the {@link fs.Stats} for the given path. If the path is a symbolic link, + * then the Stats of the symlink's target are returned instead. If the symlink is broken, + * then the Stats of the symlink itself are returned. * - * Copyright (c) 2015, Jon Schlinkert. - * Licensed under the MIT License. + * @param {object} fs - Synchronous or Asynchronouse facade for the "fs" module + * @param {string} path - The path to return stats for + * @param {function} callback */ +function stat (fs, path, callback) { + let isSymLink = false; - - -var isGlob = __webpack_require__(790); - -module.exports = function hasGlob(val) { - if (val == null) return false; - if (typeof val === 'string') { - return isGlob(val); - } - if (Array.isArray(val)) { - var len = val.length; - while (len--) { - if (isGlob(val[len])) { - return true; - } + call.safe(fs.lstat, path, (err, lstats) => { + if (err) { + // fs.lstat threw an eror + return callback(err); } - } - return false; -}; + try { + isSymLink = lstats.isSymbolicLink(); + } + catch (err2) { + // lstats.isSymbolicLink() threw an error + // (probably because fs.lstat returned an invalid result) + return callback(err2); + } -/***/ }), -/* 790 */ -/***/ (function(module, exports, __webpack_require__) { + if (isSymLink) { + // Try to resolve the symlink + symlinkStat(fs, path, lstats, callback); + } + else { + // It's not a symlink, so return the stats as-is + callback(null, lstats); + } + }); +} -/*! - * is-glob +/** + * Retrieves the {@link fs.Stats} for the target of the given symlink. + * If the symlink is broken, then the Stats of the symlink itself are returned. * - * Copyright (c) 2014-2016, Jon Schlinkert. - * Licensed under the MIT License. + * @param {object} fs - Synchronous or Asynchronouse facade for the "fs" module + * @param {string} path - The path of the symlink to return stats for + * @param {object} lstats - The stats of the symlink + * @param {function} callback */ +function symlinkStat (fs, path, lstats, callback) { + call.safe(fs.stat, path, (err, stats) => { + if (err) { + // The symlink is broken, so return the stats for the link itself + return callback(null, lstats); + } -var isExtglob = __webpack_require__(388); - -module.exports = function isGlob(str) { - if (typeof str !== 'string' || str === '') { - return false; - } - - if (isExtglob(str)) return true; - - var regex = /(\\).|([*?]|\[.*\]|\{.*\}|\(.*\|.*\)|^!)/; - var match; + try { + // Return the stats for the resolved symlink target, + // and override the `isSymbolicLink` method to indicate that it's a symlink + stats.isSymbolicLink = () => true; + } + catch (err2) { + // Setting stats.isSymbolicLink threw an error + // (probably because fs.stat returned an invalid result) + return callback(err2); + } - while ((match = regex.exec(str))) { - if (match[2]) return true; - str = str.slice(match.index + match[0].length); - } - return false; -}; + callback(null, stats); + }); +} /***/ }), -/* 791 */ +/* 799 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const path = __webpack_require__(4); -const {constants: fsConstants} = __webpack_require__(253); -const pEvent = __webpack_require__(792); -const CpFileError = __webpack_require__(795); -const fs = __webpack_require__(797); -const ProgressEmitter = __webpack_require__(800); -const cpFileAsync = async (source, destination, options, progressEmitter) => { - let readError; - const stat = await fs.stat(source); - progressEmitter.size = stat.size; +let call = module.exports = { + safe: safeCall, + once: callOnce, +}; - const read = await fs.createReadStream(source); - await fs.makeDir(path.dirname(destination)); - const write = fs.createWriteStream(destination, {flags: options.overwrite ? 'w' : 'wx'}); - read.on('data', () => { - progressEmitter.written = write.bytesWritten; - }); - read.once('error', error => { - readError = new CpFileError(`Cannot read from \`${source}\`: ${error.message}`, error); - write.end(); - }); +/** + * Calls a function with the given arguments, and ensures that the error-first callback is _always_ + * invoked exactly once, even if the function throws an error. + * + * @param {function} fn - The function to invoke + * @param {...*} args - The arguments to pass to the function. The final argument must be a callback function. + */ +function safeCall (fn, args) { + // Get the function arguments as an array + args = Array.prototype.slice.call(arguments, 1); - let updateStats = false; - try { - const writePromise = pEvent(write, 'close'); - read.pipe(write); - await writePromise; - progressEmitter.written = progressEmitter.size; - updateStats = true; - } catch (error) { - if (options.overwrite || error.code !== 'EEXIST') { - throw new CpFileError(`Cannot write to \`${destination}\`: ${error.message}`, error); - } - } + // Replace the callback function with a wrapper that ensures it will only be called once + let callback = call.once(args.pop()); + args.push(callback); - if (readError) { - throw readError; - } + try { + fn.apply(null, args); + } + catch (err) { + callback(err); + } +} - if (updateStats) { - const stats = await fs.lstat(source); +/** + * Returns a wrapper function that ensures the given callback function is only called once. + * Subsequent calls are ignored, unless the first argument is an Error, in which case the + * error is thrown. + * + * @param {function} fn - The function that should only be called once + * @returns {function} + */ +function callOnce (fn) { + let fulfilled = false; - return Promise.all([ - fs.utimes(destination, stats.atime, stats.mtime), - fs.chmod(destination, stats.mode), - fs.chown(destination, stats.uid, stats.gid) - ]); - } -}; + return function onceWrapper (err) { + if (!fulfilled) { + fulfilled = true; + return fn.apply(this, arguments); + } + else if (err) { + // The callback has already been called, but now an error has occurred + // (most likely inside the callback function). So re-throw the error, + // so it gets handled further up the call stack + throw err; + } + }; +} -const cpFile = (source, destination, options) => { - if (!source || !destination) { - return Promise.reject(new CpFileError('`source` and `destination` required')); - } - options = { - overwrite: true, - ...options - }; +/***/ }), +/* 800 */ +/***/ (function(module, exports, __webpack_require__) { - const progressEmitter = new ProgressEmitter(path.resolve(source), path.resolve(destination)); - const promise = cpFileAsync(source, destination, options, progressEmitter); - promise.on = (...args) => { - progressEmitter.on(...args); - return promise; - }; +"use strict"; - return promise; -}; -module.exports = cpFile; +const fs = __webpack_require__(253); +const call = __webpack_require__(799); -const checkSourceIsFile = (stat, source) => { - if (stat.isDirectory()) { - throw Object.assign(new CpFileError(`EISDIR: illegal operation on a directory '${source}'`), { - errno: -21, - code: 'EISDIR', - source - }); - } -}; +/** + * A facade around {@link fs.readdirSync} that allows it to be called + * the same way as {@link fs.readdir}. + * + * @param {string} dir + * @param {function} callback + */ +exports.readdir = function (dir, callback) { + // Make sure the callback is only called once + callback = call.once(callback); -const fixupAttributes = (destination, stat) => { - fs.chmodSync(destination, stat.mode); - fs.chownSync(destination, stat.uid, stat.gid); + try { + let items = fs.readdirSync(dir); + callback(null, items); + } + catch (err) { + callback(err); + } }; -module.exports.sync = (source, destination, options) => { - if (!source || !destination) { - throw new CpFileError('`source` and `destination` required'); - } - - options = { - overwrite: true, - ...options - }; - - const stat = fs.statSync(source); - checkSourceIsFile(stat, source); - fs.makeDirSync(path.dirname(destination)); +/** + * A facade around {@link fs.statSync} that allows it to be called + * the same way as {@link fs.stat}. + * + * @param {string} path + * @param {function} callback + */ +exports.stat = function (path, callback) { + // Make sure the callback is only called once + callback = call.once(callback); - const flags = options.overwrite ? null : fsConstants.COPYFILE_EXCL; - try { - fs.copyFileSync(source, destination, flags); - } catch (error) { - if (!options.overwrite && error.code === 'EEXIST') { - return; - } + try { + let stats = fs.statSync(path); + callback(null, stats); + } + catch (err) { + callback(err); + } +}; - throw error; - } +/** + * A facade around {@link fs.lstatSync} that allows it to be called + * the same way as {@link fs.lstat}. + * + * @param {string} path + * @param {function} callback + */ +exports.lstat = function (path, callback) { + // Make sure the callback is only called once + callback = call.once(callback); - fs.utimesSync(destination, stat.atime, stat.mtime); - fixupAttributes(destination, stat); + try { + let stats = fs.lstatSync(path); + callback(null, stats); + } + catch (err) { + callback(err); + } }; /***/ }), -/* 792 */ +/* 801 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const pTimeout = __webpack_require__(793); - -const symbolAsyncIterator = Symbol.asyncIterator || '@@asyncIterator'; - -const normalizeEmitter = emitter => { - const addListener = emitter.on || emitter.addListener || emitter.addEventListener; - const removeListener = emitter.off || emitter.removeListener || emitter.removeEventListener; - - if (!addListener || !removeListener) { - throw new TypeError('Emitter is not compatible'); - } - - return { - addListener: addListener.bind(emitter), - removeListener: removeListener.bind(emitter) - }; -}; - -const normalizeEvents = event => Array.isArray(event) ? event : [event]; - -const multiple = (emitter, event, options) => { - let cancel; - const ret = new Promise((resolve, reject) => { - options = { - rejectionEvents: ['error'], - multiArgs: false, - resolveImmediately: false, - ...options - }; - - if (!(options.count >= 0 && (options.count === Infinity || Number.isInteger(options.count)))) { - throw new TypeError('The `count` option should be at least 0 or more'); - } - - // Allow multiple events - const events = normalizeEvents(event); - - const items = []; - const {addListener, removeListener} = normalizeEmitter(emitter); - - const onItem = (...args) => { - const value = options.multiArgs ? args : args[0]; - if (options.filter && !options.filter(value)) { - return; - } +module.exports = syncForEach; - items.push(value); +/** + * A facade that allows {@link Array.forEach} to be called as though it were asynchronous. + * + * @param {array} array - The array to iterate over + * @param {function} iterator - The function to call for each item in the array + * @param {function} done - The function to call when all iterators have completed + */ +function syncForEach (array, iterator, done) { + array.forEach(item => { + iterator(item, () => { + // Note: No error-handling here because this is currently only ever called + // by DirectoryReader, which never passes an `error` parameter to the callback. + // Instead, DirectoryReader emits an "error" event if an error occurs. + }); + }); - if (options.count === items.length) { - cancel(); - resolve(items); - } - }; + done(); +} - const rejectHandler = error => { - cancel(); - reject(error); - }; - cancel = () => { - for (const event of events) { - removeListener(event, onItem); - } +/***/ }), +/* 802 */ +/***/ (function(module, exports, __webpack_require__) { - for (const rejectionEvent of options.rejectionEvents) { - removeListener(rejectionEvent, rejectHandler); - } - }; +"use strict"; - for (const event of events) { - addListener(event, onItem); - } - for (const rejectionEvent of options.rejectionEvents) { - addListener(rejectionEvent, rejectHandler); - } +module.exports = readdirAsync; - if (options.resolveImmediately) { - resolve(items); - } - }); +const maybe = __webpack_require__(803); +const DirectoryReader = __webpack_require__(795); - ret.cancel = cancel; +let asyncFacade = { + fs: __webpack_require__(253), + forEach: __webpack_require__(804), + async: true +}; - if (typeof options.timeout === 'number') { - const timeout = pTimeout(ret, options.timeout); - timeout.cancel = cancel; - return timeout; - } +/** + * Returns the buffered output from an asynchronous {@link DirectoryReader}, + * via an error-first callback or a {@link Promise}. + * + * @param {string} dir + * @param {object} [options] + * @param {function} [callback] + * @param {object} internalOptions + */ +function readdirAsync (dir, options, callback, internalOptions) { + if (typeof options === 'function') { + callback = options; + options = undefined; + } - return ret; -}; + return maybe(callback, new Promise(((resolve, reject) => { + let results = []; -const pEvent = (emitter, event, options) => { - if (typeof options === 'function') { - options = {filter: options}; - } + internalOptions.facade = asyncFacade; - options = { - ...options, - count: 1, - resolveImmediately: false - }; + let reader = new DirectoryReader(dir, options, internalOptions); + let stream = reader.stream; - const arrayPromise = multiple(emitter, event, options); - const promise = arrayPromise.then(array => array[0]); // eslint-disable-line promise/prefer-await-to-then - promise.cancel = arrayPromise.cancel; + stream.on('error', err => { + reject(err); + stream.pause(); + }); + stream.on('data', result => { + results.push(result); + }); + stream.on('end', () => { + resolve(results); + }); + }))); +} - return promise; -}; -module.exports = pEvent; -// TODO: Remove this for the next major release -module.exports.default = pEvent; +/***/ }), +/* 803 */ +/***/ (function(module, exports, __webpack_require__) { -module.exports.multiple = multiple; +"use strict"; -module.exports.iterator = (emitter, event, options) => { - if (typeof options === 'function') { - options = {filter: options}; - } - // Allow multiple events - const events = normalizeEvents(event); +var next = (global.process && process.nextTick) || global.setImmediate || function (f) { + setTimeout(f, 0) +} - options = { - rejectionEvents: ['error'], - resolutionEvents: [], - limit: Infinity, - multiArgs: false, - ...options - }; +module.exports = function maybe (cb, promise) { + if (cb) { + promise + .then(function (result) { + next(function () { cb(null, result) }) + }, function (err) { + next(function () { cb(err) }) + }) + return undefined + } + else { + return promise + } +} - const {limit} = options; - const isValidLimit = limit >= 0 && (limit === Infinity || Number.isInteger(limit)); - if (!isValidLimit) { - throw new TypeError('The `limit` option should be a non-negative integer or Infinity'); - } - if (limit === 0) { - // Return an empty async iterator to avoid any further cost - return { - [Symbol.asyncIterator]() { - return this; - }, - async next() { - return { - done: true, - value: undefined - }; - } - }; - } +/***/ }), +/* 804 */ +/***/ (function(module, exports, __webpack_require__) { - const {addListener, removeListener} = normalizeEmitter(emitter); +"use strict"; - let isDone = false; - let error; - let hasPendingError = false; - const nextQueue = []; - const valueQueue = []; - let eventCount = 0; - let isLimitReached = false; - const valueHandler = (...args) => { - eventCount++; - isLimitReached = eventCount === limit; +module.exports = asyncForEach; - const value = options.multiArgs ? args : args[0]; +/** + * Simultaneously processes all items in the given array. + * + * @param {array} array - The array to iterate over + * @param {function} iterator - The function to call for each item in the array + * @param {function} done - The function to call when all iterators have completed + */ +function asyncForEach (array, iterator, done) { + if (array.length === 0) { + // NOTE: Normally a bad idea to mix sync and async, but it's safe here because + // of the way that this method is currently used by DirectoryReader. + done(); + return; + } - if (nextQueue.length > 0) { - const {resolve} = nextQueue.shift(); + // Simultaneously process all items in the array. + let pending = array.length; + array.forEach(item => { + iterator(item, () => { + if (--pending === 0) { + done(); + } + }); + }); +} - resolve({done: false, value}); - if (isLimitReached) { - cancel(); - } +/***/ }), +/* 805 */ +/***/ (function(module, exports, __webpack_require__) { - return; - } +"use strict"; - valueQueue.push(value); - if (isLimitReached) { - cancel(); - } - }; +module.exports = readdirStream; - const cancel = () => { - isDone = true; - for (const event of events) { - removeListener(event, valueHandler); - } +const DirectoryReader = __webpack_require__(795); - for (const rejectionEvent of options.rejectionEvents) { - removeListener(rejectionEvent, rejectHandler); - } +let streamFacade = { + fs: __webpack_require__(253), + forEach: __webpack_require__(804), + async: true +}; - for (const resolutionEvent of options.resolutionEvents) { - removeListener(resolutionEvent, resolveHandler); - } +/** + * Returns the {@link stream.Readable} of an asynchronous {@link DirectoryReader}. + * + * @param {string} dir + * @param {object} [options] + * @param {object} internalOptions + */ +function readdirStream (dir, options, internalOptions) { + internalOptions.facade = streamFacade; - while (nextQueue.length > 0) { - const {resolve} = nextQueue.shift(); - resolve({done: true, value: undefined}); - } - }; + let reader = new DirectoryReader(dir, options, internalOptions); + return reader.stream; +} - const rejectHandler = (...args) => { - error = options.multiArgs ? args : args[0]; - if (nextQueue.length > 0) { - const {reject} = nextQueue.shift(); - reject(error); - } else { - hasPendingError = true; - } +/***/ }), +/* 806 */ +/***/ (function(module, exports, __webpack_require__) { - cancel(); - }; +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var path = __webpack_require__(4); +var deep_1 = __webpack_require__(807); +var entry_1 = __webpack_require__(809); +var pathUtil = __webpack_require__(808); +var Reader = /** @class */ (function () { + function Reader(options) { + this.options = options; + this.micromatchOptions = this.getMicromatchOptions(); + this.entryFilter = new entry_1.default(options, this.micromatchOptions); + this.deepFilter = new deep_1.default(options, this.micromatchOptions); + } + /** + * Returns root path to scanner. + */ + Reader.prototype.getRootDirectory = function (task) { + return path.resolve(this.options.cwd, task.base); + }; + /** + * Returns options for reader. + */ + Reader.prototype.getReaderOptions = function (task) { + return { + basePath: task.base === '.' ? '' : task.base, + filter: this.entryFilter.getFilter(task.positive, task.negative), + deep: this.deepFilter.getFilter(task.positive, task.negative), + sep: '/' + }; + }; + /** + * Returns options for micromatch. + */ + Reader.prototype.getMicromatchOptions = function () { + return { + dot: this.options.dot, + nobrace: !this.options.brace, + noglobstar: !this.options.globstar, + noext: !this.options.extension, + nocase: !this.options.case, + matchBase: this.options.matchBase + }; + }; + /** + * Returns transformed entry. + */ + Reader.prototype.transform = function (entry) { + if (this.options.absolute) { + entry.path = pathUtil.makeAbsolute(this.options.cwd, entry.path); + } + if (this.options.markDirectories && entry.isDirectory()) { + entry.path += '/'; + } + var item = this.options.stats ? entry : entry.path; + if (this.options.transform === null) { + return item; + } + return this.options.transform(item); + }; + /** + * Returns true if error has ENOENT code. + */ + Reader.prototype.isEnoentCodeError = function (err) { + return err.code === 'ENOENT'; + }; + return Reader; +}()); +exports.default = Reader; - const resolveHandler = (...args) => { - const value = options.multiArgs ? args : args[0]; - if (options.filter && !options.filter(value)) { - return; - } +/***/ }), +/* 807 */ +/***/ (function(module, exports, __webpack_require__) { - if (nextQueue.length > 0) { - const {resolve} = nextQueue.shift(); - resolve({done: true, value}); - } else { - valueQueue.push(value); - } +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var pathUtils = __webpack_require__(808); +var patternUtils = __webpack_require__(642); +var DeepFilter = /** @class */ (function () { + function DeepFilter(options, micromatchOptions) { + this.options = options; + this.micromatchOptions = micromatchOptions; + } + /** + * Returns filter for directories. + */ + DeepFilter.prototype.getFilter = function (positive, negative) { + var _this = this; + var maxPatternDepth = this.getMaxPatternDepth(positive); + var negativeRe = this.getNegativePatternsRe(negative); + return function (entry) { return _this.filter(entry, negativeRe, maxPatternDepth); }; + }; + /** + * Returns max depth of the provided patterns. + */ + DeepFilter.prototype.getMaxPatternDepth = function (patterns) { + var globstar = patterns.some(patternUtils.hasGlobStar); + return globstar ? Infinity : patternUtils.getMaxNaivePatternsDepth(patterns); + }; + /** + * Returns RegExp's for patterns that can affect the depth of reading. + */ + DeepFilter.prototype.getNegativePatternsRe = function (patterns) { + var affectDepthOfReadingPatterns = patterns.filter(patternUtils.isAffectDepthOfReadingPattern); + return patternUtils.convertPatternsToRe(affectDepthOfReadingPatterns, this.micromatchOptions); + }; + /** + * Returns «true» for directory that should be read. + */ + DeepFilter.prototype.filter = function (entry, negativeRe, maxPatternDepth) { + if (this.isSkippedByDeepOption(entry.depth)) { + return false; + } + if (this.isSkippedByMaxPatternDepth(entry.depth, maxPatternDepth)) { + return false; + } + if (this.isSkippedSymlinkedDirectory(entry)) { + return false; + } + if (this.isSkippedDotDirectory(entry)) { + return false; + } + return this.isSkippedByNegativePatterns(entry, negativeRe); + }; + /** + * Returns «true» when the «deep» option is disabled or number and depth of the entry is greater that the option value. + */ + DeepFilter.prototype.isSkippedByDeepOption = function (entryDepth) { + return !this.options.deep || (typeof this.options.deep === 'number' && entryDepth >= this.options.deep); + }; + /** + * Returns «true» when depth parameter is not an Infinity and entry depth greater that the parameter value. + */ + DeepFilter.prototype.isSkippedByMaxPatternDepth = function (entryDepth, maxPatternDepth) { + return maxPatternDepth !== Infinity && entryDepth >= maxPatternDepth; + }; + /** + * Returns «true» for symlinked directory if the «followSymlinkedDirectories» option is disabled. + */ + DeepFilter.prototype.isSkippedSymlinkedDirectory = function (entry) { + return !this.options.followSymlinkedDirectories && entry.isSymbolicLink(); + }; + /** + * Returns «true» for a directory whose name starts with a period if «dot» option is disabled. + */ + DeepFilter.prototype.isSkippedDotDirectory = function (entry) { + return !this.options.dot && pathUtils.isDotDirectory(entry.path); + }; + /** + * Returns «true» for a directory whose path math to any negative pattern. + */ + DeepFilter.prototype.isSkippedByNegativePatterns = function (entry, negativeRe) { + return !patternUtils.matchAny(entry.path, negativeRe); + }; + return DeepFilter; +}()); +exports.default = DeepFilter; - cancel(); - }; - for (const event of events) { - addListener(event, valueHandler); - } +/***/ }), +/* 808 */ +/***/ (function(module, exports, __webpack_require__) { - for (const rejectionEvent of options.rejectionEvents) { - addListener(rejectionEvent, rejectHandler); - } +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var path = __webpack_require__(4); +/** + * Returns «true» if the last partial of the path starting with a period. + */ +function isDotDirectory(filepath) { + return path.basename(filepath).startsWith('.'); +} +exports.isDotDirectory = isDotDirectory; +/** + * Convert a windows-like path to a unix-style path. + */ +function normalize(filepath) { + return filepath.replace(/\\/g, '/'); +} +exports.normalize = normalize; +/** + * Returns normalized absolute path of provided filepath. + */ +function makeAbsolute(cwd, filepath) { + return normalize(path.resolve(cwd, filepath)); +} +exports.makeAbsolute = makeAbsolute; - for (const resolutionEvent of options.resolutionEvents) { - addListener(resolutionEvent, resolveHandler); - } - return { - [symbolAsyncIterator]() { - return this; - }, - async next() { - if (valueQueue.length > 0) { - const value = valueQueue.shift(); - return { - done: isDone && valueQueue.length === 0 && !isLimitReached, - value - }; - } +/***/ }), +/* 809 */ +/***/ (function(module, exports, __webpack_require__) { - if (hasPendingError) { - hasPendingError = false; - throw error; - } +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var pathUtils = __webpack_require__(808); +var patternUtils = __webpack_require__(642); +var EntryFilter = /** @class */ (function () { + function EntryFilter(options, micromatchOptions) { + this.options = options; + this.micromatchOptions = micromatchOptions; + this.index = new Map(); + } + /** + * Returns filter for directories. + */ + EntryFilter.prototype.getFilter = function (positive, negative) { + var _this = this; + var positiveRe = patternUtils.convertPatternsToRe(positive, this.micromatchOptions); + var negativeRe = patternUtils.convertPatternsToRe(negative, this.micromatchOptions); + return function (entry) { return _this.filter(entry, positiveRe, negativeRe); }; + }; + /** + * Returns true if entry must be added to result. + */ + EntryFilter.prototype.filter = function (entry, positiveRe, negativeRe) { + // Exclude duplicate results + if (this.options.unique) { + if (this.isDuplicateEntry(entry)) { + return false; + } + this.createIndexRecord(entry); + } + // Filter files and directories by options + if (this.onlyFileFilter(entry) || this.onlyDirectoryFilter(entry)) { + return false; + } + if (this.isSkippedByAbsoluteNegativePatterns(entry, negativeRe)) { + return false; + } + return this.isMatchToPatterns(entry.path, positiveRe) && !this.isMatchToPatterns(entry.path, negativeRe); + }; + /** + * Return true if the entry already has in the cross reader index. + */ + EntryFilter.prototype.isDuplicateEntry = function (entry) { + return this.index.has(entry.path); + }; + /** + * Create record in the cross reader index. + */ + EntryFilter.prototype.createIndexRecord = function (entry) { + this.index.set(entry.path, undefined); + }; + /** + * Returns true for non-files if the «onlyFiles» option is enabled. + */ + EntryFilter.prototype.onlyFileFilter = function (entry) { + return this.options.onlyFiles && !entry.isFile(); + }; + /** + * Returns true for non-directories if the «onlyDirectories» option is enabled. + */ + EntryFilter.prototype.onlyDirectoryFilter = function (entry) { + return this.options.onlyDirectories && !entry.isDirectory(); + }; + /** + * Return true when `absolute` option is enabled and matched to the negative patterns. + */ + EntryFilter.prototype.isSkippedByAbsoluteNegativePatterns = function (entry, negativeRe) { + if (!this.options.absolute) { + return false; + } + var fullpath = pathUtils.makeAbsolute(this.options.cwd, entry.path); + return this.isMatchToPatterns(fullpath, negativeRe); + }; + /** + * Return true when entry match to provided patterns. + * + * First, just trying to apply patterns to the path. + * Second, trying to apply patterns to the path with final slash (need to micromatch to support «directory/**» patterns). + */ + EntryFilter.prototype.isMatchToPatterns = function (filepath, patternsRe) { + return patternUtils.matchAny(filepath, patternsRe) || patternUtils.matchAny(filepath + '/', patternsRe); + }; + return EntryFilter; +}()); +exports.default = EntryFilter; - if (isDone) { - return { - done: true, - value: undefined - }; - } - return new Promise((resolve, reject) => nextQueue.push({resolve, reject})); - }, - async return(value) { - cancel(); - return { - done: isDone, - value - }; - } - }; -}; +/***/ }), +/* 810 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var stream = __webpack_require__(294); +var fsStat = __webpack_require__(811); +var fs_1 = __webpack_require__(815); +var FileSystemStream = /** @class */ (function (_super) { + __extends(FileSystemStream, _super); + function FileSystemStream() { + return _super !== null && _super.apply(this, arguments) || this; + } + /** + * Use stream API to read entries for Task. + */ + FileSystemStream.prototype.read = function (patterns, filter) { + var _this = this; + var filepaths = patterns.map(this.getFullEntryPath, this); + var transform = new stream.Transform({ objectMode: true }); + transform._transform = function (index, _enc, done) { + return _this.getEntry(filepaths[index], patterns[index]).then(function (entry) { + if (entry !== null && filter(entry)) { + transform.push(entry); + } + if (index === filepaths.length - 1) { + transform.end(); + } + done(); + }); + }; + for (var i = 0; i < filepaths.length; i++) { + transform.write(i); + } + return transform; + }; + /** + * Return entry for the provided path. + */ + FileSystemStream.prototype.getEntry = function (filepath, pattern) { + var _this = this; + return this.getStat(filepath) + .then(function (stat) { return _this.makeEntry(stat, pattern); }) + .catch(function () { return null; }); + }; + /** + * Return fs.Stats for the provided path. + */ + FileSystemStream.prototype.getStat = function (filepath) { + return fsStat.stat(filepath, { throwErrorOnBrokenSymlinks: false }); + }; + return FileSystemStream; +}(fs_1.default)); +exports.default = FileSystemStream; /***/ }), -/* 793 */ +/* 811 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const pFinally = __webpack_require__(794); - -class TimeoutError extends Error { - constructor(message) { - super(message); - this.name = 'TimeoutError'; - } +Object.defineProperty(exports, "__esModule", { value: true }); +const optionsManager = __webpack_require__(812); +const statProvider = __webpack_require__(814); +/** + * Asynchronous API. + */ +function stat(path, opts) { + return new Promise((resolve, reject) => { + statProvider.async(path, optionsManager.prepare(opts), (err, stats) => err ? reject(err) : resolve(stats)); + }); } +exports.stat = stat; +function statCallback(path, optsOrCallback, callback) { + if (typeof optsOrCallback === 'function') { + callback = optsOrCallback; /* tslint:disable-line: no-parameter-reassignment */ + optsOrCallback = undefined; /* tslint:disable-line: no-parameter-reassignment */ + } + if (typeof callback === 'undefined') { + throw new TypeError('The "callback" argument must be of type Function.'); + } + statProvider.async(path, optionsManager.prepare(optsOrCallback), callback); +} +exports.statCallback = statCallback; +/** + * Synchronous API. + */ +function statSync(path, opts) { + return statProvider.sync(path, optionsManager.prepare(opts)); +} +exports.statSync = statSync; -module.exports = (promise, ms, fallback) => new Promise((resolve, reject) => { - if (typeof ms !== 'number' || ms < 0) { - throw new TypeError('Expected `ms` to be a positive number'); - } - - const timer = setTimeout(() => { - if (typeof fallback === 'function') { - try { - resolve(fallback()); - } catch (err) { - reject(err); - } - return; - } - - const message = typeof fallback === 'string' ? fallback : `Promise timed out after ${ms} milliseconds`; - const err = fallback instanceof Error ? fallback : new TimeoutError(message); - - if (typeof promise.cancel === 'function') { - promise.cancel(); - } - reject(err); - }, ms); +/***/ }), +/* 812 */ +/***/ (function(module, exports, __webpack_require__) { - pFinally( - promise.then(resolve, reject), - () => { - clearTimeout(timer); - } - ); -}); +"use strict"; -module.exports.TimeoutError = TimeoutError; +Object.defineProperty(exports, "__esModule", { value: true }); +const fsAdapter = __webpack_require__(813); +function prepare(opts) { + const options = Object.assign({ + fs: fsAdapter.getFileSystemAdapter(opts ? opts.fs : undefined), + throwErrorOnBrokenSymlinks: true, + followSymlinks: true + }, opts); + return options; +} +exports.prepare = prepare; /***/ }), -/* 794 */ +/* 813 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -module.exports = (promise, onFinally) => { - onFinally = onFinally || (() => {}); - - return promise.then( - val => new Promise(resolve => { - resolve(onFinally()); - }).then(() => val), - err => new Promise(resolve => { - resolve(onFinally()); - }).then(() => { - throw err; - }) - ); +Object.defineProperty(exports, "__esModule", { value: true }); +const fs = __webpack_require__(253); +exports.FILE_SYSTEM_ADAPTER = { + lstat: fs.lstat, + stat: fs.stat, + lstatSync: fs.lstatSync, + statSync: fs.statSync }; +function getFileSystemAdapter(fsMethods) { + if (!fsMethods) { + return exports.FILE_SYSTEM_ADAPTER; + } + return Object.assign({}, exports.FILE_SYSTEM_ADAPTER, fsMethods); +} +exports.getFileSystemAdapter = getFileSystemAdapter; /***/ }), -/* 795 */ +/* 814 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const NestedError = __webpack_require__(796); - -class CpFileError extends NestedError { - constructor(message, nested) { - super(message, nested); - Object.assign(this, nested); - this.name = 'CpFileError'; - } +Object.defineProperty(exports, "__esModule", { value: true }); +function sync(path, options) { + const lstat = options.fs.lstatSync(path); + if (!isFollowedSymlink(lstat, options)) { + return lstat; + } + try { + const stat = options.fs.statSync(path); + stat.isSymbolicLink = () => true; + return stat; + } + catch (err) { + if (!options.throwErrorOnBrokenSymlinks) { + return lstat; + } + throw err; + } } - -module.exports = CpFileError; +exports.sync = sync; +function async(path, options, callback) { + options.fs.lstat(path, (err0, lstat) => { + if (err0) { + return callback(err0, undefined); + } + if (!isFollowedSymlink(lstat, options)) { + return callback(null, lstat); + } + options.fs.stat(path, (err1, stat) => { + if (err1) { + return options.throwErrorOnBrokenSymlinks ? callback(err1) : callback(null, lstat); + } + stat.isSymbolicLink = () => true; + callback(null, stat); + }); + }); +} +exports.async = async; +/** + * Returns `true` for followed symlink. + */ +function isFollowedSymlink(stat, options) { + return stat.isSymbolicLink() && options.followSymlinks; +} +exports.isFollowedSymlink = isFollowedSymlink; /***/ }), -/* 796 */ +/* 815 */ /***/ (function(module, exports, __webpack_require__) { -var inherits = __webpack_require__(234).inherits; +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var path = __webpack_require__(4); +var FileSystem = /** @class */ (function () { + function FileSystem(options) { + this.options = options; + } + /** + * Return full path to entry. + */ + FileSystem.prototype.getFullEntryPath = function (filepath) { + return path.resolve(this.options.cwd, filepath); + }; + /** + * Return an implementation of the Entry interface. + */ + FileSystem.prototype.makeEntry = function (stat, pattern) { + stat.path = pattern; + stat.depth = pattern.split('/').length; + return stat; + }; + return FileSystem; +}()); +exports.default = FileSystem; -var NestedError = function (message, nested) { - this.nested = nested; - if (message instanceof Error) { - nested = message; - } else if (typeof message !== 'undefined') { - Object.defineProperty(this, 'message', { - value: message, - writable: true, - enumerable: false, - configurable: true - }); - } +/***/ }), +/* 816 */ +/***/ (function(module, exports, __webpack_require__) { - Error.captureStackTrace(this, this.constructor); - var oldStackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack'); - var stackDescriptor = buildStackDescriptor(oldStackDescriptor, nested); - Object.defineProperty(this, 'stack', stackDescriptor); -}; +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var stream = __webpack_require__(294); +var readdir = __webpack_require__(793); +var reader_1 = __webpack_require__(806); +var fs_stream_1 = __webpack_require__(810); +var TransformStream = /** @class */ (function (_super) { + __extends(TransformStream, _super); + function TransformStream(reader) { + var _this = _super.call(this, { objectMode: true }) || this; + _this.reader = reader; + return _this; + } + TransformStream.prototype._transform = function (entry, _encoding, callback) { + callback(null, this.reader.transform(entry)); + }; + return TransformStream; +}(stream.Transform)); +var ReaderStream = /** @class */ (function (_super) { + __extends(ReaderStream, _super); + function ReaderStream() { + return _super !== null && _super.apply(this, arguments) || this; + } + Object.defineProperty(ReaderStream.prototype, "fsAdapter", { + /** + * Returns FileSystem adapter. + */ + get: function () { + return new fs_stream_1.default(this.options); + }, + enumerable: true, + configurable: true + }); + /** + * Use stream API to read entries for Task. + */ + ReaderStream.prototype.read = function (task) { + var _this = this; + var root = this.getRootDirectory(task); + var options = this.getReaderOptions(task); + var transform = new TransformStream(this); + var readable = this.api(root, task, options); + return readable + .on('error', function (err) { return _this.isEnoentCodeError(err) ? null : transform.emit('error', err); }) + .pipe(transform); + }; + /** + * Returns founded paths. + */ + ReaderStream.prototype.api = function (root, task, options) { + if (task.dynamic) { + return this.dynamicApi(root, options); + } + return this.staticApi(task, options); + }; + /** + * Api for dynamic tasks. + */ + ReaderStream.prototype.dynamicApi = function (root, options) { + return readdir.readdirStreamStat(root, options); + }; + /** + * Api for static tasks. + */ + ReaderStream.prototype.staticApi = function (task, options) { + return this.fsAdapter.read(task.patterns, options.filter); + }; + return ReaderStream; +}(reader_1.default)); +exports.default = ReaderStream; -function buildStackDescriptor(oldStackDescriptor, nested) { - if (oldStackDescriptor.get) { - return { - get: function () { - var stack = oldStackDescriptor.get.call(this); - return buildCombinedStacks(stack, this.nested); - } - }; - } else { - var stack = oldStackDescriptor.value; - return { - value: buildCombinedStacks(stack, nested) - }; - } -} -function buildCombinedStacks(stack, nested) { - if (nested) { - stack += '\nCaused By: ' + nested.stack; - } - return stack; -} +/***/ }), +/* 817 */ +/***/ (function(module, exports, __webpack_require__) { -inherits(NestedError, Error); -NestedError.prototype.name = 'NestedError'; +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var readdir = __webpack_require__(793); +var reader_1 = __webpack_require__(806); +var fs_sync_1 = __webpack_require__(818); +var ReaderSync = /** @class */ (function (_super) { + __extends(ReaderSync, _super); + function ReaderSync() { + return _super !== null && _super.apply(this, arguments) || this; + } + Object.defineProperty(ReaderSync.prototype, "fsAdapter", { + /** + * Returns FileSystem adapter. + */ + get: function () { + return new fs_sync_1.default(this.options); + }, + enumerable: true, + configurable: true + }); + /** + * Use sync API to read entries for Task. + */ + ReaderSync.prototype.read = function (task) { + var root = this.getRootDirectory(task); + var options = this.getReaderOptions(task); + try { + var entries = this.api(root, task, options); + return entries.map(this.transform, this); + } + catch (err) { + if (this.isEnoentCodeError(err)) { + return []; + } + throw err; + } + }; + /** + * Returns founded paths. + */ + ReaderSync.prototype.api = function (root, task, options) { + if (task.dynamic) { + return this.dynamicApi(root, options); + } + return this.staticApi(task, options); + }; + /** + * Api for dynamic tasks. + */ + ReaderSync.prototype.dynamicApi = function (root, options) { + return readdir.readdirSyncStat(root, options); + }; + /** + * Api for static tasks. + */ + ReaderSync.prototype.staticApi = function (task, options) { + return this.fsAdapter.read(task.patterns, options.filter); + }; + return ReaderSync; +}(reader_1.default)); +exports.default = ReaderSync; -module.exports = NestedError; +/***/ }), +/* 818 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var fsStat = __webpack_require__(811); +var fs_1 = __webpack_require__(815); +var FileSystemSync = /** @class */ (function (_super) { + __extends(FileSystemSync, _super); + function FileSystemSync() { + return _super !== null && _super.apply(this, arguments) || this; + } + /** + * Use sync API to read entries for Task. + */ + FileSystemSync.prototype.read = function (patterns, filter) { + var _this = this; + var entries = []; + patterns.forEach(function (pattern) { + var filepath = _this.getFullEntryPath(pattern); + var entry = _this.getEntry(filepath, pattern); + if (entry === null || !filter(entry)) { + return; + } + entries.push(entry); + }); + return entries; + }; + /** + * Return entry for the provided path. + */ + FileSystemSync.prototype.getEntry = function (filepath, pattern) { + try { + var stat = this.getStat(filepath); + return this.makeEntry(stat, pattern); + } + catch (err) { + return null; + } + }; + /** + * Return fs.Stats for the provided path. + */ + FileSystemSync.prototype.getStat = function (filepath) { + return fsStat.statSync(filepath, { throwErrorOnBrokenSymlinks: false }); + }; + return FileSystemSync; +}(fs_1.default)); +exports.default = FileSystemSync; /***/ }), -/* 797 */ +/* 819 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Flatten nested arrays (max depth is 2) into a non-nested array of non-array items. + */ +function flatten(items) { + return items.reduce(function (collection, item) { return [].concat(collection, item); }, []); +} +exports.flatten = flatten; -const {promisify} = __webpack_require__(234); -const fs = __webpack_require__(354); -const makeDir = __webpack_require__(798); -const pEvent = __webpack_require__(792); -const CpFileError = __webpack_require__(795); -const stat = promisify(fs.stat); -const lstat = promisify(fs.lstat); -const utimes = promisify(fs.utimes); -const chmod = promisify(fs.chmod); -const chown = promisify(fs.chown); +/***/ }), +/* 820 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var merge2 = __webpack_require__(364); +/** + * Merge multiple streams and propagate their errors into one stream in parallel. + */ +function merge(streams) { + var mergedStream = merge2(streams); + streams.forEach(function (stream) { + stream.on('error', function (err) { return mergedStream.emit('error', err); }); + }); + return mergedStream; +} +exports.merge = merge; -exports.closeSync = fs.closeSync.bind(fs); -exports.createWriteStream = fs.createWriteStream.bind(fs); -exports.createReadStream = async (path, options) => { - const read = fs.createReadStream(path, options); +/***/ }), +/* 821 */ +/***/ (function(module, exports, __webpack_require__) { - try { - await pEvent(read, ['readable', 'end']); - } catch (error) { - throw new CpFileError(`Cannot read from \`${path}\`: ${error.message}`, error); - } +"use strict"; - return read; -}; +const path = __webpack_require__(4); +const pathType = __webpack_require__(822); -exports.stat = path => stat(path).catch(error => { - throw new CpFileError(`Cannot stat path \`${path}\`: ${error.message}`, error); -}); +const getExtensions = extensions => extensions.length > 1 ? `{${extensions.join(',')}}` : extensions[0]; -exports.lstat = path => lstat(path).catch(error => { - throw new CpFileError(`lstat \`${path}\` failed: ${error.message}`, error); -}); +const getPath = (filepath, cwd) => { + const pth = filepath[0] === '!' ? filepath.slice(1) : filepath; + return path.isAbsolute(pth) ? pth : path.join(cwd, pth); +}; -exports.utimes = (path, atime, mtime) => utimes(path, atime, mtime).catch(error => { - throw new CpFileError(`utimes \`${path}\` failed: ${error.message}`, error); -}); +const addExtensions = (file, extensions) => { + if (path.extname(file)) { + return `**/${file}`; + } -exports.chmod = (path, mode) => chmod(path, mode).catch(error => { - throw new CpFileError(`chmod \`${path}\` failed: ${error.message}`, error); -}); + return `**/${file}.${getExtensions(extensions)}`; +}; -exports.chown = (path, uid, gid) => chown(path, uid, gid).catch(error => { - throw new CpFileError(`chown \`${path}\` failed: ${error.message}`, error); -}); +const getGlob = (dir, opts) => { + if (opts.files && !Array.isArray(opts.files)) { + throw new TypeError(`Expected \`files\` to be of type \`Array\` but received type \`${typeof opts.files}\``); + } -exports.statSync = path => { - try { - return fs.statSync(path); - } catch (error) { - throw new CpFileError(`stat \`${path}\` failed: ${error.message}`, error); + if (opts.extensions && !Array.isArray(opts.extensions)) { + throw new TypeError(`Expected \`extensions\` to be of type \`Array\` but received type \`${typeof opts.extensions}\``); } -}; -exports.utimesSync = (path, atime, mtime) => { - try { - return fs.utimesSync(path, atime, mtime); - } catch (error) { - throw new CpFileError(`utimes \`${path}\` failed: ${error.message}`, error); + if (opts.files && opts.extensions) { + return opts.files.map(x => path.join(dir, addExtensions(x, opts.extensions))); } -}; -exports.chmodSync = (path, mode) => { - try { - return fs.chmodSync(path, mode); - } catch (error) { - throw new CpFileError(`chmod \`${path}\` failed: ${error.message}`, error); + if (opts.files) { + return opts.files.map(x => path.join(dir, `**/${x}`)); } -}; -exports.chownSync = (path, uid, gid) => { - try { - return fs.chownSync(path, uid, gid); - } catch (error) { - throw new CpFileError(`chown \`${path}\` failed: ${error.message}`, error); + if (opts.extensions) { + return [path.join(dir, `**/*.${getExtensions(opts.extensions)}`)]; } + + return [path.join(dir, '**')]; }; -exports.makeDir = path => makeDir(path, {fs}).catch(error => { - throw new CpFileError(`Cannot create directory \`${path}\`: ${error.message}`, error); -}); +module.exports = (input, opts) => { + opts = Object.assign({cwd: process.cwd()}, opts); -exports.makeDirSync = path => { - try { - makeDir.sync(path, {fs}); - } catch (error) { - throw new CpFileError(`Cannot create directory \`${path}\`: ${error.message}`, error); + if (typeof opts.cwd !== 'string') { + return Promise.reject(new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof opts.cwd}\``)); } + + return Promise.all([].concat(input).map(x => pathType.dir(getPath(x, opts.cwd)) + .then(isDir => isDir ? getGlob(x, opts) : x))) + .then(globs => [].concat.apply([], globs)); }; -exports.copyFileSync = (source, destination, flags) => { - try { - fs.copyFileSync(source, destination, flags); - } catch (error) { - throw new CpFileError(`Cannot copy from \`${source}\` to \`${destination}\`: ${error.message}`, error); +module.exports.sync = (input, opts) => { + opts = Object.assign({cwd: process.cwd()}, opts); + + if (typeof opts.cwd !== 'string') { + throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof opts.cwd}\``); } + + const globs = [].concat(input).map(x => pathType.dirSync(getPath(x, opts.cwd)) ? getGlob(x, opts) : x); + return [].concat.apply([], globs); }; /***/ }), -/* 798 */ +/* 822 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; const fs = __webpack_require__(253); -const path = __webpack_require__(4); -const {promisify} = __webpack_require__(234); -const semver = __webpack_require__(799); +const pify = __webpack_require__(823); -const useNativeRecursiveOption = semver.satisfies(process.version, '>=10.12.0'); +function type(fn, fn2, fp) { + if (typeof fp !== 'string') { + return Promise.reject(new TypeError(`Expected a string, got ${typeof fp}`)); + } -// https://github.com/nodejs/node/issues/8987 -// https://github.com/libuv/libuv/pull/1088 -const checkPath = pth => { - if (process.platform === 'win32') { - const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path.parse(pth).root, '')); + return pify(fs[fn])(fp) + .then(stats => stats[fn2]()) + .catch(err => { + if (err.code === 'ENOENT') { + return false; + } - if (pathHasInvalidWinCharacters) { - const error = new Error(`Path contains invalid characters: ${pth}`); - error.code = 'EINVAL'; - throw error; - } + throw err; + }); +} + +function typeSync(fn, fn2, fp) { + if (typeof fp !== 'string') { + throw new TypeError(`Expected a string, got ${typeof fp}`); } -}; -const processOptions = options => { - // https://github.com/sindresorhus/make-dir/issues/18 - const defaults = { - mode: 0o777, - fs - }; + try { + return fs[fn](fp)[fn2](); + } catch (err) { + if (err.code === 'ENOENT') { + return false; + } - return { - ...defaults, - ...options - }; -}; + throw err; + } +} -const permissionError = pth => { - // This replicates the exception of `fs.mkdir` with native the - // `recusive` option when run on an invalid drive under Windows. - const error = new Error(`operation not permitted, mkdir '${pth}'`); - error.code = 'EPERM'; - error.errno = -4048; - error.path = pth; - error.syscall = 'mkdir'; - return error; -}; +exports.file = type.bind(null, 'stat', 'isFile'); +exports.dir = type.bind(null, 'stat', 'isDirectory'); +exports.symlink = type.bind(null, 'lstat', 'isSymbolicLink'); +exports.fileSync = typeSync.bind(null, 'statSync', 'isFile'); +exports.dirSync = typeSync.bind(null, 'statSync', 'isDirectory'); +exports.symlinkSync = typeSync.bind(null, 'lstatSync', 'isSymbolicLink'); -const makeDir = async (input, options) => { - checkPath(input); - options = processOptions(options); - const mkdir = promisify(options.fs.mkdir); - const stat = promisify(options.fs.stat); +/***/ }), +/* 823 */ +/***/ (function(module, exports, __webpack_require__) { - if (useNativeRecursiveOption && options.fs.mkdir === fs.mkdir) { - const pth = path.resolve(input); +"use strict"; - await mkdir(pth, { - mode: options.mode, - recursive: true - }); - return pth; +const processFn = (fn, opts) => function () { + const P = opts.promiseModule; + const args = new Array(arguments.length); + + for (let i = 0; i < arguments.length; i++) { + args[i] = arguments[i]; } - const make = async pth => { - try { - await mkdir(pth, options.mode); + return new P((resolve, reject) => { + if (opts.errorFirst) { + args.push(function (err, result) { + if (opts.multiArgs) { + const results = new Array(arguments.length - 1); - return pth; - } catch (error) { - if (error.code === 'EPERM') { - throw error; - } + for (let i = 1; i < arguments.length; i++) { + results[i - 1] = arguments[i]; + } - if (error.code === 'ENOENT') { - if (path.dirname(pth) === pth) { - throw permissionError(pth); + if (err) { + results.unshift(err); + reject(results); + } else { + resolve(results); + } + } else if (err) { + reject(err); + } else { + resolve(result); } + }); + } else { + args.push(function (result) { + if (opts.multiArgs) { + const results = new Array(arguments.length - 1); - if (error.message.includes('null bytes')) { - throw error; + for (let i = 0; i < arguments.length; i++) { + results[i] = arguments[i]; + } + + resolve(results); + } else { + resolve(result); } + }); + } - await make(path.dirname(pth)); + fn.apply(this, args); + }); +}; - return make(pth); - } +module.exports = (obj, opts) => { + opts = Object.assign({ + exclude: [/.+(Sync|Stream)$/], + errorFirst: true, + promiseModule: Promise + }, opts); - try { - const stats = await stat(pth); - if (!stats.isDirectory()) { - throw new Error('The path is not a directory'); - } - } catch (_) { - throw error; + const filter = key => { + const match = pattern => typeof pattern === 'string' ? key === pattern : pattern.test(key); + return opts.include ? opts.include.some(match) : !opts.exclude.some(match); + }; + + let ret; + if (typeof obj === 'function') { + ret = function () { + if (opts.excludeMain) { + return obj.apply(this, arguments); } - return pth; - } - }; + return processFn(obj, opts).apply(this, arguments); + }; + } else { + ret = Object.create(Object.getPrototypeOf(obj)); + } - return make(path.resolve(input)); -}; + for (const key in obj) { // eslint-disable-line guard-for-in + const x = obj[key]; + ret[key] = typeof x === 'function' && filter(key) ? processFn(x, opts) : x; + } -module.exports = makeDir; + return ret; +}; -module.exports.sync = (input, options) => { - checkPath(input); - options = processOptions(options); - if (useNativeRecursiveOption && options.fs.mkdirSync === fs.mkdirSync) { - const pth = path.resolve(input); +/***/ }), +/* 824 */ +/***/ (function(module, exports, __webpack_require__) { - fs.mkdirSync(pth, { - mode: options.mode, - recursive: true - }); +"use strict"; - return pth; - } +const fs = __webpack_require__(253); +const path = __webpack_require__(4); +const fastGlob = __webpack_require__(638); +const gitIgnore = __webpack_require__(825); +const pify = __webpack_require__(526); +const slash = __webpack_require__(826); - const make = pth => { - try { - options.fs.mkdirSync(pth, options.mode); - } catch (error) { - if (error.code === 'EPERM') { - throw error; - } +const DEFAULT_IGNORE = [ + '**/node_modules/**', + '**/bower_components/**', + '**/flow-typed/**', + '**/coverage/**', + '**/.git' +]; - if (error.code === 'ENOENT') { - if (path.dirname(pth) === pth) { - throw permissionError(pth); - } +const readFileP = pify(fs.readFile); - if (error.message.includes('null bytes')) { - throw error; - } +const mapGitIgnorePatternTo = base => ignore => { + if (ignore.startsWith('!')) { + return '!' + path.posix.join(base, ignore.slice(1)); + } - make(path.dirname(pth)); - return make(pth); - } + return path.posix.join(base, ignore); +}; - try { - if (!options.fs.statSync(pth).isDirectory()) { - throw new Error('The path is not a directory'); - } - } catch (_) { - throw error; - } - } +const parseGitIgnore = (content, options) => { + const base = slash(path.relative(options.cwd, path.dirname(options.fileName))); - return pth; - }; + return content + .split(/\r?\n/) + .filter(Boolean) + .filter(line => line.charAt(0) !== '#') + .map(mapGitIgnorePatternTo(base)); +}; - return make(path.resolve(input)); +const reduceIgnore = files => { + return files.reduce((ignores, file) => { + ignores.add(parseGitIgnore(file.content, { + cwd: file.cwd, + fileName: file.filePath + })); + return ignores; + }, gitIgnore()); }; +const getIsIgnoredPredecate = (ignores, cwd) => { + return p => ignores.ignores(slash(path.relative(cwd, p))); +}; -/***/ }), -/* 799 */ -/***/ (function(module, exports) { +const getFile = (file, cwd) => { + const filePath = path.join(cwd, file); + return readFileP(filePath, 'utf8') + .then(content => ({ + content, + cwd, + filePath + })); +}; -exports = module.exports = SemVer +const getFileSync = (file, cwd) => { + const filePath = path.join(cwd, file); + const content = fs.readFileSync(filePath, 'utf8'); -var debug -/* istanbul ignore next */ -if (typeof process === 'object' && - process.env && - process.env.NODE_DEBUG && - /\bsemver\b/i.test(process.env.NODE_DEBUG)) { - debug = function () { - var args = Array.prototype.slice.call(arguments, 0) - args.unshift('SEMVER') - console.log.apply(console, args) - } -} else { - debug = function () {} -} + return { + content, + cwd, + filePath + }; +}; -// Note: this is the semver.org version of the spec that it implements -// Not necessarily the package version of this code. -exports.SEMVER_SPEC_VERSION = '2.0.0' +const normalizeOptions = (options = {}) => { + const ignore = options.ignore || []; + const cwd = options.cwd || process.cwd(); + return {ignore, cwd}; +}; -var MAX_LENGTH = 256 -var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || - /* istanbul ignore next */ 9007199254740991 +module.exports = options => { + options = normalizeOptions(options); -// Max safe segment length for coercion. -var MAX_SAFE_COMPONENT_LENGTH = 16 + return fastGlob('**/.gitignore', { + ignore: DEFAULT_IGNORE.concat(options.ignore), + cwd: options.cwd + }) + .then(paths => Promise.all(paths.map(file => getFile(file, options.cwd)))) + .then(files => reduceIgnore(files)) + .then(ignores => getIsIgnoredPredecate(ignores, options.cwd)); +}; -// The actual regexps go on exports.re -var re = exports.re = [] -var src = exports.src = [] -var t = exports.tokens = {} -var R = 0 +module.exports.sync = options => { + options = normalizeOptions(options); -function tok (n) { - t[n] = R++ -} + const paths = fastGlob.sync('**/.gitignore', { + ignore: DEFAULT_IGNORE.concat(options.ignore), + cwd: options.cwd + }); + const files = paths.map(file => getFileSync(file, options.cwd)); + const ignores = reduceIgnore(files); -// The following Regular Expressions can be used for tokenizing, -// validating, and parsing SemVer version strings. + return getIsIgnoredPredecate(ignores, options.cwd); +}; -// ## Numeric Identifier -// A single `0`, or a non-zero digit followed by zero or more digits. -tok('NUMERICIDENTIFIER') -src[t.NUMERICIDENTIFIER] = '0|[1-9]\\d*' -tok('NUMERICIDENTIFIERLOOSE') -src[t.NUMERICIDENTIFIERLOOSE] = '[0-9]+' +/***/ }), +/* 825 */ +/***/ (function(module, exports) { -// ## Non-numeric Identifier -// Zero or more digits, followed by a letter or hyphen, and then zero or -// more letters, digits, or hyphens. +// A simple implementation of make-array +function make_array (subject) { + return Array.isArray(subject) + ? subject + : [subject] +} -tok('NONNUMERICIDENTIFIER') -src[t.NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' +const REGEX_BLANK_LINE = /^\s+$/ +const REGEX_LEADING_EXCAPED_EXCLAMATION = /^\\!/ +const REGEX_LEADING_EXCAPED_HASH = /^\\#/ +const SLASH = '/' +const KEY_IGNORE = typeof Symbol !== 'undefined' + ? Symbol.for('node-ignore') + /* istanbul ignore next */ + : 'node-ignore' -// ## Main Version -// Three dot-separated numeric identifiers. +const define = (object, key, value) => + Object.defineProperty(object, key, {value}) -tok('MAINVERSION') -src[t.MAINVERSION] = '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + - '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + - '(' + src[t.NUMERICIDENTIFIER] + ')' +const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g -tok('MAINVERSIONLOOSE') -src[t.MAINVERSIONLOOSE] = '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')' +// Sanitize the range of a regular expression +// The cases are complicated, see test cases for details +const sanitizeRange = range => range.replace( + REGEX_REGEXP_RANGE, + (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) + ? match + // Invalid range (out of order) which is ok for gitignore rules but + // fatal for JavaScript regular expression, so eliminate it. + : '' +) -// ## Pre-release Version Identifier -// A numeric identifier, or a non-numeric identifier. +// > If the pattern ends with a slash, +// > it is removed for the purpose of the following description, +// > but it would only find a match with a directory. +// > In other words, foo/ will match a directory foo and paths underneath it, +// > but will not match a regular file or a symbolic link foo +// > (this is consistent with the way how pathspec works in general in Git). +// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`' +// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call +// you could use option `mark: true` with `glob` -tok('PRERELEASEIDENTIFIER') -src[t.PRERELEASEIDENTIFIER] = '(?:' + src[t.NUMERICIDENTIFIER] + - '|' + src[t.NONNUMERICIDENTIFIER] + ')' +// '`foo/`' should not continue with the '`..`' +const DEFAULT_REPLACER_PREFIX = [ -tok('PRERELEASEIDENTIFIERLOOSE') -src[t.PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[t.NUMERICIDENTIFIERLOOSE] + - '|' + src[t.NONNUMERICIDENTIFIER] + ')' + // > Trailing spaces are ignored unless they are quoted with backslash ("\") + [ + // (a\ ) -> (a ) + // (a ) -> (a) + // (a \ ) -> (a ) + /\\?\s+$/, + match => match.indexOf('\\') === 0 + ? ' ' + : '' + ], -// ## Pre-release Version -// Hyphen, followed by one or more dot-separated pre-release version -// identifiers. + // replace (\ ) with ' ' + [ + /\\\s/g, + () => ' ' + ], -tok('PRERELEASE') -src[t.PRERELEASE] = '(?:-(' + src[t.PRERELEASEIDENTIFIER] + - '(?:\\.' + src[t.PRERELEASEIDENTIFIER] + ')*))' + // Escape metacharacters + // which is written down by users but means special for regular expressions. -tok('PRERELEASELOOSE') -src[t.PRERELEASELOOSE] = '(?:-?(' + src[t.PRERELEASEIDENTIFIERLOOSE] + - '(?:\\.' + src[t.PRERELEASEIDENTIFIERLOOSE] + ')*))' + // > There are 12 characters with special meanings: + // > - the backslash \, + // > - the caret ^, + // > - the dollar sign $, + // > - the period or dot ., + // > - the vertical bar or pipe symbol |, + // > - the question mark ?, + // > - the asterisk or star *, + // > - the plus sign +, + // > - the opening parenthesis (, + // > - the closing parenthesis ), + // > - and the opening square bracket [, + // > - the opening curly brace {, + // > These special characters are often called "metacharacters". + [ + /[\\^$.|*+(){]/g, + match => `\\${match}` + ], -// ## Build Metadata Identifier -// Any combination of digits, letters, or hyphens. + [ + // > [abc] matches any character inside the brackets + // > (in this case a, b, or c); + /\[([^\]/]*)($|\])/g, + (match, p1, p2) => p2 === ']' + ? `[${sanitizeRange(p1)}]` + : `\\${match}` + ], -tok('BUILDIDENTIFIER') -src[t.BUILDIDENTIFIER] = '[0-9A-Za-z-]+' + [ + // > a question mark (?) matches a single character + /(?!\\)\?/g, + () => '[^/]' + ], -// ## Build Metadata -// Plus sign, followed by one or more period-separated build metadata -// identifiers. + // leading slash + [ -tok('BUILD') -src[t.BUILD] = '(?:\\+(' + src[t.BUILDIDENTIFIER] + - '(?:\\.' + src[t.BUILDIDENTIFIER] + ')*))' + // > A leading slash matches the beginning of the pathname. + // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c". + // A leading slash matches the beginning of the pathname + /^\//, + () => '^' + ], -// ## Full Version String -// A main version, followed optionally by a pre-release version and -// build metadata. + // replace special metacharacter slash after the leading slash + [ + /\//g, + () => '\\/' + ], -// Note that the only major, minor, patch, and pre-release sections of -// the version string are capturing groups. The build metadata is not a -// capturing group, because it should not ever be used in version -// comparison. + [ + // > A leading "**" followed by a slash means match in all directories. + // > For example, "**/foo" matches file or directory "foo" anywhere, + // > the same as pattern "foo". + // > "**/foo/bar" matches file or directory "bar" anywhere that is directly + // > under directory "foo". + // Notice that the '*'s have been replaced as '\\*' + /^\^*\\\*\\\*\\\//, -tok('FULL') -tok('FULLPLAIN') -src[t.FULLPLAIN] = 'v?' + src[t.MAINVERSION] + - src[t.PRERELEASE] + '?' + - src[t.BUILD] + '?' + // '**/foo' <-> 'foo' + () => '^(?:.*\\/)?' + ] +] -src[t.FULL] = '^' + src[t.FULLPLAIN] + '$' +const DEFAULT_REPLACER_SUFFIX = [ + // starting + [ + // there will be no leading '/' + // (which has been replaced by section "leading slash") + // If starts with '**', adding a '^' to the regular expression also works + /^(?=[^^])/, + function startingReplacer () { + return !/\/(?!$)/.test(this) + // > If the pattern does not contain a slash /, + // > Git treats it as a shell glob pattern + // Actually, if there is only a trailing slash, + // git also treats it as a shell glob pattern + ? '(?:^|\\/)' -// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. -// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty -// common in the npm registry. -tok('LOOSEPLAIN') -src[t.LOOSEPLAIN] = '[v=\\s]*' + src[t.MAINVERSIONLOOSE] + - src[t.PRERELEASELOOSE] + '?' + - src[t.BUILD] + '?' + // > Otherwise, Git treats the pattern as a shell glob suitable for + // > consumption by fnmatch(3) + : '^' + } + ], -tok('LOOSE') -src[t.LOOSE] = '^' + src[t.LOOSEPLAIN] + '$' + // two globstars + [ + // Use lookahead assertions so that we could match more than one `'/**'` + /\\\/\\\*\\\*(?=\\\/|$)/g, -tok('GTLT') -src[t.GTLT] = '((?:<|>)?=?)' + // Zero, one or several directories + // should not use '*', or it will be replaced by the next replacer -// Something like "2.*" or "1.2.x". -// Note that "x.x" is a valid xRange identifer, meaning "any version" -// Only the first item is strictly required. -tok('XRANGEIDENTIFIERLOOSE') -src[t.XRANGEIDENTIFIERLOOSE] = src[t.NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' -tok('XRANGEIDENTIFIER') -src[t.XRANGEIDENTIFIER] = src[t.NUMERICIDENTIFIER] + '|x|X|\\*' + // Check if it is not the last `'/**'` + (match, index, str) => index + 6 < str.length -tok('XRANGEPLAIN') -src[t.XRANGEPLAIN] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + - '(?:' + src[t.PRERELEASE] + ')?' + - src[t.BUILD] + '?' + - ')?)?' + // case: /**/ + // > A slash followed by two consecutive asterisks then a slash matches + // > zero or more directories. + // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on. + // '/**/' + ? '(?:\\/[^\\/]+)*' -tok('XRANGEPLAINLOOSE') -src[t.XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + - '(?:' + src[t.PRERELEASELOOSE] + ')?' + - src[t.BUILD] + '?' + - ')?)?' + // case: /** + // > A trailing `"/**"` matches everything inside. -tok('XRANGE') -src[t.XRANGE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAIN] + '$' -tok('XRANGELOOSE') -src[t.XRANGELOOSE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAINLOOSE] + '$' + // #21: everything inside but it should not include the current folder + : '\\/.+' + ], -// Coercion. -// Extract anything that could conceivably be a part of a valid semver -tok('COERCE') -src[t.COERCE] = '(^|[^\\d])' + - '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:$|[^\\d])' -tok('COERCERTL') -re[t.COERCERTL] = new RegExp(src[t.COERCE], 'g') + // intermediate wildcards + [ + // Never replace escaped '*' + // ignore rule '\*' will match the path '*' -// Tilde ranges. -// Meaning is "reasonably at or greater than" -tok('LONETILDE') -src[t.LONETILDE] = '(?:~>?)' + // 'abc.*/' -> go + // 'abc.*' -> skip this rule + /(^|[^\\]+)\\\*(?=.+)/g, -tok('TILDETRIM') -src[t.TILDETRIM] = '(\\s*)' + src[t.LONETILDE] + '\\s+' -re[t.TILDETRIM] = new RegExp(src[t.TILDETRIM], 'g') -var tildeTrimReplace = '$1~' + // '*.js' matches '.js' + // '*.js' doesn't match 'abc' + (match, p1) => `${p1}[^\\/]*` + ], -tok('TILDE') -src[t.TILDE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAIN] + '$' -tok('TILDELOOSE') -src[t.TILDELOOSE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAINLOOSE] + '$' + // trailing wildcard + [ + /(\^|\\\/)?\\\*$/, + (match, p1) => { + const prefix = p1 + // '\^': + // '/*' does not match '' + // '/*' does not match everything -// Caret ranges. -// Meaning is "at least and backwards compatible with" -tok('LONECARET') -src[t.LONECARET] = '(?:\\^)' + // '\\\/': + // 'abc/*' does not match 'abc/' + ? `${p1}[^/]+` -tok('CARETTRIM') -src[t.CARETTRIM] = '(\\s*)' + src[t.LONECARET] + '\\s+' -re[t.CARETTRIM] = new RegExp(src[t.CARETTRIM], 'g') -var caretTrimReplace = '$1^' + // 'a*' matches 'a' + // 'a*' matches 'aa' + : '[^/]*' -tok('CARET') -src[t.CARET] = '^' + src[t.LONECARET] + src[t.XRANGEPLAIN] + '$' -tok('CARETLOOSE') -src[t.CARETLOOSE] = '^' + src[t.LONECARET] + src[t.XRANGEPLAINLOOSE] + '$' + return `${prefix}(?=$|\\/$)` + } + ], -// A simple gt/lt/eq thing, or just "" to indicate "any version" -tok('COMPARATORLOOSE') -src[t.COMPARATORLOOSE] = '^' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + ')$|^$' -tok('COMPARATOR') -src[t.COMPARATOR] = '^' + src[t.GTLT] + '\\s*(' + src[t.FULLPLAIN] + ')$|^$' + [ + // unescape + /\\\\\\/g, + () => '\\' + ] +] -// An expression to strip any whitespace between the gtlt and the thing -// it modifies, so that `> 1.2.3` ==> `>1.2.3` -tok('COMPARATORTRIM') -src[t.COMPARATORTRIM] = '(\\s*)' + src[t.GTLT] + - '\\s*(' + src[t.LOOSEPLAIN] + '|' + src[t.XRANGEPLAIN] + ')' +const POSITIVE_REPLACERS = [ + ...DEFAULT_REPLACER_PREFIX, -// this one has to use the /g flag -re[t.COMPARATORTRIM] = new RegExp(src[t.COMPARATORTRIM], 'g') -var comparatorTrimReplace = '$1$2$3' + // 'f' + // matches + // - /f(end) + // - /f/ + // - (start)f(end) + // - (start)f/ + // doesn't match + // - oof + // - foo + // pseudo: + // -> (^|/)f(/|$) -// Something like `1.2.3 - 1.2.4` -// Note that these all use the loose form, because they'll be -// checked against either the strict or loose comparator form -// later. -tok('HYPHENRANGE') -src[t.HYPHENRANGE] = '^\\s*(' + src[t.XRANGEPLAIN] + ')' + - '\\s+-\\s+' + - '(' + src[t.XRANGEPLAIN] + ')' + - '\\s*$' + // ending + [ + // 'js' will not match 'js.' + // 'ab' will not match 'abc' + /(?:[^*/])$/, -tok('HYPHENRANGELOOSE') -src[t.HYPHENRANGELOOSE] = '^\\s*(' + src[t.XRANGEPLAINLOOSE] + ')' + - '\\s+-\\s+' + - '(' + src[t.XRANGEPLAINLOOSE] + ')' + - '\\s*$' + // 'js*' will not match 'a.js' + // 'js/' will not match 'a.js' + // 'js' will match 'a.js' and 'a.js/' + match => `${match}(?=$|\\/)` + ], -// Star ranges basically just allow anything at all. -tok('STAR') -src[t.STAR] = '(<|>)?=?\\s*\\*' + ...DEFAULT_REPLACER_SUFFIX +] -// Compile to actual regexp objects. -// All are flag-free, unless they were created above with a flag. -for (var i = 0; i < R; i++) { - debug(i, src[i]) - if (!re[i]) { - re[i] = new RegExp(src[i]) - } -} +const NEGATIVE_REPLACERS = [ + ...DEFAULT_REPLACER_PREFIX, -exports.parse = parse -function parse (version, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } + // #24, #38 + // The MISSING rule of [gitignore docs](https://git-scm.com/docs/gitignore) + // A negative pattern without a trailing wildcard should not + // re-include the things inside that directory. - if (version instanceof SemVer) { - return version - } + // eg: + // ['node_modules/*', '!node_modules'] + // should ignore `node_modules/a.js` + [ + /(?:[^*])$/, + match => `${match}(?=$|\\/$)` + ], - if (typeof version !== 'string') { - return null - } + ...DEFAULT_REPLACER_SUFFIX +] - if (version.length > MAX_LENGTH) { - return null - } +// A simple cache, because an ignore rule only has only one certain meaning +const cache = Object.create(null) - var r = options.loose ? re[t.LOOSE] : re[t.FULL] - if (!r.test(version)) { - return null +// @param {pattern} +const make_regex = (pattern, negative, ignorecase) => { + const r = cache[pattern] + if (r) { + return r } - try { - return new SemVer(version, options) - } catch (er) { - return null - } -} + const replacers = negative + ? NEGATIVE_REPLACERS + : POSITIVE_REPLACERS -exports.valid = valid -function valid (version, options) { - var v = parse(version, options) - return v ? v.version : null -} + const source = replacers.reduce( + (prev, current) => prev.replace(current[0], current[1].bind(pattern)), + pattern + ) -exports.clean = clean -function clean (version, options) { - var s = parse(version.trim().replace(/^[=v]+/, ''), options) - return s ? s.version : null + return cache[pattern] = ignorecase + ? new RegExp(source, 'i') + : new RegExp(source) } -exports.SemVer = SemVer +// > A blank line matches no files, so it can serve as a separator for readability. +const checkPattern = pattern => pattern + && typeof pattern === 'string' + && !REGEX_BLANK_LINE.test(pattern) -function SemVer (version, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - if (version instanceof SemVer) { - if (version.loose === options.loose) { - return version - } else { - version = version.version - } - } else if (typeof version !== 'string') { - throw new TypeError('Invalid Version: ' + version) - } + // > A line starting with # serves as a comment. + && pattern.indexOf('#') !== 0 - if (version.length > MAX_LENGTH) { - throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') - } +const createRule = (pattern, ignorecase) => { + const origin = pattern + let negative = false - if (!(this instanceof SemVer)) { - return new SemVer(version, options) + // > An optional prefix "!" which negates the pattern; + if (pattern.indexOf('!') === 0) { + negative = true + pattern = pattern.substr(1) } - debug('SemVer', version, options) - this.options = options - this.loose = !!options.loose + pattern = pattern + // > Put a backslash ("\") in front of the first "!" for patterns that + // > begin with a literal "!", for example, `"\!important!.txt"`. + .replace(REGEX_LEADING_EXCAPED_EXCLAMATION, '!') + // > Put a backslash ("\") in front of the first hash for patterns that + // > begin with a hash. + .replace(REGEX_LEADING_EXCAPED_HASH, '#') - var m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) + const regex = make_regex(pattern, negative, ignorecase) - if (!m) { - throw new TypeError('Invalid Version: ' + version) + return { + origin, + pattern, + negative, + regex } +} - this.raw = version - - // these are actually numbers - this.major = +m[1] - this.minor = +m[2] - this.patch = +m[3] - - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError('Invalid major version') +class IgnoreBase { + constructor ({ + ignorecase = true + } = {}) { + this._rules = [] + this._ignorecase = ignorecase + define(this, KEY_IGNORE, true) + this._initCache() } - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError('Invalid minor version') + _initCache () { + this._cache = Object.create(null) } - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError('Invalid patch version') - } + // @param {Array.|string|Ignore} pattern + add (pattern) { + this._added = false - // numberify any prerelease numeric ids - if (!m[4]) { - this.prerelease = [] - } else { - this.prerelease = m[4].split('.').map(function (id) { - if (/^[0-9]+$/.test(id)) { - var num = +id - if (num >= 0 && num < MAX_SAFE_INTEGER) { - return num - } - } - return id - }) - } + if (typeof pattern === 'string') { + pattern = pattern.split(/\r?\n/g) + } - this.build = m[5] ? m[5].split('.') : [] - this.format() -} + make_array(pattern).forEach(this._addPattern, this) -SemVer.prototype.format = function () { - this.version = this.major + '.' + this.minor + '.' + this.patch - if (this.prerelease.length) { - this.version += '-' + this.prerelease.join('.') - } - return this.version -} + // Some rules have just added to the ignore, + // making the behavior changed. + if (this._added) { + this._initCache() + } -SemVer.prototype.toString = function () { - return this.version -} + return this + } -SemVer.prototype.compare = function (other) { - debug('SemVer.compare', this.version, this.options, other) - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) + // legacy + addPattern (pattern) { + return this.add(pattern) } - return this.compareMain(other) || this.comparePre(other) -} + _addPattern (pattern) { + // #32 + if (pattern && pattern[KEY_IGNORE]) { + this._rules = this._rules.concat(pattern._rules) + this._added = true + return + } -SemVer.prototype.compareMain = function (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) + if (checkPattern(pattern)) { + const rule = createRule(pattern, this._ignorecase) + this._added = true + this._rules.push(rule) + } } - return compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch) -} + filter (paths) { + return make_array(paths).filter(path => this._filter(path)) + } -SemVer.prototype.comparePre = function (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) + createFilter () { + return path => this._filter(path) } - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) { - return -1 - } else if (!this.prerelease.length && other.prerelease.length) { - return 1 - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0 + ignores (path) { + return !this._filter(path) } - var i = 0 - do { - var a = this.prerelease[i] - var b = other.prerelease[i] - debug('prerelease compare', i, a, b) - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) + // @returns `Boolean` true if the `path` is NOT ignored + _filter (path, slices) { + if (!path) { + return false } - } while (++i) -} -SemVer.prototype.compareBuild = function (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } + if (path in this._cache) { + return this._cache[path] + } - var i = 0 - do { - var a = this.build[i] - var b = other.build[i] - debug('prerelease compare', i, a, b) - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) + if (!slices) { + // path/to/a.js + // ['path', 'to', 'a.js'] + slices = path.split(SLASH) } - } while (++i) -} -// preminor will bump the version up to the next minor release, and immediately -// down to pre-release. premajor and prepatch work the same way. -SemVer.prototype.inc = function (release, identifier) { - switch (release) { - case 'premajor': - this.prerelease.length = 0 - this.patch = 0 - this.minor = 0 - this.major++ - this.inc('pre', identifier) - break - case 'preminor': - this.prerelease.length = 0 - this.patch = 0 - this.minor++ - this.inc('pre', identifier) - break - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0 - this.inc('patch', identifier) - this.inc('pre', identifier) - break - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) { - this.inc('patch', identifier) - } - this.inc('pre', identifier) - break + slices.pop() - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if (this.minor !== 0 || - this.patch !== 0 || - this.prerelease.length === 0) { - this.major++ - } - this.minor = 0 - this.patch = 0 - this.prerelease = [] - break - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++ - } - this.patch = 0 - this.prerelease = [] - break - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) { - this.patch++ - } - this.prerelease = [] - break - // This probably shouldn't be used publicly. - // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. - case 'pre': - if (this.prerelease.length === 0) { - this.prerelease = [0] - } else { - var i = this.prerelease.length - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++ - i = -2 - } - } - if (i === -1) { - // didn't increment anything - this.prerelease.push(0) - } - } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) { - this.prerelease = [identifier, 0] - } - } else { - this.prerelease = [identifier, 0] - } - } - break + return this._cache[path] = slices.length + // > It is not possible to re-include a file if a parent directory of + // > that file is excluded. + // If the path contains a parent directory, check the parent first + ? this._filter(slices.join(SLASH) + SLASH, slices) + && this._test(path) - default: - throw new Error('invalid increment argument: ' + release) + // Or only test the path + : this._test(path) } - this.format() - this.raw = this.version - return this -} -exports.inc = inc -function inc (version, release, loose, identifier) { - if (typeof (loose) === 'string') { - identifier = loose - loose = undefined - } + // @returns {Boolean} true if a file is NOT ignored + _test (path) { + // Explicitly define variable type by setting matched to `0` + let matched = 0 - try { - return new SemVer(version, loose).inc(release, identifier).version - } catch (er) { - return null + this._rules.forEach(rule => { + // if matched = true, then we only test negative rules + // if matched = false, then we test non-negative rules + if (!(matched ^ rule.negative)) { + matched = rule.negative ^ rule.regex.test(path) + } + }) + + return !matched } } -exports.diff = diff -function diff (version1, version2) { - if (eq(version1, version2)) { - return null - } else { - var v1 = parse(version1) - var v2 = parse(version2) - var prefix = '' - if (v1.prerelease.length || v2.prerelease.length) { - prefix = 'pre' - var defaultResult = 'prerelease' - } - for (var key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return prefix + key - } - } - } - return defaultResult // may be undefined +// Windows +// -------------------------------------------------------------- +/* istanbul ignore if */ +if ( + // Detect `process` so that it can run in browsers. + typeof process !== 'undefined' + && ( + process.env && process.env.IGNORE_TEST_WIN32 + || process.platform === 'win32' + ) +) { + const filter = IgnoreBase.prototype._filter + + /* eslint no-control-regex: "off" */ + const make_posix = str => /^\\\\\?\\/.test(str) + || /[^\x00-\x80]+/.test(str) + ? str + : str.replace(/\\/g, '/') + + IgnoreBase.prototype._filter = function filterWin32 (path, slices) { + path = make_posix(path) + return filter.call(this, path, slices) } } -exports.compareIdentifiers = compareIdentifiers +module.exports = options => new IgnoreBase(options) -var numeric = /^[0-9]+$/ -function compareIdentifiers (a, b) { - var anum = numeric.test(a) - var bnum = numeric.test(b) - if (anum && bnum) { - a = +a - b = +b - } +/***/ }), +/* 826 */ +/***/ (function(module, exports, __webpack_require__) { - return a === b ? 0 - : (anum && !bnum) ? -1 - : (bnum && !anum) ? 1 - : a < b ? -1 - : 1 -} +"use strict"; -exports.rcompareIdentifiers = rcompareIdentifiers -function rcompareIdentifiers (a, b) { - return compareIdentifiers(b, a) -} +module.exports = input => { + const isExtendedLengthPath = /^\\\\\?\\/.test(input); + const hasNonAscii = /[^\u0000-\u0080]+/.test(input); // eslint-disable-line no-control-regex -exports.major = major -function major (a, loose) { - return new SemVer(a, loose).major -} + if (isExtendedLengthPath || hasNonAscii) { + return input; + } -exports.minor = minor -function minor (a, loose) { - return new SemVer(a, loose).minor -} + return input.replace(/\\/g, '/'); +}; -exports.patch = patch -function patch (a, loose) { - return new SemVer(a, loose).patch -} -exports.compare = compare -function compare (a, b, loose) { - return new SemVer(a, loose).compare(new SemVer(b, loose)) -} +/***/ }), +/* 827 */ +/***/ (function(module, exports, __webpack_require__) { -exports.compareLoose = compareLoose -function compareLoose (a, b) { - return compare(a, b, true) -} +"use strict"; +/*! + * has-glob + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ -exports.compareBuild = compareBuild -function compareBuild (a, b, loose) { - var versionA = new SemVer(a, loose) - var versionB = new SemVer(b, loose) - return versionA.compare(versionB) || versionA.compareBuild(versionB) -} -exports.rcompare = rcompare -function rcompare (a, b, loose) { - return compare(b, a, loose) -} -exports.sort = sort -function sort (list, loose) { - return list.sort(function (a, b) { - return exports.compareBuild(a, b, loose) - }) -} +var isGlob = __webpack_require__(828); -exports.rsort = rsort -function rsort (list, loose) { - return list.sort(function (a, b) { - return exports.compareBuild(b, a, loose) - }) -} +module.exports = function hasGlob(val) { + if (val == null) return false; + if (typeof val === 'string') { + return isGlob(val); + } + if (Array.isArray(val)) { + var len = val.length; + while (len--) { + if (isGlob(val[len])) { + return true; + } + } + } + return false; +}; -exports.gt = gt -function gt (a, b, loose) { - return compare(a, b, loose) > 0 -} -exports.lt = lt -function lt (a, b, loose) { - return compare(a, b, loose) < 0 -} +/***/ }), +/* 828 */ +/***/ (function(module, exports, __webpack_require__) { -exports.eq = eq -function eq (a, b, loose) { - return compare(a, b, loose) === 0 -} +/*! + * is-glob + * + * Copyright (c) 2014-2016, Jon Schlinkert. + * Licensed under the MIT License. + */ -exports.neq = neq -function neq (a, b, loose) { - return compare(a, b, loose) !== 0 -} +var isExtglob = __webpack_require__(388); -exports.gte = gte -function gte (a, b, loose) { - return compare(a, b, loose) >= 0 -} +module.exports = function isGlob(str) { + if (typeof str !== 'string' || str === '') { + return false; + } -exports.lte = lte -function lte (a, b, loose) { - return compare(a, b, loose) <= 0 -} + if (isExtglob(str)) return true; -exports.cmp = cmp -function cmp (a, op, b, loose) { - switch (op) { - case '===': - if (typeof a === 'object') - a = a.version - if (typeof b === 'object') - b = b.version - return a === b + var regex = /(\\).|([*?]|\[.*\]|\{.*\}|\(.*\|.*\)|^!)/; + var match; - case '!==': - if (typeof a === 'object') - a = a.version - if (typeof b === 'object') - b = b.version - return a !== b + while ((match = regex.exec(str))) { + if (match[2]) return true; + str = str.slice(match.index + match[0].length); + } + return false; +}; - case '': - case '=': - case '==': - return eq(a, b, loose) - case '!=': - return neq(a, b, loose) +/***/ }), +/* 829 */ +/***/ (function(module, exports, __webpack_require__) { - case '>': - return gt(a, b, loose) +"use strict"; - case '>=': - return gte(a, b, loose) +const path = __webpack_require__(4); +const {constants: fsConstants} = __webpack_require__(253); +const pEvent = __webpack_require__(830); +const CpFileError = __webpack_require__(833); +const fs = __webpack_require__(835); +const ProgressEmitter = __webpack_require__(838); - case '<': - return lt(a, b, loose) +const cpFileAsync = async (source, destination, options, progressEmitter) => { + let readError; + const stat = await fs.stat(source); + progressEmitter.size = stat.size; - case '<=': - return lte(a, b, loose) + const read = await fs.createReadStream(source); + await fs.makeDir(path.dirname(destination)); + const write = fs.createWriteStream(destination, {flags: options.overwrite ? 'w' : 'wx'}); + read.on('data', () => { + progressEmitter.written = write.bytesWritten; + }); + read.once('error', error => { + readError = new CpFileError(`Cannot read from \`${source}\`: ${error.message}`, error); + write.end(); + }); - default: - throw new TypeError('Invalid operator: ' + op) - } -} + let updateStats = false; + try { + const writePromise = pEvent(write, 'close'); + read.pipe(write); + await writePromise; + progressEmitter.written = progressEmitter.size; + updateStats = true; + } catch (error) { + if (options.overwrite || error.code !== 'EEXIST') { + throw new CpFileError(`Cannot write to \`${destination}\`: ${error.message}`, error); + } + } -exports.Comparator = Comparator -function Comparator (comp, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } + if (readError) { + throw readError; + } - if (comp instanceof Comparator) { - if (comp.loose === !!options.loose) { - return comp - } else { - comp = comp.value - } - } + if (updateStats) { + const stats = await fs.lstat(source); + + return Promise.all([ + fs.utimes(destination, stats.atime, stats.mtime), + fs.chmod(destination, stats.mode), + fs.chown(destination, stats.uid, stats.gid) + ]); + } +}; + +const cpFile = (source, destination, options) => { + if (!source || !destination) { + return Promise.reject(new CpFileError('`source` and `destination` required')); + } + + options = { + overwrite: true, + ...options + }; + + const progressEmitter = new ProgressEmitter(path.resolve(source), path.resolve(destination)); + const promise = cpFileAsync(source, destination, options, progressEmitter); + promise.on = (...args) => { + progressEmitter.on(...args); + return promise; + }; - if (!(this instanceof Comparator)) { - return new Comparator(comp, options) - } + return promise; +}; - debug('comparator', comp, options) - this.options = options - this.loose = !!options.loose - this.parse(comp) +module.exports = cpFile; - if (this.semver === ANY) { - this.value = '' - } else { - this.value = this.operator + this.semver.version - } +const checkSourceIsFile = (stat, source) => { + if (stat.isDirectory()) { + throw Object.assign(new CpFileError(`EISDIR: illegal operation on a directory '${source}'`), { + errno: -21, + code: 'EISDIR', + source + }); + } +}; - debug('comp', this) -} +const fixupAttributes = (destination, stat) => { + fs.chmodSync(destination, stat.mode); + fs.chownSync(destination, stat.uid, stat.gid); +}; -var ANY = {} -Comparator.prototype.parse = function (comp) { - var r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] - var m = comp.match(r) +module.exports.sync = (source, destination, options) => { + if (!source || !destination) { + throw new CpFileError('`source` and `destination` required'); + } - if (!m) { - throw new TypeError('Invalid comparator: ' + comp) - } + options = { + overwrite: true, + ...options + }; - this.operator = m[1] !== undefined ? m[1] : '' - if (this.operator === '=') { - this.operator = '' - } + const stat = fs.statSync(source); + checkSourceIsFile(stat, source); + fs.makeDirSync(path.dirname(destination)); - // if it literally is just '>' or '' then allow anything. - if (!m[2]) { - this.semver = ANY - } else { - this.semver = new SemVer(m[2], this.options.loose) - } -} + const flags = options.overwrite ? null : fsConstants.COPYFILE_EXCL; + try { + fs.copyFileSync(source, destination, flags); + } catch (error) { + if (!options.overwrite && error.code === 'EEXIST') { + return; + } -Comparator.prototype.toString = function () { - return this.value -} + throw error; + } -Comparator.prototype.test = function (version) { - debug('Comparator.test', version, this.options.loose) + fs.utimesSync(destination, stat.atime, stat.mtime); + fixupAttributes(destination, stat); +}; - if (this.semver === ANY || version === ANY) { - return true - } - if (typeof version === 'string') { - try { - version = new SemVer(version, this.options) - } catch (er) { - return false - } - } +/***/ }), +/* 830 */ +/***/ (function(module, exports, __webpack_require__) { - return cmp(version, this.operator, this.semver, this.options) -} +"use strict"; -Comparator.prototype.intersects = function (comp, options) { - if (!(comp instanceof Comparator)) { - throw new TypeError('a Comparator is required') - } +const pTimeout = __webpack_require__(831); - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } +const symbolAsyncIterator = Symbol.asyncIterator || '@@asyncIterator'; - var rangeTmp +const normalizeEmitter = emitter => { + const addListener = emitter.on || emitter.addListener || emitter.addEventListener; + const removeListener = emitter.off || emitter.removeListener || emitter.removeEventListener; - if (this.operator === '') { - if (this.value === '') { - return true - } - rangeTmp = new Range(comp.value, options) - return satisfies(this.value, rangeTmp, options) - } else if (comp.operator === '') { - if (comp.value === '') { - return true - } - rangeTmp = new Range(this.value, options) - return satisfies(comp.semver, rangeTmp, options) - } + if (!addListener || !removeListener) { + throw new TypeError('Emitter is not compatible'); + } - var sameDirectionIncreasing = - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '>=' || comp.operator === '>') - var sameDirectionDecreasing = - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '<=' || comp.operator === '<') - var sameSemVer = this.semver.version === comp.semver.version - var differentDirectionsInclusive = - (this.operator === '>=' || this.operator === '<=') && - (comp.operator === '>=' || comp.operator === '<=') - var oppositeDirectionsLessThan = - cmp(this.semver, '<', comp.semver, options) && - ((this.operator === '>=' || this.operator === '>') && - (comp.operator === '<=' || comp.operator === '<')) - var oppositeDirectionsGreaterThan = - cmp(this.semver, '>', comp.semver, options) && - ((this.operator === '<=' || this.operator === '<') && - (comp.operator === '>=' || comp.operator === '>')) + return { + addListener: addListener.bind(emitter), + removeListener: removeListener.bind(emitter) + }; +}; - return sameDirectionIncreasing || sameDirectionDecreasing || - (sameSemVer && differentDirectionsInclusive) || - oppositeDirectionsLessThan || oppositeDirectionsGreaterThan -} +const normalizeEvents = event => Array.isArray(event) ? event : [event]; -exports.Range = Range -function Range (range, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } +const multiple = (emitter, event, options) => { + let cancel; + const ret = new Promise((resolve, reject) => { + options = { + rejectionEvents: ['error'], + multiArgs: false, + resolveImmediately: false, + ...options + }; - if (range instanceof Range) { - if (range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease) { - return range - } else { - return new Range(range.raw, options) - } - } + if (!(options.count >= 0 && (options.count === Infinity || Number.isInteger(options.count)))) { + throw new TypeError('The `count` option should be at least 0 or more'); + } - if (range instanceof Comparator) { - return new Range(range.value, options) - } + // Allow multiple events + const events = normalizeEvents(event); - if (!(this instanceof Range)) { - return new Range(range, options) - } + const items = []; + const {addListener, removeListener} = normalizeEmitter(emitter); - this.options = options - this.loose = !!options.loose - this.includePrerelease = !!options.includePrerelease + const onItem = (...args) => { + const value = options.multiArgs ? args : args[0]; - // First, split based on boolean or || - this.raw = range - this.set = range.split(/\s*\|\|\s*/).map(function (range) { - return this.parseRange(range.trim()) - }, this).filter(function (c) { - // throw out any that are not relevant for whatever reason - return c.length - }) + if (options.filter && !options.filter(value)) { + return; + } - if (!this.set.length) { - throw new TypeError('Invalid SemVer Range: ' + range) - } + items.push(value); - this.format() -} + if (options.count === items.length) { + cancel(); + resolve(items); + } + }; -Range.prototype.format = function () { - this.range = this.set.map(function (comps) { - return comps.join(' ').trim() - }).join('||').trim() - return this.range -} + const rejectHandler = error => { + cancel(); + reject(error); + }; -Range.prototype.toString = function () { - return this.range -} + cancel = () => { + for (const event of events) { + removeListener(event, onItem); + } -Range.prototype.parseRange = function (range) { - var loose = this.options.loose - range = range.trim() - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - var hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] - range = range.replace(hr, hyphenReplace) - debug('hyphen replace', range) - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) - debug('comparator trim', range, re[t.COMPARATORTRIM]) + for (const rejectionEvent of options.rejectionEvents) { + removeListener(rejectionEvent, rejectHandler); + } + }; - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re[t.TILDETRIM], tildeTrimReplace) + for (const event of events) { + addListener(event, onItem); + } - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re[t.CARETTRIM], caretTrimReplace) + for (const rejectionEvent of options.rejectionEvents) { + addListener(rejectionEvent, rejectHandler); + } - // normalize spaces - range = range.split(/\s+/).join(' ') + if (options.resolveImmediately) { + resolve(items); + } + }); - // At this point, the range is completely trimmed and - // ready to be split into comparators. + ret.cancel = cancel; - var compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] - var set = range.split(' ').map(function (comp) { - return parseComparator(comp, this.options) - }, this).join(' ').split(/\s+/) - if (this.options.loose) { - // in loose mode, throw out any that are not valid comparators - set = set.filter(function (comp) { - return !!comp.match(compRe) - }) - } - set = set.map(function (comp) { - return new Comparator(comp, this.options) - }, this) + if (typeof options.timeout === 'number') { + const timeout = pTimeout(ret, options.timeout); + timeout.cancel = cancel; + return timeout; + } - return set -} + return ret; +}; -Range.prototype.intersects = function (range, options) { - if (!(range instanceof Range)) { - throw new TypeError('a Range is required') - } +const pEvent = (emitter, event, options) => { + if (typeof options === 'function') { + options = {filter: options}; + } - return this.set.some(function (thisComparators) { - return ( - isSatisfiable(thisComparators, options) && - range.set.some(function (rangeComparators) { - return ( - isSatisfiable(rangeComparators, options) && - thisComparators.every(function (thisComparator) { - return rangeComparators.every(function (rangeComparator) { - return thisComparator.intersects(rangeComparator, options) - }) - }) - ) - }) - ) - }) -} + options = { + ...options, + count: 1, + resolveImmediately: false + }; -// take a set of comparators and determine whether there -// exists a version which can satisfy it -function isSatisfiable (comparators, options) { - var result = true - var remainingComparators = comparators.slice() - var testComparator = remainingComparators.pop() + const arrayPromise = multiple(emitter, event, options); + const promise = arrayPromise.then(array => array[0]); // eslint-disable-line promise/prefer-await-to-then + promise.cancel = arrayPromise.cancel; - while (result && remainingComparators.length) { - result = remainingComparators.every(function (otherComparator) { - return testComparator.intersects(otherComparator, options) - }) + return promise; +}; - testComparator = remainingComparators.pop() - } +module.exports = pEvent; +// TODO: Remove this for the next major release +module.exports.default = pEvent; - return result -} +module.exports.multiple = multiple; -// Mostly just for testing and legacy API reasons -exports.toComparators = toComparators -function toComparators (range, options) { - return new Range(range, options).set.map(function (comp) { - return comp.map(function (c) { - return c.value - }).join(' ').trim().split(' ') - }) -} +module.exports.iterator = (emitter, event, options) => { + if (typeof options === 'function') { + options = {filter: options}; + } -// comprised of xranges, tildes, stars, and gtlt's at this point. -// already replaced the hyphen ranges -// turn into a set of JUST comparators. -function parseComparator (comp, options) { - debug('comp', comp, options) - comp = replaceCarets(comp, options) - debug('caret', comp) - comp = replaceTildes(comp, options) - debug('tildes', comp) - comp = replaceXRanges(comp, options) - debug('xrange', comp) - comp = replaceStars(comp, options) - debug('stars', comp) - return comp -} + // Allow multiple events + const events = normalizeEvents(event); -function isX (id) { - return !id || id.toLowerCase() === 'x' || id === '*' -} + options = { + rejectionEvents: ['error'], + resolutionEvents: [], + limit: Infinity, + multiArgs: false, + ...options + }; -// ~, ~> --> * (any, kinda silly) -// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 -// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 -// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 -// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 -// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 -function replaceTildes (comp, options) { - return comp.trim().split(/\s+/).map(function (comp) { - return replaceTilde(comp, options) - }).join(' ') -} + const {limit} = options; + const isValidLimit = limit >= 0 && (limit === Infinity || Number.isInteger(limit)); + if (!isValidLimit) { + throw new TypeError('The `limit` option should be a non-negative integer or Infinity'); + } -function replaceTilde (comp, options) { - var r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] - return comp.replace(r, function (_, M, m, p, pr) { - debug('tilde', comp, _, M, m, p, pr) - var ret + if (limit === 0) { + // Return an empty async iterator to avoid any further cost + return { + [Symbol.asyncIterator]() { + return this; + }, + async next() { + return { + done: true, + value: undefined + }; + } + }; + } - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (isX(p)) { - // ~1.2 == >=1.2.0 <1.3.0 - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } else if (pr) { - debug('replaceTilde pr', pr) - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + (+m + 1) + '.0' - } else { - // ~1.2.3 == >=1.2.3 <1.3.0 - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0' - } + const {addListener, removeListener} = normalizeEmitter(emitter); - debug('tilde return', ret) - return ret - }) -} + let isDone = false; + let error; + let hasPendingError = false; + const nextQueue = []; + const valueQueue = []; + let eventCount = 0; + let isLimitReached = false; -// ^ --> * (any, kinda silly) -// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 -// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 -// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 -// ^1.2.3 --> >=1.2.3 <2.0.0 -// ^1.2.0 --> >=1.2.0 <2.0.0 -function replaceCarets (comp, options) { - return comp.trim().split(/\s+/).map(function (comp) { - return replaceCaret(comp, options) - }).join(' ') -} + const valueHandler = (...args) => { + eventCount++; + isLimitReached = eventCount === limit; -function replaceCaret (comp, options) { - debug('caret', comp, options) - var r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] - return comp.replace(r, function (_, M, m, p, pr) { - debug('caret', comp, _, M, m, p, pr) - var ret + const value = options.multiArgs ? args : args[0]; - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (isX(p)) { - if (M === '0') { - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } else { - ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' - } - } else if (pr) { - debug('replaceCaret pr', pr) - if (M === '0') { - if (m === '0') { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + m + '.' + (+p + 1) - } else { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + (+m + 1) + '.0' - } - } else { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + (+M + 1) + '.0.0' - } - } else { - debug('no pr') - if (M === '0') { - if (m === '0') { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + m + '.' + (+p + 1) - } else { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0' - } - } else { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + (+M + 1) + '.0.0' - } - } + if (nextQueue.length > 0) { + const {resolve} = nextQueue.shift(); + + resolve({done: false, value}); - debug('caret return', ret) - return ret - }) -} + if (isLimitReached) { + cancel(); + } -function replaceXRanges (comp, options) { - debug('replaceXRanges', comp, options) - return comp.split(/\s+/).map(function (comp) { - return replaceXRange(comp, options) - }).join(' ') -} + return; + } -function replaceXRange (comp, options) { - comp = comp.trim() - var r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] - return comp.replace(r, function (ret, gtlt, M, m, p, pr) { - debug('xRange', comp, ret, gtlt, M, m, p, pr) - var xM = isX(M) - var xm = xM || isX(m) - var xp = xm || isX(p) - var anyX = xp + valueQueue.push(value); - if (gtlt === '=' && anyX) { - gtlt = '' - } + if (isLimitReached) { + cancel(); + } + }; - // if we're including prereleases in the match, then we need - // to fix this to -0, the lowest possible prerelease value - pr = options.includePrerelease ? '-0' : '' + const cancel = () => { + isDone = true; + for (const event of events) { + removeListener(event, valueHandler); + } - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0-0' - } else { - // nothing is forbidden - ret = '*' - } - } else if (gtlt && anyX) { - // we know patch is an x, because we have any x at all. - // replace X with 0 - if (xm) { - m = 0 - } - p = 0 + for (const rejectionEvent of options.rejectionEvents) { + removeListener(rejectionEvent, rejectHandler); + } - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - // >1.2.3 => >= 1.2.4 - gtlt = '>=' - if (xm) { - M = +M + 1 - m = 0 - p = 0 - } else { - m = +m + 1 - p = 0 - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<' - if (xm) { - M = +M + 1 - } else { - m = +m + 1 - } - } + for (const resolutionEvent of options.resolutionEvents) { + removeListener(resolutionEvent, resolveHandler); + } - ret = gtlt + M + '.' + m + '.' + p + pr - } else if (xm) { - ret = '>=' + M + '.0.0' + pr + ' <' + (+M + 1) + '.0.0' + pr - } else if (xp) { - ret = '>=' + M + '.' + m + '.0' + pr + - ' <' + M + '.' + (+m + 1) + '.0' + pr - } + while (nextQueue.length > 0) { + const {resolve} = nextQueue.shift(); + resolve({done: true, value: undefined}); + } + }; - debug('xRange return', ret) + const rejectHandler = (...args) => { + error = options.multiArgs ? args : args[0]; - return ret - }) -} + if (nextQueue.length > 0) { + const {reject} = nextQueue.shift(); + reject(error); + } else { + hasPendingError = true; + } -// Because * is AND-ed with everything else in the comparator, -// and '' means "any version", just remove the *s entirely. -function replaceStars (comp, options) { - debug('replaceStars', comp, options) - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re[t.STAR], '') -} + cancel(); + }; -// This function is passed to string.replace(re[t.HYPHENRANGE]) -// M, m, patch, prerelease, build -// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 -// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do -// 1.2 - 3.4 => >=1.2.0 <3.5.0 -function hyphenReplace ($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) { - if (isX(fM)) { - from = '' - } else if (isX(fm)) { - from = '>=' + fM + '.0.0' - } else if (isX(fp)) { - from = '>=' + fM + '.' + fm + '.0' - } else { - from = '>=' + from - } + const resolveHandler = (...args) => { + const value = options.multiArgs ? args : args[0]; - if (isX(tM)) { - to = '' - } else if (isX(tm)) { - to = '<' + (+tM + 1) + '.0.0' - } else if (isX(tp)) { - to = '<' + tM + '.' + (+tm + 1) + '.0' - } else if (tpr) { - to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr - } else { - to = '<=' + to - } + if (options.filter && !options.filter(value)) { + return; + } - return (from + ' ' + to).trim() -} + if (nextQueue.length > 0) { + const {resolve} = nextQueue.shift(); + resolve({done: true, value}); + } else { + valueQueue.push(value); + } -// if ANY of the sets match ALL of its comparators, then pass -Range.prototype.test = function (version) { - if (!version) { - return false - } + cancel(); + }; - if (typeof version === 'string') { - try { - version = new SemVer(version, this.options) - } catch (er) { - return false - } - } + for (const event of events) { + addListener(event, valueHandler); + } - for (var i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { - return true - } - } - return false -} + for (const rejectionEvent of options.rejectionEvents) { + addListener(rejectionEvent, rejectHandler); + } -function testSet (set, version, options) { - for (var i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false - } - } + for (const resolutionEvent of options.resolutionEvents) { + addListener(resolutionEvent, resolveHandler); + } - if (version.prerelease.length && !options.includePrerelease) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (i = 0; i < set.length; i++) { - debug(set[i].semver) - if (set[i].semver === ANY) { - continue - } + return { + [symbolAsyncIterator]() { + return this; + }, + async next() { + if (valueQueue.length > 0) { + const value = valueQueue.shift(); + return { + done: isDone && valueQueue.length === 0 && !isLimitReached, + value + }; + } - if (set[i].semver.prerelease.length > 0) { - var allowed = set[i].semver - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) { - return true - } - } - } + if (hasPendingError) { + hasPendingError = false; + throw error; + } - // Version has a -pre, but it's not one of the ones we like. - return false - } + if (isDone) { + return { + done: true, + value: undefined + }; + } - return true -} + return new Promise((resolve, reject) => nextQueue.push({resolve, reject})); + }, + async return(value) { + cancel(); + return { + done: isDone, + value + }; + } + }; +}; -exports.satisfies = satisfies -function satisfies (version, range, options) { - try { - range = new Range(range, options) - } catch (er) { - return false - } - return range.test(version) -} -exports.maxSatisfying = maxSatisfying -function maxSatisfying (versions, range, options) { - var max = null - var maxSV = null - try { - var rangeObj = new Range(range, options) - } catch (er) { - return null - } - versions.forEach(function (v) { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!max || maxSV.compare(v) === -1) { - // compare(max, v, true) - max = v - maxSV = new SemVer(max, options) - } - } - }) - return max -} +/***/ }), +/* 831 */ +/***/ (function(module, exports, __webpack_require__) { -exports.minSatisfying = minSatisfying -function minSatisfying (versions, range, options) { - var min = null - var minSV = null - try { - var rangeObj = new Range(range, options) - } catch (er) { - return null - } - versions.forEach(function (v) { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!min || minSV.compare(v) === 1) { - // compare(min, v, true) - min = v - minSV = new SemVer(min, options) - } - } - }) - return min +"use strict"; + +const pFinally = __webpack_require__(832); + +class TimeoutError extends Error { + constructor(message) { + super(message); + this.name = 'TimeoutError'; + } } -exports.minVersion = minVersion -function minVersion (range, loose) { - range = new Range(range, loose) +module.exports = (promise, ms, fallback) => new Promise((resolve, reject) => { + if (typeof ms !== 'number' || ms < 0) { + throw new TypeError('Expected `ms` to be a positive number'); + } - var minver = new SemVer('0.0.0') - if (range.test(minver)) { - return minver - } + const timer = setTimeout(() => { + if (typeof fallback === 'function') { + try { + resolve(fallback()); + } catch (err) { + reject(err); + } + return; + } - minver = new SemVer('0.0.0-0') - if (range.test(minver)) { - return minver - } + const message = typeof fallback === 'string' ? fallback : `Promise timed out after ${ms} milliseconds`; + const err = fallback instanceof Error ? fallback : new TimeoutError(message); - minver = null - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i] + if (typeof promise.cancel === 'function') { + promise.cancel(); + } - comparators.forEach(function (comparator) { - // Clone to avoid manipulating the comparator's semver object. - var compver = new SemVer(comparator.semver.version) - switch (comparator.operator) { - case '>': - if (compver.prerelease.length === 0) { - compver.patch++ - } else { - compver.prerelease.push(0) - } - compver.raw = compver.format() - /* fallthrough */ - case '': - case '>=': - if (!minver || gt(minver, compver)) { - minver = compver - } - break - case '<': - case '<=': - /* Ignore maximum versions */ - break - /* istanbul ignore next */ - default: - throw new Error('Unexpected operation: ' + comparator.operator) - } - }) - } + reject(err); + }, ms); - if (minver && range.test(minver)) { - return minver - } + pFinally( + promise.then(resolve, reject), + () => { + clearTimeout(timer); + } + ); +}); - return null -} +module.exports.TimeoutError = TimeoutError; -exports.validRange = validRange -function validRange (range, options) { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range(range, options).range || '*' - } catch (er) { - return null - } -} -// Determine if version is less than all the versions possible in the range -exports.ltr = ltr -function ltr (version, range, options) { - return outside(version, range, '<', options) -} +/***/ }), +/* 832 */ +/***/ (function(module, exports, __webpack_require__) { -// Determine if version is greater than all the versions possible in the range. -exports.gtr = gtr -function gtr (version, range, options) { - return outside(version, range, '>', options) +"use strict"; + +module.exports = (promise, onFinally) => { + onFinally = onFinally || (() => {}); + + return promise.then( + val => new Promise(resolve => { + resolve(onFinally()); + }).then(() => val), + err => new Promise(resolve => { + resolve(onFinally()); + }).then(() => { + throw err; + }) + ); +}; + + +/***/ }), +/* 833 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +const NestedError = __webpack_require__(834); + +class CpFileError extends NestedError { + constructor(message, nested) { + super(message, nested); + Object.assign(this, nested); + this.name = 'CpFileError'; + } } -exports.outside = outside -function outside (version, range, hilo, options) { - version = new SemVer(version, options) - range = new Range(range, options) +module.exports = CpFileError; - var gtfn, ltefn, ltfn, comp, ecomp - switch (hilo) { - case '>': - gtfn = gt - ltefn = lte - ltfn = lt - comp = '>' - ecomp = '>=' - break - case '<': - gtfn = lt - ltefn = gte - ltfn = gt - comp = '<' - ecomp = '<=' - break - default: - throw new TypeError('Must provide a hilo val of "<" or ">"') - } - // If it satisifes the range it is not outside - if (satisfies(version, range, options)) { - return false - } +/***/ }), +/* 834 */ +/***/ (function(module, exports, __webpack_require__) { - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. +var inherits = __webpack_require__(234).inherits; - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i] +var NestedError = function (message, nested) { + this.nested = nested; - var high = null - var low = null + if (message instanceof Error) { + nested = message; + } else if (typeof message !== 'undefined') { + Object.defineProperty(this, 'message', { + value: message, + writable: true, + enumerable: false, + configurable: true + }); + } - comparators.forEach(function (comparator) { - if (comparator.semver === ANY) { - comparator = new Comparator('>=0.0.0') - } - high = high || comparator - low = low || comparator - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator - } - }) + Error.captureStackTrace(this, this.constructor); + var oldStackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack'); + var stackDescriptor = buildStackDescriptor(oldStackDescriptor, nested); + Object.defineProperty(this, 'stack', stackDescriptor); +}; - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false +function buildStackDescriptor(oldStackDescriptor, nested) { + if (oldStackDescriptor.get) { + return { + get: function () { + var stack = oldStackDescriptor.get.call(this); + return buildCombinedStacks(stack, this.nested); + } + }; + } else { + var stack = oldStackDescriptor.value; + return { + value: buildCombinedStacks(stack, nested) + }; } +} - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false +function buildCombinedStacks(stack, nested) { + if (nested) { + stack += '\nCaused By: ' + nested.stack; } - } - return true + return stack; } -exports.prerelease = prerelease -function prerelease (version, options) { - var parsed = parse(version, options) - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null -} +inherits(NestedError, Error); +NestedError.prototype.name = 'NestedError'; -exports.intersects = intersects -function intersects (r1, r2, options) { - r1 = new Range(r1, options) - r2 = new Range(r2, options) - return r1.intersects(r2) -} -exports.coerce = coerce -function coerce (version, options) { - if (version instanceof SemVer) { - return version - } +module.exports = NestedError; - if (typeof version === 'number') { - version = String(version) - } - if (typeof version !== 'string') { - return null - } +/***/ }), +/* 835 */ +/***/ (function(module, exports, __webpack_require__) { - options = options || {} +"use strict"; - var match = null - if (!options.rtl) { - match = version.match(re[t.COERCE]) - } else { - // Find the right-most coercible string that does not share - // a terminus with a more left-ward coercible string. - // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' - // - // Walk through the string checking with a /g regexp - // Manually set the index so as to pick up overlapping matches. - // Stop when we get a match that ends at the string end, since no - // coercible string can be more right-ward without the same terminus. - var next - while ((next = re[t.COERCERTL].exec(version)) && - (!match || match.index + match[0].length !== version.length) - ) { - if (!match || - next.index + next[0].length !== match.index + match[0].length) { - match = next - } - re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length - } - // leave it in a clean state - re[t.COERCERTL].lastIndex = -1 - } +const {promisify} = __webpack_require__(234); +const fs = __webpack_require__(354); +const makeDir = __webpack_require__(836); +const pEvent = __webpack_require__(830); +const CpFileError = __webpack_require__(833); - if (match === null) { - return null - } +const stat = promisify(fs.stat); +const lstat = promisify(fs.lstat); +const utimes = promisify(fs.utimes); +const chmod = promisify(fs.chmod); +const chown = promisify(fs.chown); - return parse(match[2] + - '.' + (match[3] || '0') + - '.' + (match[4] || '0'), options) -} +exports.closeSync = fs.closeSync.bind(fs); +exports.createWriteStream = fs.createWriteStream.bind(fs); +exports.createReadStream = async (path, options) => { + const read = fs.createReadStream(path, options); -/***/ }), -/* 800 */ -/***/ (function(module, exports, __webpack_require__) { + try { + await pEvent(read, ['readable', 'end']); + } catch (error) { + throw new CpFileError(`Cannot read from \`${path}\`: ${error.message}`, error); + } -"use strict"; + return read; +}; -const EventEmitter = __webpack_require__(285); +exports.stat = path => stat(path).catch(error => { + throw new CpFileError(`Cannot stat path \`${path}\`: ${error.message}`, error); +}); -const written = new WeakMap(); +exports.lstat = path => lstat(path).catch(error => { + throw new CpFileError(`lstat \`${path}\` failed: ${error.message}`, error); +}); -class ProgressEmitter extends EventEmitter { - constructor(source, destination) { - super(); - this._source = source; - this._destination = destination; +exports.utimes = (path, atime, mtime) => utimes(path, atime, mtime).catch(error => { + throw new CpFileError(`utimes \`${path}\` failed: ${error.message}`, error); +}); + +exports.chmod = (path, mode) => chmod(path, mode).catch(error => { + throw new CpFileError(`chmod \`${path}\` failed: ${error.message}`, error); +}); + +exports.chown = (path, uid, gid) => chown(path, uid, gid).catch(error => { + throw new CpFileError(`chown \`${path}\` failed: ${error.message}`, error); +}); + +exports.statSync = path => { + try { + return fs.statSync(path); + } catch (error) { + throw new CpFileError(`stat \`${path}\` failed: ${error.message}`, error); } +}; - set written(value) { - written.set(this, value); - this.emitProgress(); +exports.utimesSync = (path, atime, mtime) => { + try { + return fs.utimesSync(path, atime, mtime); + } catch (error) { + throw new CpFileError(`utimes \`${path}\` failed: ${error.message}`, error); } +}; - get written() { - return written.get(this); +exports.chmodSync = (path, mode) => { + try { + return fs.chmodSync(path, mode); + } catch (error) { + throw new CpFileError(`chmod \`${path}\` failed: ${error.message}`, error); } +}; - emitProgress() { - const {size, written} = this; - this.emit('progress', { - src: this._source, - dest: this._destination, - size, - written, - percent: written === size ? 1 : written / size - }); +exports.chownSync = (path, uid, gid) => { + try { + return fs.chownSync(path, uid, gid); + } catch (error) { + throw new CpFileError(`chown \`${path}\` failed: ${error.message}`, error); } -} +}; -module.exports = ProgressEmitter; +exports.makeDir = path => makeDir(path, {fs}).catch(error => { + throw new CpFileError(`Cannot create directory \`${path}\`: ${error.message}`, error); +}); + +exports.makeDirSync = path => { + try { + makeDir.sync(path, {fs}); + } catch (error) { + throw new CpFileError(`Cannot create directory \`${path}\`: ${error.message}`, error); + } +}; + +exports.copyFileSync = (source, destination, flags) => { + try { + fs.copyFileSync(source, destination, flags); + } catch (error) { + throw new CpFileError(`Cannot copy from \`${source}\` to \`${destination}\`: ${error.message}`, error); + } +}; /***/ }), -/* 801 */ +/* 836 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +const fs = __webpack_require__(253); +const path = __webpack_require__(4); +const {promisify} = __webpack_require__(234); +const semver = __webpack_require__(837); -const blacklist = [ - // # All - '^npm-debug\\.log$', // Error log for npm - '^\\..*\\.swp$', // Swap file for vim state +const useNativeRecursiveOption = semver.satisfies(process.version, '>=10.12.0'); - // # macOS - '^\\.DS_Store$', // Stores custom folder attributes - '^\\.AppleDouble$', // Stores additional file resources - '^\\.LSOverride$', // Contains the absolute path to the app to be used - '^Icon\\r$', // Custom Finder icon: http://superuser.com/questions/298785/icon-file-on-os-x-desktop - '^\\._.*', // Thumbnail - '^\\.Spotlight-V100(?:$|\\/)', // Directory that might appear on external disk - '\\.Trashes', // File that might appear on external disk - '^__MACOSX$', // Resource fork +// https://github.com/nodejs/node/issues/8987 +// https://github.com/libuv/libuv/pull/1088 +const checkPath = pth => { + if (process.platform === 'win32') { + const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path.parse(pth).root, '')); - // # Linux - '~$', // Backup file + if (pathHasInvalidWinCharacters) { + const error = new Error(`Path contains invalid characters: ${pth}`); + error.code = 'EINVAL'; + throw error; + } + } +}; - // # Windows - '^Thumbs\\.db$', // Image file cache - '^ehthumbs\\.db$', // Folder config file - '^Desktop\\.ini$', // Stores custom folder attributes - '@eaDir$' // Synology Diskstation "hidden" folder where the server stores thumbnails -]; +const processOptions = options => { + // https://github.com/sindresorhus/make-dir/issues/18 + const defaults = { + mode: 0o777, + fs + }; -exports.re = () => { - throw new Error('`junk.re` was renamed to `junk.regex`'); + return { + ...defaults, + ...options + }; }; -exports.regex = new RegExp(blacklist.join('|')); +const permissionError = pth => { + // This replicates the exception of `fs.mkdir` with native the + // `recusive` option when run on an invalid drive under Windows. + const error = new Error(`operation not permitted, mkdir '${pth}'`); + error.code = 'EPERM'; + error.errno = -4048; + error.path = pth; + error.syscall = 'mkdir'; + return error; +}; -exports.is = filename => exports.regex.test(filename); +const makeDir = async (input, options) => { + checkPath(input); + options = processOptions(options); -exports.not = filename => !exports.is(filename); + const mkdir = promisify(options.fs.mkdir); + const stat = promisify(options.fs.stat); -// TODO: Remove this for the next major release -exports.default = module.exports; + if (useNativeRecursiveOption && options.fs.mkdir === fs.mkdir) { + const pth = path.resolve(input); + await mkdir(pth, { + mode: options.mode, + recursive: true + }); -/***/ }), -/* 802 */ -/***/ (function(module, exports, __webpack_require__) { + return pth; + } -"use strict"; + const make = async pth => { + try { + await mkdir(pth, options.mode); -const pMap = __webpack_require__(803); + return pth; + } catch (error) { + if (error.code === 'EPERM') { + throw error; + } -const pFilter = async (iterable, filterer, options) => { - const values = await pMap( - iterable, - (element, index) => Promise.all([filterer(element, index), element]), - options - ); - return values.filter(value => Boolean(value[0])).map(value => value[1]); -}; + if (error.code === 'ENOENT') { + if (path.dirname(pth) === pth) { + throw permissionError(pth); + } -module.exports = pFilter; -// TODO: Remove this for the next major release -module.exports.default = pFilter; + if (error.message.includes('null bytes')) { + throw error; + } + await make(path.dirname(pth)); -/***/ }), -/* 803 */ -/***/ (function(module, exports, __webpack_require__) { + return make(pth); + } -"use strict"; + try { + const stats = await stat(pth); + if (!stats.isDirectory()) { + throw new Error('The path is not a directory'); + } + } catch (_) { + throw error; + } + return pth; + } + }; -const pMap = (iterable, mapper, options) => new Promise((resolve, reject) => { - options = Object.assign({ - concurrency: Infinity - }, options); + return make(path.resolve(input)); +}; - if (typeof mapper !== 'function') { - throw new TypeError('Mapper function is required'); - } +module.exports = makeDir; - const {concurrency} = options; +module.exports.sync = (input, options) => { + checkPath(input); + options = processOptions(options); - if (!(typeof concurrency === 'number' && concurrency >= 1)) { - throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${concurrency}\` (${typeof concurrency})`); - } + if (useNativeRecursiveOption && options.fs.mkdirSync === fs.mkdirSync) { + const pth = path.resolve(input); - const ret = []; - const iterator = iterable[Symbol.iterator](); - let isRejected = false; - let isIterableDone = false; - let resolvingCount = 0; - let currentIndex = 0; + fs.mkdirSync(pth, { + mode: options.mode, + recursive: true + }); - const next = () => { - if (isRejected) { - return; - } + return pth; + } - const nextItem = iterator.next(); - const i = currentIndex; - currentIndex++; + const make = pth => { + try { + options.fs.mkdirSync(pth, options.mode); + } catch (error) { + if (error.code === 'EPERM') { + throw error; + } - if (nextItem.done) { - isIterableDone = true; + if (error.code === 'ENOENT') { + if (path.dirname(pth) === pth) { + throw permissionError(pth); + } - if (resolvingCount === 0) { - resolve(ret); + if (error.message.includes('null bytes')) { + throw error; + } + + make(path.dirname(pth)); + return make(pth); } - return; + try { + if (!options.fs.statSync(pth).isDirectory()) { + throw new Error('The path is not a directory'); + } + } catch (_) { + throw error; + } } - resolvingCount++; - - Promise.resolve(nextItem.value) - .then(element => mapper(element, i)) - .then( - value => { - ret[i] = value; - resolvingCount--; - next(); - }, - error => { - isRejected = true; - reject(error); - } - ); + return pth; }; - for (let i = 0; i < concurrency; i++) { - next(); + return make(path.resolve(input)); +}; - if (isIterableDone) { - break; - } - } -}); -module.exports = pMap; -// TODO: Remove this for the next major release -module.exports.default = pMap; +/***/ }), +/* 837 */ +/***/ (function(module, exports) { +exports = module.exports = SemVer -/***/ }), -/* 804 */ -/***/ (function(module, exports, __webpack_require__) { +var debug +/* istanbul ignore next */ +if (typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG)) { + debug = function () { + var args = Array.prototype.slice.call(arguments, 0) + args.unshift('SEMVER') + console.log.apply(console, args) + } +} else { + debug = function () {} +} -"use strict"; +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +exports.SEMVER_SPEC_VERSION = '2.0.0' -const NestedError = __webpack_require__(796); +var MAX_LENGTH = 256 +var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ 9007199254740991 -class CpyError extends NestedError { - constructor(message, nested) { - super(message, nested); - Object.assign(this, nested); - this.name = 'CpyError'; - } +// Max safe segment length for coercion. +var MAX_SAFE_COMPONENT_LENGTH = 16 + +// The actual regexps go on exports.re +var re = exports.re = [] +var src = exports.src = [] +var t = exports.tokens = {} +var R = 0 + +function tok (n) { + t[n] = R++ } -module.exports = CpyError; +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. -/***/ }), -/* 805 */ -/***/ (function(module, exports, __webpack_require__) { +tok('NUMERICIDENTIFIER') +src[t.NUMERICIDENTIFIER] = '0|[1-9]\\d*' +tok('NUMERICIDENTIFIERLOOSE') +src[t.NUMERICIDENTIFIERLOOSE] = '[0-9]+' + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +tok('NONNUMERICIDENTIFIER') +src[t.NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' + +// ## Main Version +// Three dot-separated numeric identifiers. + +tok('MAINVERSION') +src[t.MAINVERSION] = '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + + '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + + '(' + src[t.NUMERICIDENTIFIER] + ')' + +tok('MAINVERSIONLOOSE') +src[t.MAINVERSIONLOOSE] = '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')' + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +tok('PRERELEASEIDENTIFIER') +src[t.PRERELEASEIDENTIFIER] = '(?:' + src[t.NUMERICIDENTIFIER] + + '|' + src[t.NONNUMERICIDENTIFIER] + ')' + +tok('PRERELEASEIDENTIFIERLOOSE') +src[t.PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[t.NUMERICIDENTIFIERLOOSE] + + '|' + src[t.NONNUMERICIDENTIFIER] + ')' + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +tok('PRERELEASE') +src[t.PRERELEASE] = '(?:-(' + src[t.PRERELEASEIDENTIFIER] + + '(?:\\.' + src[t.PRERELEASEIDENTIFIER] + ')*))' + +tok('PRERELEASELOOSE') +src[t.PRERELEASELOOSE] = '(?:-?(' + src[t.PRERELEASEIDENTIFIERLOOSE] + + '(?:\\.' + src[t.PRERELEASEIDENTIFIERLOOSE] + ')*))' -"use strict"; +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. -const fs = __webpack_require__(253); -const arrayUnion = __webpack_require__(363); -const merge2 = __webpack_require__(364); -const fastGlob = __webpack_require__(806); -const dirGlob = __webpack_require__(447); -const gitignore = __webpack_require__(831); -const {FilterStream, UniqueStream} = __webpack_require__(832); +tok('BUILDIDENTIFIER') +src[t.BUILDIDENTIFIER] = '[0-9A-Za-z-]+' -const DEFAULT_FILTER = () => false; +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. -const isNegative = pattern => pattern[0] === '!'; +tok('BUILD') +src[t.BUILD] = '(?:\\+(' + src[t.BUILDIDENTIFIER] + + '(?:\\.' + src[t.BUILDIDENTIFIER] + ')*))' -const assertPatternsInput = patterns => { - if (!patterns.every(pattern => typeof pattern === 'string')) { - throw new TypeError('Patterns must be a string or an array of strings'); - } -}; +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. -const checkCwdOption = (options = {}) => { - if (!options.cwd) { - return; - } +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. - let stat; - try { - stat = fs.statSync(options.cwd); - } catch { - return; - } +tok('FULL') +tok('FULLPLAIN') +src[t.FULLPLAIN] = 'v?' + src[t.MAINVERSION] + + src[t.PRERELEASE] + '?' + + src[t.BUILD] + '?' - if (!stat.isDirectory()) { - throw new Error('The `cwd` option must be a path to a directory'); - } -}; +src[t.FULL] = '^' + src[t.FULLPLAIN] + '$' -const getPathString = p => p.stats instanceof fs.Stats ? p.path : p; +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +tok('LOOSEPLAIN') +src[t.LOOSEPLAIN] = '[v=\\s]*' + src[t.MAINVERSIONLOOSE] + + src[t.PRERELEASELOOSE] + '?' + + src[t.BUILD] + '?' -const generateGlobTasks = (patterns, taskOptions) => { - patterns = arrayUnion([].concat(patterns)); - assertPatternsInput(patterns); - checkCwdOption(taskOptions); +tok('LOOSE') +src[t.LOOSE] = '^' + src[t.LOOSEPLAIN] + '$' - const globTasks = []; +tok('GTLT') +src[t.GTLT] = '((?:<|>)?=?)' - taskOptions = { - ignore: [], - expandDirectories: true, - ...taskOptions - }; +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +tok('XRANGEIDENTIFIERLOOSE') +src[t.XRANGEIDENTIFIERLOOSE] = src[t.NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' +tok('XRANGEIDENTIFIER') +src[t.XRANGEIDENTIFIER] = src[t.NUMERICIDENTIFIER] + '|x|X|\\*' - for (const [index, pattern] of patterns.entries()) { - if (isNegative(pattern)) { - continue; - } +tok('XRANGEPLAIN') +src[t.XRANGEPLAIN] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + + '(?:' + src[t.PRERELEASE] + ')?' + + src[t.BUILD] + '?' + + ')?)?' - const ignore = patterns - .slice(index) - .filter(pattern => isNegative(pattern)) - .map(pattern => pattern.slice(1)); +tok('XRANGEPLAINLOOSE') +src[t.XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + + '(?:' + src[t.PRERELEASELOOSE] + ')?' + + src[t.BUILD] + '?' + + ')?)?' - const options = { - ...taskOptions, - ignore: taskOptions.ignore.concat(ignore) - }; +tok('XRANGE') +src[t.XRANGE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAIN] + '$' +tok('XRANGELOOSE') +src[t.XRANGELOOSE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAINLOOSE] + '$' - globTasks.push({pattern, options}); - } +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +tok('COERCE') +src[t.COERCE] = '(^|[^\\d])' + + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:$|[^\\d])' +tok('COERCERTL') +re[t.COERCERTL] = new RegExp(src[t.COERCE], 'g') - return globTasks; -}; +// Tilde ranges. +// Meaning is "reasonably at or greater than" +tok('LONETILDE') +src[t.LONETILDE] = '(?:~>?)' -const globDirs = (task, fn) => { - let options = {}; - if (task.options.cwd) { - options.cwd = task.options.cwd; - } +tok('TILDETRIM') +src[t.TILDETRIM] = '(\\s*)' + src[t.LONETILDE] + '\\s+' +re[t.TILDETRIM] = new RegExp(src[t.TILDETRIM], 'g') +var tildeTrimReplace = '$1~' - if (Array.isArray(task.options.expandDirectories)) { - options = { - ...options, - files: task.options.expandDirectories - }; - } else if (typeof task.options.expandDirectories === 'object') { - options = { - ...options, - ...task.options.expandDirectories - }; - } +tok('TILDE') +src[t.TILDE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAIN] + '$' +tok('TILDELOOSE') +src[t.TILDELOOSE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAINLOOSE] + '$' - return fn(task.pattern, options); -}; +// Caret ranges. +// Meaning is "at least and backwards compatible with" +tok('LONECARET') +src[t.LONECARET] = '(?:\\^)' -const getPattern = (task, fn) => task.options.expandDirectories ? globDirs(task, fn) : [task.pattern]; +tok('CARETTRIM') +src[t.CARETTRIM] = '(\\s*)' + src[t.LONECARET] + '\\s+' +re[t.CARETTRIM] = new RegExp(src[t.CARETTRIM], 'g') +var caretTrimReplace = '$1^' -const getFilterSync = options => { - return options && options.gitignore ? - gitignore.sync({cwd: options.cwd, ignore: options.ignore}) : - DEFAULT_FILTER; -}; +tok('CARET') +src[t.CARET] = '^' + src[t.LONECARET] + src[t.XRANGEPLAIN] + '$' +tok('CARETLOOSE') +src[t.CARETLOOSE] = '^' + src[t.LONECARET] + src[t.XRANGEPLAINLOOSE] + '$' -const globToTask = task => glob => { - const {options} = task; - if (options.ignore && Array.isArray(options.ignore) && options.expandDirectories) { - options.ignore = dirGlob.sync(options.ignore); - } +// A simple gt/lt/eq thing, or just "" to indicate "any version" +tok('COMPARATORLOOSE') +src[t.COMPARATORLOOSE] = '^' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + ')$|^$' +tok('COMPARATOR') +src[t.COMPARATOR] = '^' + src[t.GTLT] + '\\s*(' + src[t.FULLPLAIN] + ')$|^$' - return { - pattern: glob, - options - }; -}; +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +tok('COMPARATORTRIM') +src[t.COMPARATORTRIM] = '(\\s*)' + src[t.GTLT] + + '\\s*(' + src[t.LOOSEPLAIN] + '|' + src[t.XRANGEPLAIN] + ')' -module.exports = async (patterns, options) => { - const globTasks = generateGlobTasks(patterns, options); +// this one has to use the /g flag +re[t.COMPARATORTRIM] = new RegExp(src[t.COMPARATORTRIM], 'g') +var comparatorTrimReplace = '$1$2$3' - const getFilter = async () => { - return options && options.gitignore ? - gitignore({cwd: options.cwd, ignore: options.ignore}) : - DEFAULT_FILTER; - }; +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +tok('HYPHENRANGE') +src[t.HYPHENRANGE] = '^\\s*(' + src[t.XRANGEPLAIN] + ')' + + '\\s+-\\s+' + + '(' + src[t.XRANGEPLAIN] + ')' + + '\\s*$' - const getTasks = async () => { - const tasks = await Promise.all(globTasks.map(async task => { - const globs = await getPattern(task, dirGlob); - return Promise.all(globs.map(globToTask(task))); - })); +tok('HYPHENRANGELOOSE') +src[t.HYPHENRANGELOOSE] = '^\\s*(' + src[t.XRANGEPLAINLOOSE] + ')' + + '\\s+-\\s+' + + '(' + src[t.XRANGEPLAINLOOSE] + ')' + + '\\s*$' - return arrayUnion(...tasks); - }; +// Star ranges basically just allow anything at all. +tok('STAR') +src[t.STAR] = '(<|>)?=?\\s*\\*' - const [filter, tasks] = await Promise.all([getFilter(), getTasks()]); - const paths = await Promise.all(tasks.map(task => fastGlob(task.pattern, task.options))); +// Compile to actual regexp objects. +// All are flag-free, unless they were created above with a flag. +for (var i = 0; i < R; i++) { + debug(i, src[i]) + if (!re[i]) { + re[i] = new RegExp(src[i]) + } +} - return arrayUnion(...paths).filter(path_ => !filter(getPathString(path_))); -}; +exports.parse = parse +function parse (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } -module.exports.sync = (patterns, options) => { - const globTasks = generateGlobTasks(patterns, options); + if (version instanceof SemVer) { + return version + } - const tasks = []; - for (const task of globTasks) { - const newTask = getPattern(task, dirGlob.sync).map(globToTask(task)); - tasks.push(...newTask); - } + if (typeof version !== 'string') { + return null + } - const filter = getFilterSync(options); + if (version.length > MAX_LENGTH) { + return null + } - let matches = []; - for (const task of tasks) { - matches = arrayUnion(matches, fastGlob.sync(task.pattern, task.options)); - } + var r = options.loose ? re[t.LOOSE] : re[t.FULL] + if (!r.test(version)) { + return null + } - return matches.filter(path_ => !filter(path_)); -}; + try { + return new SemVer(version, options) + } catch (er) { + return null + } +} -module.exports.stream = (patterns, options) => { - const globTasks = generateGlobTasks(patterns, options); +exports.valid = valid +function valid (version, options) { + var v = parse(version, options) + return v ? v.version : null +} - const tasks = []; - for (const task of globTasks) { - const newTask = getPattern(task, dirGlob.sync).map(globToTask(task)); - tasks.push(...newTask); - } +exports.clean = clean +function clean (version, options) { + var s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null +} - const filter = getFilterSync(options); - const filterStream = new FilterStream(p => !filter(p)); - const uniqueStream = new UniqueStream(); +exports.SemVer = SemVer - return merge2(tasks.map(task => fastGlob.stream(task.pattern, task.options))) - .pipe(filterStream) - .pipe(uniqueStream); -}; +function SemVer (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + if (version instanceof SemVer) { + if (version.loose === options.loose) { + return version + } else { + version = version.version + } + } else if (typeof version !== 'string') { + throw new TypeError('Invalid Version: ' + version) + } -module.exports.generateGlobTasks = generateGlobTasks; + if (version.length > MAX_LENGTH) { + throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') + } -module.exports.hasMagic = (patterns, options) => [] - .concat(patterns) - .some(pattern => fastGlob.isDynamicPattern(pattern, options)); + if (!(this instanceof SemVer)) { + return new SemVer(version, options) + } -module.exports.gitignore = gitignore; + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose + var m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) -/***/ }), -/* 806 */ -/***/ (function(module, exports, __webpack_require__) { + if (!m) { + throw new TypeError('Invalid Version: ' + version) + } -"use strict"; + this.raw = version -const taskManager = __webpack_require__(807); -const async_1 = __webpack_require__(817); -const stream_1 = __webpack_require__(827); -const sync_1 = __webpack_require__(828); -const settings_1 = __webpack_require__(830); -const utils = __webpack_require__(808); -async function FastGlob(source, options) { - assertPatternsInput(source); - const works = getWorks(source, async_1.default, options); - const result = await Promise.all(works); - return utils.array.flatten(result); -} -// https://github.com/typescript-eslint/typescript-eslint/issues/60 -// eslint-disable-next-line no-redeclare -(function (FastGlob) { - function sync(source, options) { - assertPatternsInput(source); - const works = getWorks(source, sync_1.default, options); - return utils.array.flatten(works); - } - FastGlob.sync = sync; - function stream(source, options) { - assertPatternsInput(source); - const works = getWorks(source, stream_1.default, options); - /** - * The stream returned by the provider cannot work with an asynchronous iterator. - * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams. - * This affects performance (+25%). I don't see best solution right now. - */ - return utils.stream.merge(works); - } - FastGlob.stream = stream; - function generateTasks(source, options) { - assertPatternsInput(source); - const patterns = [].concat(source); - const settings = new settings_1.default(options); - return taskManager.generate(patterns, settings); - } - FastGlob.generateTasks = generateTasks; - function isDynamicPattern(source, options) { - assertPatternsInput(source); - const settings = new settings_1.default(options); - return utils.pattern.isDynamicPattern(source, settings); - } - FastGlob.isDynamicPattern = isDynamicPattern; - function escapePath(source) { - assertPatternsInput(source); - return utils.path.escape(source); - } - FastGlob.escapePath = escapePath; -})(FastGlob || (FastGlob = {})); -function getWorks(source, _Provider, options) { - const patterns = [].concat(source); - const settings = new settings_1.default(options); - const tasks = taskManager.generate(patterns, settings); - const provider = new _Provider(settings); - return tasks.map(provider.read, provider); -} -function assertPatternsInput(input) { - const source = [].concat(input); - const isValidSource = source.every((item) => utils.string.isString(item) && !utils.string.isEmpty(item)); - if (!isValidSource) { - throw new TypeError('Patterns must be a string (non empty) or an array of strings'); - } -} -module.exports = FastGlob; + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } -/***/ }), -/* 807 */ -/***/ (function(module, exports, __webpack_require__) { + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } -"use strict"; + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } -Object.defineProperty(exports, "__esModule", { value: true }); -exports.convertPatternGroupToTask = exports.convertPatternGroupsToTasks = exports.groupPatternsByBaseDirectory = exports.getNegativePatternsAsPositive = exports.getPositivePatterns = exports.convertPatternsToTasks = exports.generate = void 0; -const utils = __webpack_require__(808); -function generate(patterns, settings) { - const positivePatterns = getPositivePatterns(patterns); - const negativePatterns = getNegativePatternsAsPositive(patterns, settings.ignore); - const staticPatterns = positivePatterns.filter((pattern) => utils.pattern.isStaticPattern(pattern, settings)); - const dynamicPatterns = positivePatterns.filter((pattern) => utils.pattern.isDynamicPattern(pattern, settings)); - const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false); - const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, /* dynamic */ true); - return staticTasks.concat(dynamicTasks); -} -exports.generate = generate; -/** - * Returns tasks grouped by basic pattern directories. - * - * Patterns that can be found inside (`./`) and outside (`../`) the current directory are handled separately. - * This is necessary because directory traversal starts at the base directory and goes deeper. - */ -function convertPatternsToTasks(positive, negative, dynamic) { - const tasks = []; - const patternsOutsideCurrentDirectory = utils.pattern.getPatternsOutsideCurrentDirectory(positive); - const patternsInsideCurrentDirectory = utils.pattern.getPatternsInsideCurrentDirectory(positive); - const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsOutsideCurrentDirectory); - const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsInsideCurrentDirectory); - tasks.push(...convertPatternGroupsToTasks(outsideCurrentDirectoryGroup, negative, dynamic)); - /* - * For the sake of reducing future accesses to the file system, we merge all tasks within the current directory - * into a global task, if at least one pattern refers to the root (`.`). In this case, the global task covers the rest. - */ - if ('.' in insideCurrentDirectoryGroup) { - tasks.push(convertPatternGroupToTask('.', patternsInsideCurrentDirectory, negative, dynamic)); - } - else { - tasks.push(...convertPatternGroupsToTasks(insideCurrentDirectoryGroup, negative, dynamic)); - } - return tasks; -} -exports.convertPatternsToTasks = convertPatternsToTasks; -function getPositivePatterns(patterns) { - return utils.pattern.getPositivePatterns(patterns); -} -exports.getPositivePatterns = getPositivePatterns; -function getNegativePatternsAsPositive(patterns, ignore) { - const negative = utils.pattern.getNegativePatterns(patterns).concat(ignore); - const positive = negative.map(utils.pattern.convertToPositivePattern); - return positive; -} -exports.getNegativePatternsAsPositive = getNegativePatternsAsPositive; -function groupPatternsByBaseDirectory(patterns) { - const group = {}; - return patterns.reduce((collection, pattern) => { - const base = utils.pattern.getBaseDirectory(pattern); - if (base in collection) { - collection[base].push(pattern); - } - else { - collection[base] = [pattern]; + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map(function (id) { + if (/^[0-9]+$/.test(id)) { + var num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num } - return collection; - }, group); -} -exports.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory; -function convertPatternGroupsToTasks(positive, negative, dynamic) { - return Object.keys(positive).map((base) => { - return convertPatternGroupToTask(base, positive[base], negative, dynamic); - }); + } + return id + }) + } + + this.build = m[5] ? m[5].split('.') : [] + this.format() } -exports.convertPatternGroupsToTasks = convertPatternGroupsToTasks; -function convertPatternGroupToTask(base, positive, negative, dynamic) { - return { - dynamic, - positive, - negative, - base, - patterns: [].concat(positive, negative.map(utils.pattern.convertToNegativePattern)) - }; + +SemVer.prototype.format = function () { + this.version = this.major + '.' + this.minor + '.' + this.patch + if (this.prerelease.length) { + this.version += '-' + this.prerelease.join('.') + } + return this.version } -exports.convertPatternGroupToTask = convertPatternGroupToTask; +SemVer.prototype.toString = function () { + return this.version +} -/***/ }), -/* 808 */ -/***/ (function(module, exports, __webpack_require__) { +SemVer.prototype.compare = function (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } -"use strict"; + return this.compareMain(other) || this.comparePre(other) +} -Object.defineProperty(exports, "__esModule", { value: true }); -exports.string = exports.stream = exports.pattern = exports.path = exports.fs = exports.errno = exports.array = void 0; -const array = __webpack_require__(809); -exports.array = array; -const errno = __webpack_require__(810); -exports.errno = errno; -const fs = __webpack_require__(811); -exports.fs = fs; -const path = __webpack_require__(812); -exports.path = path; -const pattern = __webpack_require__(813); -exports.pattern = pattern; -const stream = __webpack_require__(815); -exports.stream = stream; -const string = __webpack_require__(816); -exports.string = string; +SemVer.prototype.compareMain = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + return compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) +} -/***/ }), -/* 809 */ -/***/ (function(module, exports, __webpack_require__) { +SemVer.prototype.comparePre = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } -"use strict"; + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } -Object.defineProperty(exports, "__esModule", { value: true }); -exports.splitWhen = exports.flatten = void 0; -function flatten(items) { - return items.reduce((collection, item) => [].concat(collection, item), []); -} -exports.flatten = flatten; -function splitWhen(items, predicate) { - const result = [[]]; - let groupIndex = 0; - for (const item of items) { - if (predicate(item)) { - groupIndex++; - result[groupIndex] = []; - } - else { - result[groupIndex].push(item); - } + var i = 0 + do { + var a = this.prerelease[i] + var b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) } - return result; + } while (++i) } -exports.splitWhen = splitWhen; - -/***/ }), -/* 810 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; +SemVer.prototype.compareBuild = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } -Object.defineProperty(exports, "__esModule", { value: true }); -exports.isEnoentCodeError = void 0; -function isEnoentCodeError(error) { - return error.code === 'ENOENT'; + var i = 0 + do { + var a = this.build[i] + var b = other.build[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) } -exports.isEnoentCodeError = isEnoentCodeError; - -/***/ }), -/* 811 */ -/***/ (function(module, exports, __webpack_require__) { +// preminor will bump the version up to the next minor release, and immediately +// down to pre-release. premajor and prepatch work the same way. +SemVer.prototype.inc = function (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier) + this.inc('pre', identifier) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier) + } + this.inc('pre', identifier) + break -"use strict"; + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0) { + this.major++ + } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0] + } else { + var i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0] + } + } else { + this.prerelease = [identifier, 0] + } + } + break -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createDirentFromStats = void 0; -class DirentFromStats { - constructor(name, stats) { - this.name = name; - this.isBlockDevice = stats.isBlockDevice.bind(stats); - this.isCharacterDevice = stats.isCharacterDevice.bind(stats); - this.isDirectory = stats.isDirectory.bind(stats); - this.isFIFO = stats.isFIFO.bind(stats); - this.isFile = stats.isFile.bind(stats); - this.isSocket = stats.isSocket.bind(stats); - this.isSymbolicLink = stats.isSymbolicLink.bind(stats); - } -} -function createDirentFromStats(name, stats) { - return new DirentFromStats(name, stats); + default: + throw new Error('invalid increment argument: ' + release) + } + this.format() + this.raw = this.version + return this } -exports.createDirentFromStats = createDirentFromStats; - - -/***/ }), -/* 812 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; +exports.inc = inc +function inc (version, release, loose, identifier) { + if (typeof (loose) === 'string') { + identifier = loose + loose = undefined + } -Object.defineProperty(exports, "__esModule", { value: true }); -exports.removeLeadingDotSegment = exports.escape = exports.makeAbsolute = exports.unixify = void 0; -const path = __webpack_require__(4); -const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\ -const UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\())/g; -/** - * Designed to work only with simple paths: `dir\\file`. - */ -function unixify(filepath) { - return filepath.replace(/\\/g, '/'); -} -exports.unixify = unixify; -function makeAbsolute(cwd, filepath) { - return path.resolve(cwd, filepath); -} -exports.makeAbsolute = makeAbsolute; -function escape(pattern) { - return pattern.replace(UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); + try { + return new SemVer(version, loose).inc(release, identifier).version + } catch (er) { + return null + } } -exports.escape = escape; -function removeLeadingDotSegment(entry) { - // We do not use `startsWith` because this is 10x slower than current implementation for some cases. - // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with - if (entry.charAt(0) === '.') { - const secondCharactery = entry.charAt(1); - if (secondCharactery === '/' || secondCharactery === '\\') { - return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT); + +exports.diff = diff +function diff (version1, version2) { + if (eq(version1, version2)) { + return null + } else { + var v1 = parse(version1) + var v2 = parse(version2) + var prefix = '' + if (v1.prerelease.length || v2.prerelease.length) { + prefix = 'pre' + var defaultResult = 'prerelease' + } + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key } + } } - return entry; + return defaultResult // may be undefined + } } -exports.removeLeadingDotSegment = removeLeadingDotSegment; +exports.compareIdentifiers = compareIdentifiers -/***/ }), -/* 813 */ -/***/ (function(module, exports, __webpack_require__) { +var numeric = /^[0-9]+$/ +function compareIdentifiers (a, b) { + var anum = numeric.test(a) + var bnum = numeric.test(b) -"use strict"; + if (anum && bnum) { + a = +a + b = +b + } -Object.defineProperty(exports, "__esModule", { value: true }); -exports.matchAny = exports.convertPatternsToRe = exports.makeRe = exports.getPatternParts = exports.expandBraceExpansion = exports.expandPatternsWithBraceExpansion = exports.isAffectDepthOfReadingPattern = exports.endsWithSlashGlobStar = exports.hasGlobStar = exports.getBaseDirectory = exports.isPatternRelatedToParentDirectory = exports.getPatternsOutsideCurrentDirectory = exports.getPatternsInsideCurrentDirectory = exports.getPositivePatterns = exports.getNegativePatterns = exports.isPositivePattern = exports.isNegativePattern = exports.convertToNegativePattern = exports.convertToPositivePattern = exports.isDynamicPattern = exports.isStaticPattern = void 0; -const path = __webpack_require__(4); -const globParent = __webpack_require__(386); -const micromatch = __webpack_require__(814); -const GLOBSTAR = '**'; -const ESCAPE_SYMBOL = '\\'; -const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/; -const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[.*]/; -const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\(.*\|.*\)/; -const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\(.*\)/; -const BRACE_EXPANSIONS_SYMBOLS_RE = /{.*(?:,|\.\.).*}/; -function isStaticPattern(pattern, options = {}) { - return !isDynamicPattern(pattern, options); -} -exports.isStaticPattern = isStaticPattern; -function isDynamicPattern(pattern, options = {}) { - /** - * A special case with an empty string is necessary for matching patterns that start with a forward slash. - * An empty string cannot be a dynamic pattern. - * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'. - */ - if (pattern === '') { - return false; - } - /** - * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check - * filepath directly (without read directory). - */ - if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) { - return true; - } - if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) { - return true; - } - if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) { - return true; - } - if (options.braceExpansion !== false && BRACE_EXPANSIONS_SYMBOLS_RE.test(pattern)) { - return true; - } - return false; -} -exports.isDynamicPattern = isDynamicPattern; -function convertToPositivePattern(pattern) { - return isNegativePattern(pattern) ? pattern.slice(1) : pattern; -} -exports.convertToPositivePattern = convertToPositivePattern; -function convertToNegativePattern(pattern) { - return '!' + pattern; -} -exports.convertToNegativePattern = convertToNegativePattern; -function isNegativePattern(pattern) { - return pattern.startsWith('!') && pattern[1] !== '('; -} -exports.isNegativePattern = isNegativePattern; -function isPositivePattern(pattern) { - return !isNegativePattern(pattern); -} -exports.isPositivePattern = isPositivePattern; -function getNegativePatterns(patterns) { - return patterns.filter(isNegativePattern); -} -exports.getNegativePatterns = getNegativePatterns; -function getPositivePatterns(patterns) { - return patterns.filter(isPositivePattern); -} -exports.getPositivePatterns = getPositivePatterns; -/** - * Returns patterns that can be applied inside the current directory. - * - * @example - * // ['./*', '*', 'a/*'] - * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) - */ -function getPatternsInsideCurrentDirectory(patterns) { - return patterns.filter((pattern) => !isPatternRelatedToParentDirectory(pattern)); + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 } -exports.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory; -/** - * Returns patterns to be expanded relative to (outside) the current directory. - * - * @example - * // ['../*', './../*'] - * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) - */ -function getPatternsOutsideCurrentDirectory(patterns) { - return patterns.filter(isPatternRelatedToParentDirectory); + +exports.rcompareIdentifiers = rcompareIdentifiers +function rcompareIdentifiers (a, b) { + return compareIdentifiers(b, a) } -exports.getPatternsOutsideCurrentDirectory = getPatternsOutsideCurrentDirectory; -function isPatternRelatedToParentDirectory(pattern) { - return pattern.startsWith('..') || pattern.startsWith('./..'); + +exports.major = major +function major (a, loose) { + return new SemVer(a, loose).major } -exports.isPatternRelatedToParentDirectory = isPatternRelatedToParentDirectory; -function getBaseDirectory(pattern) { - return globParent(pattern, { flipBackslashes: false }); + +exports.minor = minor +function minor (a, loose) { + return new SemVer(a, loose).minor } -exports.getBaseDirectory = getBaseDirectory; -function hasGlobStar(pattern) { - return pattern.includes(GLOBSTAR); + +exports.patch = patch +function patch (a, loose) { + return new SemVer(a, loose).patch } -exports.hasGlobStar = hasGlobStar; -function endsWithSlashGlobStar(pattern) { - return pattern.endsWith('/' + GLOBSTAR); + +exports.compare = compare +function compare (a, b, loose) { + return new SemVer(a, loose).compare(new SemVer(b, loose)) } -exports.endsWithSlashGlobStar = endsWithSlashGlobStar; -function isAffectDepthOfReadingPattern(pattern) { - const basename = path.basename(pattern); - return endsWithSlashGlobStar(pattern) || isStaticPattern(basename); + +exports.compareLoose = compareLoose +function compareLoose (a, b) { + return compare(a, b, true) } -exports.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern; -function expandPatternsWithBraceExpansion(patterns) { - return patterns.reduce((collection, pattern) => { - return collection.concat(expandBraceExpansion(pattern)); - }, []); + +exports.compareBuild = compareBuild +function compareBuild (a, b, loose) { + var versionA = new SemVer(a, loose) + var versionB = new SemVer(b, loose) + return versionA.compare(versionB) || versionA.compareBuild(versionB) } -exports.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion; -function expandBraceExpansion(pattern) { - return micromatch.braces(pattern, { - expand: true, - nodupes: true - }); + +exports.rcompare = rcompare +function rcompare (a, b, loose) { + return compare(b, a, loose) } -exports.expandBraceExpansion = expandBraceExpansion; -function getPatternParts(pattern, options) { - let { parts } = micromatch.scan(pattern, Object.assign(Object.assign({}, options), { parts: true })); - /** - * The scan method returns an empty array in some cases. - * See micromatch/picomatch#58 for more details. - */ - if (parts.length === 0) { - parts = [pattern]; - } - /** - * The scan method does not return an empty part for the pattern with a forward slash. - * This is another part of micromatch/picomatch#58. - */ - if (parts[0].startsWith('/')) { - parts[0] = parts[0].slice(1); - parts.unshift(''); - } - return parts; + +exports.sort = sort +function sort (list, loose) { + return list.sort(function (a, b) { + return exports.compareBuild(a, b, loose) + }) } -exports.getPatternParts = getPatternParts; -function makeRe(pattern, options) { - return micromatch.makeRe(pattern, options); + +exports.rsort = rsort +function rsort (list, loose) { + return list.sort(function (a, b) { + return exports.compareBuild(b, a, loose) + }) } -exports.makeRe = makeRe; -function convertPatternsToRe(patterns, options) { - return patterns.map((pattern) => makeRe(pattern, options)); + +exports.gt = gt +function gt (a, b, loose) { + return compare(a, b, loose) > 0 } -exports.convertPatternsToRe = convertPatternsToRe; -function matchAny(entry, patternsRe) { - return patternsRe.some((patternRe) => patternRe.test(entry)); + +exports.lt = lt +function lt (a, b, loose) { + return compare(a, b, loose) < 0 } -exports.matchAny = matchAny; +exports.eq = eq +function eq (a, b, loose) { + return compare(a, b, loose) === 0 +} -/***/ }), -/* 814 */ -/***/ (function(module, exports, __webpack_require__) { +exports.neq = neq +function neq (a, b, loose) { + return compare(a, b, loose) !== 0 +} -"use strict"; +exports.gte = gte +function gte (a, b, loose) { + return compare(a, b, loose) >= 0 +} +exports.lte = lte +function lte (a, b, loose) { + return compare(a, b, loose) <= 0 +} -const util = __webpack_require__(234); -const braces = __webpack_require__(390); -const picomatch = __webpack_require__(400); -const utils = __webpack_require__(403); -const isEmptyString = val => val === '' || val === './'; +exports.cmp = cmp +function cmp (a, op, b, loose) { + switch (op) { + case '===': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a === b -/** - * Returns an array of strings that match one or more glob patterns. - * - * ```js - * const mm = require('micromatch'); - * // mm(list, patterns[, options]); - * - * console.log(mm(['a.js', 'a.txt'], ['*.js'])); - * //=> [ 'a.js' ] - * ``` - * @param {String|Array} `list` List of strings to match. - * @param {String|Array} `patterns` One or more glob patterns to use for matching. - * @param {Object} `options` See available [options](#options) - * @return {Array} Returns an array of matches - * @summary false - * @api public - */ + case '!==': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a !== b -const micromatch = (list, patterns, options) => { - patterns = [].concat(patterns); - list = [].concat(list); + case '': + case '=': + case '==': + return eq(a, b, loose) - let omit = new Set(); - let keep = new Set(); - let items = new Set(); - let negatives = 0; + case '!=': + return neq(a, b, loose) - let onResult = state => { - items.add(state.output); - if (options && options.onResult) { - options.onResult(state); - } - }; + case '>': + return gt(a, b, loose) - for (let i = 0; i < patterns.length; i++) { - let isMatch = picomatch(String(patterns[i]), { ...options, onResult }, true); - let negated = isMatch.state.negated || isMatch.state.negatedExtglob; - if (negated) negatives++; + case '>=': + return gte(a, b, loose) - for (let item of list) { - let matched = isMatch(item, true); + case '<': + return lt(a, b, loose) - let match = negated ? !matched.isMatch : matched.isMatch; - if (!match) continue; + case '<=': + return lte(a, b, loose) - if (negated) { - omit.add(matched.output); - } else { - omit.delete(matched.output); - keep.add(matched.output); - } - } + default: + throw new TypeError('Invalid operator: ' + op) } +} - let result = negatives === patterns.length ? [...items] : [...keep]; - let matches = result.filter(item => !omit.has(item)); - - if (options && matches.length === 0) { - if (options.failglob === true) { - throw new Error(`No matches found for "${patterns.join(', ')}"`); +exports.Comparator = Comparator +function Comparator (comp, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false } + } - if (options.nonull === true || options.nullglob === true) { - return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns; + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value } } - return matches; -}; - -/** - * Backwards compatibility - */ - -micromatch.match = micromatch; + if (!(this instanceof Comparator)) { + return new Comparator(comp, options) + } -/** - * Returns a matcher function from the given glob `pattern` and `options`. - * The returned function takes a string to match as its only argument and returns - * true if the string is a match. - * - * ```js - * const mm = require('micromatch'); - * // mm.matcher(pattern[, options]); - * - * const isMatch = mm.matcher('*.!(*a)'); - * console.log(isMatch('a.a')); //=> false - * console.log(isMatch('a.b')); //=> true - * ``` - * @param {String} `pattern` Glob pattern - * @param {Object} `options` - * @return {Function} Returns a matcher function. - * @api public - */ + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) -micromatch.matcher = (pattern, options) => picomatch(pattern, options); + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } -/** - * Returns true if **any** of the given glob `patterns` match the specified `string`. - * - * ```js - * const mm = require('micromatch'); - * // mm.isMatch(string, patterns[, options]); - * - * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true - * console.log(mm.isMatch('a.a', 'b.*')); //=> false - * ``` - * @param {String} `str` The string to test. - * @param {String|Array} `patterns` One or more glob patterns to use for matching. - * @param {Object} `[options]` See available [options](#options). - * @return {Boolean} Returns true if any patterns match `str` - * @api public - */ + debug('comp', this) +} -micromatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); +var ANY = {} +Comparator.prototype.parse = function (comp) { + var r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] + var m = comp.match(r) -/** - * Backwards compatibility - */ + if (!m) { + throw new TypeError('Invalid comparator: ' + comp) + } -micromatch.any = micromatch.isMatch; + this.operator = m[1] !== undefined ? m[1] : '' + if (this.operator === '=') { + this.operator = '' + } -/** - * Returns a list of strings that _**do not match any**_ of the given `patterns`. - * - * ```js - * const mm = require('micromatch'); - * // mm.not(list, patterns[, options]); - * - * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); - * //=> ['b.b', 'c.c'] - * ``` - * @param {Array} `list` Array of strings to match. - * @param {String|Array} `patterns` One or more glob pattern to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Array} Returns an array of strings that **do not match** the given patterns. - * @api public - */ + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) + } +} -micromatch.not = (list, patterns, options = {}) => { - patterns = [].concat(patterns).map(String); - let result = new Set(); - let items = []; +Comparator.prototype.toString = function () { + return this.value +} - let onResult = state => { - if (options.onResult) options.onResult(state); - items.push(state.output); - }; +Comparator.prototype.test = function (version) { + debug('Comparator.test', version, this.options.loose) - let matches = micromatch(list, patterns, { ...options, onResult }); + if (this.semver === ANY || version === ANY) { + return true + } - for (let item of items) { - if (!matches.includes(item)) { - result.add(item); + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false } } - return [...result]; -}; -/** - * Returns true if the given `string` contains the given pattern. Similar - * to [.isMatch](#isMatch) but the pattern can match any part of the string. - * - * ```js - * var mm = require('micromatch'); - * // mm.contains(string, pattern[, options]); - * - * console.log(mm.contains('aa/bb/cc', '*b')); - * //=> true - * console.log(mm.contains('aa/bb/cc', '*d')); - * //=> false - * ``` - * @param {String} `str` The string to match. - * @param {String|Array} `patterns` Glob pattern to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Boolean} Returns true if any of the patterns matches any part of `str`. - * @api public - */ + return cmp(version, this.operator, this.semver, this.options) +} -micromatch.contains = (str, pattern, options) => { - if (typeof str !== 'string') { - throw new TypeError(`Expected a string: "${util.inspect(str)}"`); +Comparator.prototype.intersects = function (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') } - if (Array.isArray(pattern)) { - return pattern.some(p => micromatch.contains(str, p, options)); + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } } - if (typeof pattern === 'string') { - if (isEmptyString(str) || isEmptyString(pattern)) { - return false; - } + var rangeTmp - if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) { - return true; + if (this.operator === '') { + if (this.value === '') { + return true + } + rangeTmp = new Range(comp.value, options) + return satisfies(this.value, rangeTmp, options) + } else if (comp.operator === '') { + if (comp.value === '') { + return true } + rangeTmp = new Range(this.value, options) + return satisfies(comp.semver, rangeTmp, options) } - return micromatch.isMatch(str, pattern, { ...options, contains: true }); -}; + var sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>') + var sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<') + var sameSemVer = this.semver.version === comp.semver.version + var differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<=') + var oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + ((this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<')) + var oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + ((this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>')) -/** - * Filter the keys of the given object with the given `glob` pattern - * and `options`. Does not attempt to match nested keys. If you need this feature, - * use [glob-object][] instead. - * - * ```js - * const mm = require('micromatch'); - * // mm.matchKeys(object, patterns[, options]); - * - * const obj = { aa: 'a', ab: 'b', ac: 'c' }; - * console.log(mm.matchKeys(obj, '*b')); - * //=> { ab: 'b' } - * ``` - * @param {Object} `object` The object with keys to filter. - * @param {String|Array} `patterns` One or more glob patterns to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Object} Returns an object with only keys that match the given patterns. - * @api public - */ + return sameDirectionIncreasing || sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || oppositeDirectionsGreaterThan +} -micromatch.matchKeys = (obj, patterns, options) => { - if (!utils.isObject(obj)) { - throw new TypeError('Expected the first argument to be an object'); +exports.Range = Range +function Range (range, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } } - let keys = micromatch(Object.keys(obj), patterns, options); - let res = {}; - for (let key of keys) res[key] = obj[key]; - return res; -}; - -/** - * Returns true if some of the strings in the given `list` match any of the given glob `patterns`. - * - * ```js - * const mm = require('micromatch'); - * // mm.some(list, patterns[, options]); - * - * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); - * // true - * console.log(mm.some(['foo.js'], ['*.js', '!foo.js'])); - * // false - * ``` - * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found. - * @param {String|Array} `patterns` One or more glob patterns to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Boolean} Returns true if any `patterns` matches any of the strings in `list` - * @api public - */ - -micromatch.some = (list, patterns, options) => { - let items = [].concat(list); - for (let pattern of [].concat(patterns)) { - let isMatch = picomatch(String(pattern), options); - if (items.some(item => isMatch(item))) { - return true; + if (range instanceof Range) { + if (range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease) { + return range + } else { + return new Range(range.raw, options) } } - return false; -}; - -/** - * Returns true if every string in the given `list` matches - * any of the given glob `patterns`. - * - * ```js - * const mm = require('micromatch'); - * // mm.every(list, patterns[, options]); - * - * console.log(mm.every('foo.js', ['foo.js'])); - * // true - * console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); - * // true - * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); - * // false - * console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); - * // false - * ``` - * @param {String|Array} `list` The string or array of strings to test. - * @param {String|Array} `patterns` One or more glob patterns to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Boolean} Returns true if all `patterns` matches all of the strings in `list` - * @api public - */ -micromatch.every = (list, patterns, options) => { - let items = [].concat(list); + if (range instanceof Comparator) { + return new Range(range.value, options) + } - for (let pattern of [].concat(patterns)) { - let isMatch = picomatch(String(pattern), options); - if (!items.every(item => isMatch(item))) { - return false; - } + if (!(this instanceof Range)) { + return new Range(range, options) } - return true; -}; -/** - * Returns true if **all** of the given `patterns` match - * the specified string. - * - * ```js - * const mm = require('micromatch'); - * // mm.all(string, patterns[, options]); - * - * console.log(mm.all('foo.js', ['foo.js'])); - * // true - * - * console.log(mm.all('foo.js', ['*.js', '!foo.js'])); - * // false - * - * console.log(mm.all('foo.js', ['*.js', 'foo.js'])); - * // true - * - * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); - * // true - * ``` - * @param {String|Array} `str` The string to test. - * @param {String|Array} `patterns` One or more glob patterns to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Boolean} Returns true if any patterns match `str` - * @api public - */ + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease -micromatch.all = (str, patterns, options) => { - if (typeof str !== 'string') { - throw new TypeError(`Expected a string: "${util.inspect(str)}"`); - } + // First, split based on boolean or || + this.raw = range + this.set = range.split(/\s*\|\|\s*/).map(function (range) { + return this.parseRange(range.trim()) + }, this).filter(function (c) { + // throw out any that are not relevant for whatever reason + return c.length + }) - return [].concat(patterns).every(p => picomatch(p, options)(str)); -}; + if (!this.set.length) { + throw new TypeError('Invalid SemVer Range: ' + range) + } -/** - * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match. - * - * ```js - * const mm = require('micromatch'); - * // mm.capture(pattern, string[, options]); - * - * console.log(mm.capture('test/*.js', 'test/foo.js')); - * //=> ['foo'] - * console.log(mm.capture('test/*.js', 'foo/bar.css')); - * //=> null - * ``` - * @param {String} `glob` Glob pattern to use for matching. - * @param {String} `input` String to match - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Array|null} Returns an array of captures if the input matches the glob pattern, otherwise `null`. - * @api public - */ + this.format() +} -micromatch.capture = (glob, input, options) => { - let posix = utils.isWindows(options); - let regex = picomatch.makeRe(String(glob), { ...options, capture: true }); - let match = regex.exec(posix ? utils.toPosixSlashes(input) : input); +Range.prototype.format = function () { + this.range = this.set.map(function (comps) { + return comps.join(' ').trim() + }).join('||').trim() + return this.range +} - if (match) { - return match.slice(1).map(v => v === void 0 ? '' : v); - } -}; +Range.prototype.toString = function () { + return this.range +} -/** - * Create a regular expression from the given glob `pattern`. - * - * ```js - * const mm = require('micromatch'); - * // mm.makeRe(pattern[, options]); - * - * console.log(mm.makeRe('*.js')); - * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ - * ``` - * @param {String} `pattern` A glob pattern to convert to regex. - * @param {Object} `options` - * @return {RegExp} Returns a regex created from the given pattern. - * @api public - */ +Range.prototype.parseRange = function (range) { + var loose = this.options.loose + range = range.trim() + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + var hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] + range = range.replace(hr, hyphenReplace) + debug('hyphen replace', range) + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range, re[t.COMPARATORTRIM]) -micromatch.makeRe = (...args) => picomatch.makeRe(...args); + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[t.TILDETRIM], tildeTrimReplace) -/** - * Scan a glob pattern to separate the pattern into segments. Used - * by the [split](#split) method. - * - * ```js - * const mm = require('micromatch'); - * const state = mm.scan(pattern[, options]); - * ``` - * @param {String} `pattern` - * @param {Object} `options` - * @return {Object} Returns an object with - * @api public - */ + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[t.CARETTRIM], caretTrimReplace) -micromatch.scan = (...args) => picomatch.scan(...args); + // normalize spaces + range = range.split(/\s+/).join(' ') -/** - * Parse a glob pattern to create the source string for a regular - * expression. - * - * ```js - * const mm = require('micromatch'); - * const state = mm(pattern[, options]); - * ``` - * @param {String} `glob` - * @param {Object} `options` - * @return {Object} Returns an object with useful properties and output to be used as regex source string. - * @api public - */ + // At this point, the range is completely trimmed and + // ready to be split into comparators. -micromatch.parse = (patterns, options) => { - let res = []; - for (let pattern of [].concat(patterns || [])) { - for (let str of braces(String(pattern), options)) { - res.push(picomatch.parse(str, options)); - } + var compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] + var set = range.split(' ').map(function (comp) { + return parseComparator(comp, this.options) + }, this).join(' ').split(/\s+/) + if (this.options.loose) { + // in loose mode, throw out any that are not valid comparators + set = set.filter(function (comp) { + return !!comp.match(compRe) + }) } - return res; -}; + set = set.map(function (comp) { + return new Comparator(comp, this.options) + }, this) -/** - * Process the given brace `pattern`. - * - * ```js - * const { braces } = require('micromatch'); - * console.log(braces('foo/{a,b,c}/bar')); - * //=> [ 'foo/(a|b|c)/bar' ] - * - * console.log(braces('foo/{a,b,c}/bar', { expand: true })); - * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ] - * ``` - * @param {String} `pattern` String with brace pattern to process. - * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options. - * @return {Array} - * @api public - */ + return set +} -micromatch.braces = (pattern, options) => { - if (typeof pattern !== 'string') throw new TypeError('Expected a string'); - if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) { - return [pattern]; +Range.prototype.intersects = function (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') } - return braces(pattern, options); -}; - -/** - * Expand braces - */ -micromatch.braceExpand = (pattern, options) => { - if (typeof pattern !== 'string') throw new TypeError('Expected a string'); - return micromatch.braces(pattern, { ...options, expand: true }); -}; + return this.set.some(function (thisComparators) { + return ( + isSatisfiable(thisComparators, options) && + range.set.some(function (rangeComparators) { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every(function (thisComparator) { + return rangeComparators.every(function (rangeComparator) { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) +} -/** - * Expose micromatch - */ +// take a set of comparators and determine whether there +// exists a version which can satisfy it +function isSatisfiable (comparators, options) { + var result = true + var remainingComparators = comparators.slice() + var testComparator = remainingComparators.pop() -module.exports = micromatch; + while (result && remainingComparators.length) { + result = remainingComparators.every(function (otherComparator) { + return testComparator.intersects(otherComparator, options) + }) + testComparator = remainingComparators.pop() + } -/***/ }), -/* 815 */ -/***/ (function(module, exports, __webpack_require__) { + return result +} -"use strict"; +// Mostly just for testing and legacy API reasons +exports.toComparators = toComparators +function toComparators (range, options) { + return new Range(range, options).set.map(function (comp) { + return comp.map(function (c) { + return c.value + }).join(' ').trim().split(' ') + }) +} -Object.defineProperty(exports, "__esModule", { value: true }); -exports.merge = void 0; -const merge2 = __webpack_require__(364); -function merge(streams) { - const mergedStream = merge2(streams); - streams.forEach((stream) => { - stream.once('error', (error) => mergedStream.emit('error', error)); - }); - mergedStream.once('close', () => propagateCloseEventToSources(streams)); - mergedStream.once('end', () => propagateCloseEventToSources(streams)); - return mergedStream; +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +function parseComparator (comp, options) { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp } -exports.merge = merge; -function propagateCloseEventToSources(streams) { - streams.forEach((stream) => stream.emit('close')); + +function isX (id) { + return !id || id.toLowerCase() === 'x' || id === '*' } +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 +function replaceTildes (comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceTilde(comp, options) + }).join(' ') +} -/***/ }), -/* 816 */ -/***/ (function(module, exports, __webpack_require__) { +function replaceTilde (comp, options) { + var r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] + return comp.replace(r, function (_, M, m, p, pr) { + debug('tilde', comp, _, M, m, p, pr) + var ret -"use strict"; + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0 + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } else if (pr) { + debug('replaceTilde pr', pr) + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + } else { + // ~1.2.3 == >=1.2.3 <1.3.0 + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0' + } -Object.defineProperty(exports, "__esModule", { value: true }); -exports.isEmpty = exports.isString = void 0; -function isString(input) { - return typeof input === 'string'; + debug('tilde return', ret) + return ret + }) } -exports.isString = isString; -function isEmpty(input) { - return input === ''; + +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 +// ^1.2.3 --> >=1.2.3 <2.0.0 +// ^1.2.0 --> >=1.2.0 <2.0.0 +function replaceCarets (comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceCaret(comp, options) + }).join(' ') } -exports.isEmpty = isEmpty; +function replaceCaret (comp, options) { + debug('caret', comp, options) + var r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] + return comp.replace(r, function (_, M, m, p, pr) { + debug('caret', comp, _, M, m, p, pr) + var ret -/***/ }), -/* 817 */ -/***/ (function(module, exports, __webpack_require__) { + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (isX(p)) { + if (M === '0') { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } else { + ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + m + '.' + (+p + 1) + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + } + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + (+M + 1) + '.0.0' + } + } else { + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + m + '.' + (+p + 1) + } else { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0' + } + } else { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + (+M + 1) + '.0.0' + } + } -"use strict"; + debug('caret return', ret) + return ret + }) +} -Object.defineProperty(exports, "__esModule", { value: true }); -const stream_1 = __webpack_require__(818); -const provider_1 = __webpack_require__(820); -class ProviderAsync extends provider_1.default { - constructor() { - super(...arguments); - this._reader = new stream_1.default(this._settings); - } - read(task) { - const root = this._getRootDirectory(task); - const options = this._getReaderOptions(task); - const entries = []; - return new Promise((resolve, reject) => { - const stream = this.api(root, task, options); - stream.once('error', reject); - stream.on('data', (entry) => entries.push(options.transform(entry))); - stream.once('end', () => resolve(entries)); - }); +function replaceXRanges (comp, options) { + debug('replaceXRanges', comp, options) + return comp.split(/\s+/).map(function (comp) { + return replaceXRange(comp, options) + }).join(' ') +} + +function replaceXRange (comp, options) { + comp = comp.trim() + var r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] + return comp.replace(r, function (ret, gtlt, M, m, p, pr) { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + var xM = isX(M) + var xm = xM || isX(m) + var xp = xm || isX(p) + var anyX = xp + + if (gtlt === '=' && anyX) { + gtlt = '' } - api(root, task, options) { - if (task.dynamic) { - return this._reader.dynamic(root, options); + + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : '' + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0' + } else { + // nothing is forbidden + ret = '*' + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + // >1.2.3 => >= 1.2.4 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 } - return this._reader.static(task.patterns, options); + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 + } + } + + ret = gtlt + M + '.' + m + '.' + p + pr + } else if (xm) { + ret = '>=' + M + '.0.0' + pr + ' <' + (+M + 1) + '.0.0' + pr + } else if (xp) { + ret = '>=' + M + '.' + m + '.0' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + pr } + + debug('xRange return', ret) + + return ret + }) } -exports.default = ProviderAsync; +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +function replaceStars (comp, options) { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[t.STAR], '') +} -/***/ }), -/* 818 */ -/***/ (function(module, exports, __webpack_require__) { +// This function is passed to string.replace(re[t.HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0 +function hyphenReplace ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = '>=' + fM + '.0.0' + } else if (isX(fp)) { + from = '>=' + fM + '.' + fm + '.0' + } else { + from = '>=' + from + } -"use strict"; + if (isX(tM)) { + to = '' + } else if (isX(tm)) { + to = '<' + (+tM + 1) + '.0.0' + } else if (isX(tp)) { + to = '<' + tM + '.' + (+tm + 1) + '.0' + } else if (tpr) { + to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr + } else { + to = '<=' + to + } -Object.defineProperty(exports, "__esModule", { value: true }); -const stream_1 = __webpack_require__(294); -const fsStat = __webpack_require__(410); -const fsWalk = __webpack_require__(415); -const reader_1 = __webpack_require__(819); -class ReaderStream extends reader_1.default { - constructor() { - super(...arguments); - this._walkStream = fsWalk.walkStream; - this._stat = fsStat.stat; - } - dynamic(root, options) { - return this._walkStream(root, options); - } - static(patterns, options) { - const filepaths = patterns.map(this._getFullEntryPath, this); - const stream = new stream_1.PassThrough({ objectMode: true }); - stream._write = (index, _enc, done) => { - return this._getEntry(filepaths[index], patterns[index], options) - .then((entry) => { - if (entry !== null && options.entryFilter(entry)) { - stream.push(entry); - } - if (index === filepaths.length - 1) { - stream.end(); - } - done(); - }) - .catch(done); - }; - for (let i = 0; i < filepaths.length; i++) { - stream.write(i); - } - return stream; - } - _getEntry(filepath, pattern, options) { - return this._getStat(filepath) - .then((stats) => this._makeEntry(stats, pattern)) - .catch((error) => { - if (options.errorFilter(error)) { - return null; - } - throw error; - }); - } - _getStat(filepath) { - return new Promise((resolve, reject) => { - this._stat(filepath, this._fsStatSettings, (error, stats) => { - return error === null ? resolve(stats) : reject(error); - }); - }); + return (from + ' ' + to).trim() +} + +// if ANY of the sets match ALL of its comparators, then pass +Range.prototype.test = function (version) { + if (!version) { + return false + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false } -} -exports.default = ReaderStream; + } + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false +} -/***/ }), -/* 819 */ -/***/ (function(module, exports, __webpack_require__) { +function testSet (set, version, options) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } -"use strict"; + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === ANY) { + continue + } -Object.defineProperty(exports, "__esModule", { value: true }); -const path = __webpack_require__(4); -const fsStat = __webpack_require__(410); -const utils = __webpack_require__(808); -class Reader { - constructor(_settings) { - this._settings = _settings; - this._fsStatSettings = new fsStat.Settings({ - followSymbolicLink: this._settings.followSymbolicLinks, - fs: this._settings.fs, - throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks - }); - } - _getFullEntryPath(filepath) { - return path.resolve(this._settings.cwd, filepath); - } - _makeEntry(stats, pattern) { - const entry = { - name: pattern, - path: pattern, - dirent: utils.fs.createDirentFromStats(pattern, stats) - }; - if (this._settings.stats) { - entry.stats = stats; + if (set[i].semver.prerelease.length > 0) { + var allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true } - return entry; - } - _isFatalError(error) { - return !utils.errno.isEnoentCodeError(error) && !this._settings.suppressErrors; + } } -} -exports.default = Reader; + // Version has a -pre, but it's not one of the ones we like. + return false + } -/***/ }), -/* 820 */ -/***/ (function(module, exports, __webpack_require__) { + return true +} -"use strict"; +exports.satisfies = satisfies +function satisfies (version, range, options) { + try { + range = new Range(range, options) + } catch (er) { + return false + } + return range.test(version) +} -Object.defineProperty(exports, "__esModule", { value: true }); -const path = __webpack_require__(4); -const deep_1 = __webpack_require__(821); -const entry_1 = __webpack_require__(824); -const error_1 = __webpack_require__(825); -const entry_2 = __webpack_require__(826); -class Provider { - constructor(_settings) { - this._settings = _settings; - this.errorFilter = new error_1.default(this._settings); - this.entryFilter = new entry_1.default(this._settings, this._getMicromatchOptions()); - this.deepFilter = new deep_1.default(this._settings, this._getMicromatchOptions()); - this.entryTransformer = new entry_2.default(this._settings); - } - _getRootDirectory(task) { - return path.resolve(this._settings.cwd, task.base); - } - _getReaderOptions(task) { - const basePath = task.base === '.' ? '' : task.base; - return { - basePath, - pathSegmentSeparator: '/', - concurrency: this._settings.concurrency, - deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative), - entryFilter: this.entryFilter.getFilter(task.positive, task.negative), - errorFilter: this.errorFilter.getFilter(), - followSymbolicLinks: this._settings.followSymbolicLinks, - fs: this._settings.fs, - stats: this._settings.stats, - throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink, - transform: this.entryTransformer.getTransformer() - }; - } - _getMicromatchOptions() { - return { - dot: this._settings.dot, - matchBase: this._settings.baseNameMatch, - nobrace: !this._settings.braceExpansion, - nocase: !this._settings.caseSensitiveMatch, - noext: !this._settings.extglob, - noglobstar: !this._settings.globstar, - posix: true, - strictSlashes: false - }; +exports.maxSatisfying = maxSatisfying +function maxSatisfying (versions, range, options) { + var max = null + var maxSV = null + try { + var rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) + } } + }) + return max } -exports.default = Provider; +exports.minSatisfying = minSatisfying +function minSatisfying (versions, range, options) { + var min = null + var minSV = null + try { + var rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) + } + } + }) + return min +} -/***/ }), -/* 821 */ -/***/ (function(module, exports, __webpack_require__) { +exports.minVersion = minVersion +function minVersion (range, loose) { + range = new Range(range, loose) -"use strict"; + var minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver + } -Object.defineProperty(exports, "__esModule", { value: true }); -const utils = __webpack_require__(808); -const partial_1 = __webpack_require__(822); -class DeepFilter { - constructor(_settings, _micromatchOptions) { - this._settings = _settings; - this._micromatchOptions = _micromatchOptions; - } - getFilter(basePath, positive, negative) { - const matcher = this._getMatcher(positive); - const negativeRe = this._getNegativePatternsRe(negative); - return (entry) => this._filter(basePath, entry, matcher, negativeRe); - } - _getMatcher(patterns) { - return new partial_1.default(patterns, this._settings, this._micromatchOptions); - } - _getNegativePatternsRe(patterns) { - const affectDepthOfReadingPatterns = patterns.filter(utils.pattern.isAffectDepthOfReadingPattern); - return utils.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions); - } - _filter(basePath, entry, matcher, negativeRe) { - if (this._isSkippedByDeep(basePath, entry.path)) { - return false; - } - if (this._isSkippedSymbolicLink(entry)) { - return false; - } - const filepath = utils.path.removeLeadingDotSegment(entry.path); - if (this._isSkippedByPositivePatterns(filepath, matcher)) { - return false; - } - return this._isSkippedByNegativePatterns(filepath, negativeRe); - } - _isSkippedByDeep(basePath, entryPath) { - /** - * Avoid unnecessary depth calculations when it doesn't matter. - */ - if (this._settings.deep === Infinity) { - return false; - } - return this._getEntryLevel(basePath, entryPath) >= this._settings.deep; - } - _getEntryLevel(basePath, entryPath) { - const entryPathDepth = entryPath.split('/').length; - if (basePath === '') { - return entryPathDepth; - } - const basePathDepth = basePath.split('/').length; - return entryPathDepth - basePathDepth; - } - _isSkippedSymbolicLink(entry) { - return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink(); - } - _isSkippedByPositivePatterns(entryPath, matcher) { - return !this._settings.baseNameMatch && !matcher.match(entryPath); - } - _isSkippedByNegativePatterns(entryPath, patternsRe) { - return !utils.pattern.matchAny(entryPath, patternsRe); - } -} -exports.default = DeepFilter; + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver + } + minver = null + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] -/***/ }), -/* 822 */ -/***/ (function(module, exports, __webpack_require__) { + comparators.forEach(function (comparator) { + // Clone to avoid manipulating the comparator's semver object. + var compver = new SemVer(comparator.semver.version) + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++ + } else { + compver.prerelease.push(0) + } + compver.raw = compver.format() + /* fallthrough */ + case '': + case '>=': + if (!minver || gt(minver, compver)) { + minver = compver + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error('Unexpected operation: ' + comparator.operator) + } + }) + } -"use strict"; + if (minver && range.test(minver)) { + return minver + } -Object.defineProperty(exports, "__esModule", { value: true }); -const matcher_1 = __webpack_require__(823); -class PartialMatcher extends matcher_1.default { - match(filepath) { - const parts = filepath.split('/'); - const levels = parts.length; - const patterns = this._storage.filter((info) => !info.complete || info.segments.length > levels); - for (const pattern of patterns) { - const section = pattern.sections[0]; - /** - * In this case, the pattern has a globstar and we must read all directories unconditionally, - * but only if the level has reached the end of the first group. - * - * fixtures/{a,b}/** - * ^ true/false ^ always true - */ - if (!pattern.complete && levels > section.length) { - return true; - } - const match = parts.every((part, index) => { - const segment = pattern.segments[index]; - if (segment.dynamic && segment.patternRe.test(part)) { - return true; - } - if (!segment.dynamic && segment.pattern === part) { - return true; - } - return false; - }); - if (match) { - return true; - } - } - return false; - } + return null } -exports.default = PartialMatcher; - -/***/ }), -/* 823 */ -/***/ (function(module, exports, __webpack_require__) { +exports.validRange = validRange +function validRange (range, options) { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null + } +} -"use strict"; +// Determine if version is less than all the versions possible in the range +exports.ltr = ltr +function ltr (version, range, options) { + return outside(version, range, '<', options) +} -Object.defineProperty(exports, "__esModule", { value: true }); -const utils = __webpack_require__(808); -class Matcher { - constructor(_patterns, _settings, _micromatchOptions) { - this._patterns = _patterns; - this._settings = _settings; - this._micromatchOptions = _micromatchOptions; - this._storage = []; - this._fillStorage(); - } - _fillStorage() { - /** - * The original pattern may include `{,*,**,a/*}`, which will lead to problems with matching (unresolved level). - * So, before expand patterns with brace expansion into separated patterns. - */ - const patterns = utils.pattern.expandPatternsWithBraceExpansion(this._patterns); - for (const pattern of patterns) { - const segments = this._getPatternSegments(pattern); - const sections = this._splitSegmentsIntoSections(segments); - this._storage.push({ - complete: sections.length <= 1, - pattern, - segments, - sections - }); - } - } - _getPatternSegments(pattern) { - const parts = utils.pattern.getPatternParts(pattern, this._micromatchOptions); - return parts.map((part) => { - const dynamic = utils.pattern.isDynamicPattern(part, this._settings); - if (!dynamic) { - return { - dynamic: false, - pattern: part - }; - } - return { - dynamic: true, - pattern: part, - patternRe: utils.pattern.makeRe(part, this._micromatchOptions) - }; - }); - } - _splitSegmentsIntoSections(segments) { - return utils.array.splitWhen(segments, (segment) => segment.dynamic && utils.pattern.hasGlobStar(segment.pattern)); - } +// Determine if version is greater than all the versions possible in the range. +exports.gtr = gtr +function gtr (version, range, options) { + return outside(version, range, '>', options) } -exports.default = Matcher; +exports.outside = outside +function outside (version, range, hilo, options) { + version = new SemVer(version, options) + range = new Range(range, options) -/***/ }), -/* 824 */ -/***/ (function(module, exports, __webpack_require__) { + var gtfn, ltefn, ltfn, comp, ecomp + switch (hilo) { + case '>': + gtfn = gt + ltefn = lte + ltfn = lt + comp = '>' + ecomp = '>=' + break + case '<': + gtfn = lt + ltefn = gte + ltfn = gt + comp = '<' + ecomp = '<=' + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } -"use strict"; + // If it satisifes the range it is not outside + if (satisfies(version, range, options)) { + return false + } -Object.defineProperty(exports, "__esModule", { value: true }); -const utils = __webpack_require__(808); -class EntryFilter { - constructor(_settings, _micromatchOptions) { - this._settings = _settings; - this._micromatchOptions = _micromatchOptions; - this.index = new Map(); - } - getFilter(positive, negative) { - const positiveRe = utils.pattern.convertPatternsToRe(positive, this._micromatchOptions); - const negativeRe = utils.pattern.convertPatternsToRe(negative, this._micromatchOptions); - return (entry) => this._filter(entry, positiveRe, negativeRe); - } - _filter(entry, positiveRe, negativeRe) { - if (this._settings.unique && this._isDuplicateEntry(entry)) { - return false; - } - if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) { - return false; - } - if (this._isSkippedByAbsoluteNegativePatterns(entry.path, negativeRe)) { - return false; - } - const filepath = this._settings.baseNameMatch ? entry.name : entry.path; - const isMatched = this._isMatchToPatterns(filepath, positiveRe) && !this._isMatchToPatterns(entry.path, negativeRe); - if (this._settings.unique && isMatched) { - this._createIndexRecord(entry); - } - return isMatched; - } - _isDuplicateEntry(entry) { - return this.index.has(entry.path); - } - _createIndexRecord(entry) { - this.index.set(entry.path, undefined); - } - _onlyFileFilter(entry) { - return this._settings.onlyFiles && !entry.dirent.isFile(); - } - _onlyDirectoryFilter(entry) { - return this._settings.onlyDirectories && !entry.dirent.isDirectory(); - } - _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) { - if (!this._settings.absolute) { - return false; - } - const fullpath = utils.path.makeAbsolute(this._settings.cwd, entryPath); - return utils.pattern.matchAny(fullpath, patternsRe); - } - _isMatchToPatterns(entryPath, patternsRe) { - const filepath = utils.path.removeLeadingDotSegment(entryPath); - return utils.pattern.matchAny(filepath, patternsRe); - } -} -exports.default = EntryFilter; + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] -/***/ }), -/* 825 */ -/***/ (function(module, exports, __webpack_require__) { + var high = null + var low = null -"use strict"; + comparators.forEach(function (comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator + low = low || comparator + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator + } + }) -Object.defineProperty(exports, "__esModule", { value: true }); -const utils = __webpack_require__(808); -class ErrorFilter { - constructor(_settings) { - this._settings = _settings; - } - getFilter() { - return (error) => this._isNonFatalError(error); + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false } - _isNonFatalError(error) { - return utils.errno.isEnoentCodeError(error) || this._settings.suppressErrors; + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false } + } + return true } -exports.default = ErrorFilter; - - -/***/ }), -/* 826 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; +exports.prerelease = prerelease +function prerelease (version, options) { + var parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null +} -Object.defineProperty(exports, "__esModule", { value: true }); -const utils = __webpack_require__(808); -class EntryTransformer { - constructor(_settings) { - this._settings = _settings; - } - getTransformer() { - return (entry) => this._transform(entry); - } - _transform(entry) { - let filepath = entry.path; - if (this._settings.absolute) { - filepath = utils.path.makeAbsolute(this._settings.cwd, filepath); - filepath = utils.path.unixify(filepath); - } - if (this._settings.markDirectories && entry.dirent.isDirectory()) { - filepath += '/'; - } - if (!this._settings.objectMode) { - return filepath; - } - return Object.assign(Object.assign({}, entry), { path: filepath }); - } +exports.intersects = intersects +function intersects (r1, r2, options) { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2) } -exports.default = EntryTransformer; +exports.coerce = coerce +function coerce (version, options) { + if (version instanceof SemVer) { + return version + } -/***/ }), -/* 827 */ -/***/ (function(module, exports, __webpack_require__) { + if (typeof version === 'number') { + version = String(version) + } -"use strict"; + if (typeof version !== 'string') { + return null + } -Object.defineProperty(exports, "__esModule", { value: true }); -const stream_1 = __webpack_require__(294); -const stream_2 = __webpack_require__(818); -const provider_1 = __webpack_require__(820); -class ProviderStream extends provider_1.default { - constructor() { - super(...arguments); - this._reader = new stream_2.default(this._settings); - } - read(task) { - const root = this._getRootDirectory(task); - const options = this._getReaderOptions(task); - const source = this.api(root, task, options); - const destination = new stream_1.Readable({ objectMode: true, read: () => { } }); - source - .once('error', (error) => destination.emit('error', error)) - .on('data', (entry) => destination.emit('data', options.transform(entry))) - .once('end', () => destination.emit('end')); - destination - .once('close', () => source.destroy()); - return destination; - } - api(root, task, options) { - if (task.dynamic) { - return this._reader.dynamic(root, options); - } - return this._reader.static(task.patterns, options); + options = options || {} + + var match = null + if (!options.rtl) { + match = version.match(re[t.COERCE]) + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + var next + while ((next = re[t.COERCERTL].exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next + } + re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length } + // leave it in a clean state + re[t.COERCERTL].lastIndex = -1 + } + + if (match === null) { + return null + } + + return parse(match[2] + + '.' + (match[3] || '0') + + '.' + (match[4] || '0'), options) } -exports.default = ProviderStream; /***/ }), -/* 828 */ +/* 838 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const sync_1 = __webpack_require__(829); -const provider_1 = __webpack_require__(820); -class ProviderSync extends provider_1.default { - constructor() { - super(...arguments); - this._reader = new sync_1.default(this._settings); - } - read(task) { - const root = this._getRootDirectory(task); - const options = this._getReaderOptions(task); - const entries = this.api(root, task, options); - return entries.map(options.transform); - } - api(root, task, options) { - if (task.dynamic) { - return this._reader.dynamic(root, options); - } - return this._reader.static(task.patterns, options); - } -} -exports.default = ProviderSync; +const EventEmitter = __webpack_require__(285); +const written = new WeakMap(); -/***/ }), -/* 829 */ -/***/ (function(module, exports, __webpack_require__) { +class ProgressEmitter extends EventEmitter { + constructor(source, destination) { + super(); + this._source = source; + this._destination = destination; + } -"use strict"; + set written(value) { + written.set(this, value); + this.emitProgress(); + } -Object.defineProperty(exports, "__esModule", { value: true }); -const fsStat = __webpack_require__(410); -const fsWalk = __webpack_require__(415); -const reader_1 = __webpack_require__(819); -class ReaderSync extends reader_1.default { - constructor() { - super(...arguments); - this._walkSync = fsWalk.walkSync; - this._statSync = fsStat.statSync; - } - dynamic(root, options) { - return this._walkSync(root, options); - } - static(patterns, options) { - const entries = []; - for (const pattern of patterns) { - const filepath = this._getFullEntryPath(pattern); - const entry = this._getEntry(filepath, pattern, options); - if (entry === null || !options.entryFilter(entry)) { - continue; - } - entries.push(entry); - } - return entries; - } - _getEntry(filepath, pattern, options) { - try { - const stats = this._getStat(filepath); - return this._makeEntry(stats, pattern); - } - catch (error) { - if (options.errorFilter(error)) { - return null; - } - throw error; - } - } - _getStat(filepath) { - return this._statSync(filepath, this._fsStatSettings); - } + get written() { + return written.get(this); + } + + emitProgress() { + const {size, written} = this; + this.emit('progress', { + src: this._source, + dest: this._destination, + size, + written, + percent: written === size ? 1 : written / size + }); + } } -exports.default = ReaderSync; + +module.exports = ProgressEmitter; /***/ }), -/* 830 */ +/* 839 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0; -const fs = __webpack_require__(253); -const os = __webpack_require__(243); -/** - * The `os.cpus` method can return zero. We expect the number of cores to be greater than zero. - * https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107 - */ -const CPU_COUNT = Math.max(os.cpus().length, 1); -exports.DEFAULT_FILE_SYSTEM_ADAPTER = { - lstat: fs.lstat, - lstatSync: fs.lstatSync, - stat: fs.stat, - statSync: fs.statSync, - readdir: fs.readdir, - readdirSync: fs.readdirSync -}; -class Settings { - constructor(_options = {}) { - this._options = _options; - this.absolute = this._getValue(this._options.absolute, false); - this.baseNameMatch = this._getValue(this._options.baseNameMatch, false); - this.braceExpansion = this._getValue(this._options.braceExpansion, true); - this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true); - this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT); - this.cwd = this._getValue(this._options.cwd, process.cwd()); - this.deep = this._getValue(this._options.deep, Infinity); - this.dot = this._getValue(this._options.dot, false); - this.extglob = this._getValue(this._options.extglob, true); - this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true); - this.fs = this._getFileSystemMethods(this._options.fs); - this.globstar = this._getValue(this._options.globstar, true); - this.ignore = this._getValue(this._options.ignore, []); - this.markDirectories = this._getValue(this._options.markDirectories, false); - this.objectMode = this._getValue(this._options.objectMode, false); - this.onlyDirectories = this._getValue(this._options.onlyDirectories, false); - this.onlyFiles = this._getValue(this._options.onlyFiles, true); - this.stats = this._getValue(this._options.stats, false); - this.suppressErrors = this._getValue(this._options.suppressErrors, false); - this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false); - this.unique = this._getValue(this._options.unique, true); - if (this.onlyDirectories) { - this.onlyFiles = false; - } - if (this.stats) { - this.objectMode = true; - } - } - _getValue(option, value) { - return option === undefined ? value : option; - } - _getFileSystemMethods(methods = {}) { - return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods); - } -} -exports.default = Settings; - -/***/ }), -/* 831 */ -/***/ (function(module, exports, __webpack_require__) { +const blacklist = [ + // # All + '^npm-debug\\.log$', // Error log for npm + '^\\..*\\.swp$', // Swap file for vim state -"use strict"; + // # macOS + '^\\.DS_Store$', // Stores custom folder attributes + '^\\.AppleDouble$', // Stores additional file resources + '^\\.LSOverride$', // Contains the absolute path to the app to be used + '^Icon\\r$', // Custom Finder icon: http://superuser.com/questions/298785/icon-file-on-os-x-desktop + '^\\._.*', // Thumbnail + '^\\.Spotlight-V100(?:$|\\/)', // Directory that might appear on external disk + '\\.Trashes', // File that might appear on external disk + '^__MACOSX$', // Resource fork -const {promisify} = __webpack_require__(234); -const fs = __webpack_require__(253); -const path = __webpack_require__(4); -const fastGlob = __webpack_require__(806); -const gitIgnore = __webpack_require__(450); -const slash = __webpack_require__(451); + // # Linux + '~$', // Backup file -const DEFAULT_IGNORE = [ - '**/node_modules/**', - '**/flow-typed/**', - '**/coverage/**', - '**/.git' + // # Windows + '^Thumbs\\.db$', // Image file cache + '^ehthumbs\\.db$', // Folder config file + '^Desktop\\.ini$', // Stores custom folder attributes + '@eaDir$' // Synology Diskstation "hidden" folder where the server stores thumbnails ]; -const readFileP = promisify(fs.readFile); +exports.re = () => { + throw new Error('`junk.re` was renamed to `junk.regex`'); +}; -const mapGitIgnorePatternTo = base => ignore => { - if (ignore.startsWith('!')) { - return '!' + path.posix.join(base, ignore.slice(1)); - } +exports.regex = new RegExp(blacklist.join('|')); - return path.posix.join(base, ignore); -}; +exports.is = filename => exports.regex.test(filename); -const parseGitIgnore = (content, options) => { - const base = slash(path.relative(options.cwd, path.dirname(options.fileName))); +exports.not = filename => !exports.is(filename); - return content - .split(/\r?\n/) - .filter(Boolean) - .filter(line => !line.startsWith('#')) - .map(mapGitIgnorePatternTo(base)); -}; +// TODO: Remove this for the next major release +exports.default = module.exports; -const reduceIgnore = files => { - const ignores = gitIgnore(); - for (const file of files) { - ignores.add(parseGitIgnore(file.content, { - cwd: file.cwd, - fileName: file.filePath - })); - } - return ignores; -}; +/***/ }), +/* 840 */ +/***/ (function(module, exports, __webpack_require__) { -const ensureAbsolutePathForCwd = (cwd, p) => { - cwd = slash(cwd); - if (path.isAbsolute(p)) { - if (slash(p).startsWith(cwd)) { - return p; - } +"use strict"; - throw new Error(`Path ${p} is not in cwd ${cwd}`); - } +const pMap = __webpack_require__(841); - return path.join(cwd, p); +const pFilter = async (iterable, filterer, options) => { + const values = await pMap( + iterable, + (element, index) => Promise.all([filterer(element, index), element]), + options + ); + return values.filter(value => Boolean(value[0])).map(value => value[1]); }; -const getIsIgnoredPredecate = (ignores, cwd) => { - return p => ignores.ignores(slash(path.relative(cwd, ensureAbsolutePathForCwd(cwd, p.path || p)))); -}; +module.exports = pFilter; +// TODO: Remove this for the next major release +module.exports.default = pFilter; -const getFile = async (file, cwd) => { - const filePath = path.join(cwd, file); - const content = await readFileP(filePath, 'utf8'); - return { - cwd, - filePath, - content - }; -}; +/***/ }), +/* 841 */ +/***/ (function(module, exports, __webpack_require__) { -const getFileSync = (file, cwd) => { - const filePath = path.join(cwd, file); - const content = fs.readFileSync(filePath, 'utf8'); +"use strict"; - return { - cwd, - filePath, - content - }; -}; -const normalizeOptions = ({ - ignore = [], - cwd = slash(process.cwd()) -} = {}) => { - return {ignore, cwd}; -}; +const pMap = (iterable, mapper, options) => new Promise((resolve, reject) => { + options = Object.assign({ + concurrency: Infinity + }, options); -module.exports = async options => { - options = normalizeOptions(options); + if (typeof mapper !== 'function') { + throw new TypeError('Mapper function is required'); + } - const paths = await fastGlob('**/.gitignore', { - ignore: DEFAULT_IGNORE.concat(options.ignore), - cwd: options.cwd - }); + const {concurrency} = options; - const files = await Promise.all(paths.map(file => getFile(file, options.cwd))); - const ignores = reduceIgnore(files); + if (!(typeof concurrency === 'number' && concurrency >= 1)) { + throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${concurrency}\` (${typeof concurrency})`); + } - return getIsIgnoredPredecate(ignores, options.cwd); -}; + const ret = []; + const iterator = iterable[Symbol.iterator](); + let isRejected = false; + let isIterableDone = false; + let resolvingCount = 0; + let currentIndex = 0; -module.exports.sync = options => { - options = normalizeOptions(options); + const next = () => { + if (isRejected) { + return; + } - const paths = fastGlob.sync('**/.gitignore', { - ignore: DEFAULT_IGNORE.concat(options.ignore), - cwd: options.cwd - }); + const nextItem = iterator.next(); + const i = currentIndex; + currentIndex++; - const files = paths.map(file => getFileSync(file, options.cwd)); - const ignores = reduceIgnore(files); + if (nextItem.done) { + isIterableDone = true; - return getIsIgnoredPredecate(ignores, options.cwd); -}; + if (resolvingCount === 0) { + resolve(ret); + } + return; + } -/***/ }), -/* 832 */ -/***/ (function(module, exports, __webpack_require__) { + resolvingCount++; -"use strict"; + Promise.resolve(nextItem.value) + .then(element => mapper(element, i)) + .then( + value => { + ret[i] = value; + resolvingCount--; + next(); + }, + error => { + isRejected = true; + reject(error); + } + ); + }; -const {Transform} = __webpack_require__(294); + for (let i = 0; i < concurrency; i++) { + next(); -class ObjectTransform extends Transform { - constructor() { - super({ - objectMode: true - }); + if (isIterableDone) { + break; + } } -} +}); -class FilterStream extends ObjectTransform { - constructor(filter) { - super(); - this._filter = filter; - } +module.exports = pMap; +// TODO: Remove this for the next major release +module.exports.default = pMap; - _transform(data, encoding, callback) { - if (this._filter(data)) { - this.push(data); - } - callback(); - } -} +/***/ }), +/* 842 */ +/***/ (function(module, exports, __webpack_require__) { -class UniqueStream extends ObjectTransform { - constructor() { - super(); - this._pushed = new Set(); - } +"use strict"; - _transform(data, encoding, callback) { - if (!this._pushed.has(data)) { - this.push(data); - this._pushed.add(data); - } +const NestedError = __webpack_require__(834); - callback(); +class CpyError extends NestedError { + constructor(message, nested) { + super(message, nested); + Object.assign(this, nested); + this.name = 'CpyError'; } } -module.exports = { - FilterStream, - UniqueStream -}; +module.exports = CpyError; /***/ }), -/* 833 */ +/* 843 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -88403,13 +88823,13 @@ __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "buildNonBazelProductionProjects", function() { return buildNonBazelProductionProjects; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getProductionProjects", function() { return getProductionProjects; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "buildProject", function() { return buildProject; }); -/* harmony import */ var cpy__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(593); +/* harmony import */ var cpy__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(631); /* harmony import */ var cpy__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(cpy__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var del__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(361); /* harmony import */ var del__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(del__WEBPACK_IMPORTED_MODULE_1__); /* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4); /* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(590); +/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(628); /* harmony import */ var _utils_fs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(352); /* harmony import */ var _utils_log__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(341); /* harmony import */ var _utils_package_json__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(464); diff --git a/packages/kbn-pm/src/commands/bootstrap.ts b/packages/kbn-pm/src/commands/bootstrap.ts index a1dd4d38cfb8a..5b6f4fe3baeb7 100644 --- a/packages/kbn-pm/src/commands/bootstrap.ts +++ b/packages/kbn-pm/src/commands/bootstrap.ts @@ -13,9 +13,8 @@ import { log } from '../utils/log'; import { spawnStreaming } from '../utils/child_process'; import { linkProjectExecutables } from '../utils/link_project_executables'; import { getNonBazelProjectsOnly, topologicallyBatchProjects } from '../utils/projects'; -import { ICommand } from './'; +import { ICommand } from '.'; import { readYarnLock } from '../utils/yarn_lock'; -import { sortPackageJson } from '../utils/sort_package_json'; import { validateDependencies } from '../utils/validate_dependencies'; import { installBazelTools, removeYarnIntegrityFileIfExists, runBazel } from '../utils/bazel'; import { setupRemoteCache } from '../utils/bazel/setup_remote_cache'; @@ -114,10 +113,6 @@ export const BootstrapCommand: ICommand = { } } - await time('sort package json', async () => { - await sortPackageJson(kbn); - }); - const yarnLock = await time('read yarn.lock', async () => await readYarnLock(kbn)); if (options.validate) { diff --git a/packages/kbn-pm/src/run.test.ts b/packages/kbn-pm/src/run.test.ts index 305f79947fcbb..5584c35619ba9 100644 --- a/packages/kbn-pm/src/run.test.ts +++ b/packages/kbn-pm/src/run.test.ts @@ -15,7 +15,11 @@ import { log } from './utils/log'; log.setLogLevel('silent'); -const rootPath = resolve(`${__dirname}/utils/__fixtures__/kibana`); +const rootPath = resolve(__dirname, 'utils/__fixtures__/kibana'); + +jest.mock('./utils/regenerate_package_json'); +jest.mock('./utils/regenerate_synthetic_package_map'); +jest.mock('./utils/regenerate_base_tsconfig'); function getExpectedProjectsAndGraph(runMock: any) { const [fullProjects, fullProjectGraph] = (runMock as jest.Mock).mock.calls[0]; diff --git a/packages/kbn-pm/src/run.ts b/packages/kbn-pm/src/run.ts index 41d26e26a3c29..559fcbcf8b668 100644 --- a/packages/kbn-pm/src/run.ts +++ b/packages/kbn-pm/src/run.ts @@ -6,25 +6,98 @@ * Side Public License, v 1. */ -import { CiStatsReporter } from '@kbn/dev-utils/ci_stats_reporter'; +import { CiStatsReporter, CiStatsTiming } from '@kbn/dev-utils/ci_stats_reporter'; +import { simpleKibanaPlatformPluginDiscovery, getPluginSearchPaths } from '@kbn/plugin-discovery'; import { ICommand, ICommandConfig } from './commands'; import { CliError } from './utils/errors'; import { log } from './utils/log'; import { buildProjectGraph } from './utils/projects'; import { renderProjectsTree } from './utils/projects_tree'; +import { regeneratePackageJson } from './utils/regenerate_package_json'; +import { regenerateSyntheticPackageMap } from './utils/regenerate_synthetic_package_map'; +import { regenerateBaseTsconfig } from './utils/regenerate_base_tsconfig'; import { Kibana } from './utils/kibana'; process.env.CI_STATS_NESTED_TIMING = 'true'; export async function runCommand(command: ICommand, config: Omit) { const runStartTime = Date.now(); - let kbn; + let kbn: undefined | Kibana; + const timings: Array> = []; + async function time(id: string, block: () => Promise): Promise { + const start = Date.now(); + let success = true; + try { + return await block(); + } catch (error) { + success = false; + throw error; + } finally { + timings.push({ + id, + ms: Date.now() - start, + meta: { + success, + }, + }); + } + } + + async function reportTimes(timingConfig: { group: string; id: string }, error?: Error) { + if (!kbn) { + // things are too broken to report remotely + return; + } + + const reporter = CiStatsReporter.fromEnv(log); + + try { + await reporter.timings({ + upstreamBranch: kbn.kibanaProject.json.branch, + // prevent loading @kbn/utils by passing null + kibanaUuid: kbn.getUuid() || null, + timings: [ + ...timings.map((t) => ({ ...timingConfig, ...t })), + { + group: timingConfig.group, + id: timingConfig.id, + ms: Date.now() - runStartTime, + meta: { + success: !error, + }, + }, + ], + }); + } catch (e) { + // prevent hiding bootstrap errors + log.error('failed to report timings:'); + log.error(e); + } + } try { log.debug(`Running [${command.name}] command from [${config.rootPath}]`); - kbn = await Kibana.loadFrom(config.rootPath); + await time('regenerate package.json, synthetic-package map and tsconfig', async () => { + const plugins = simpleKibanaPlatformPluginDiscovery( + getPluginSearchPaths({ + rootDir: config.rootPath, + oss: false, + examples: true, + testPlugins: true, + }), + [] + ); + + await Promise.all([ + regeneratePackageJson(config.rootPath), + regenerateSyntheticPackageMap(plugins, config.rootPath), + regenerateBaseTsconfig(plugins, config.rootPath), + ]); + }); + + kbn = await time('load Kibana project', async () => await Kibana.loadFrom(config.rootPath)); const projects = kbn.getFilteredProjects({ skipKibanaPlugins: Boolean(config.options['skip-kibana-plugins']), ossOnly: Boolean(config.options.oss), @@ -50,50 +123,11 @@ export async function runCommand(command: ICommand, config: Omit (c.toUpperCase() === c ? `-${c.toLowerCase()}` : c)) + .join('')}-plugin` + .replace(/-\w(-\w)+-/g, (match) => `-${match.split('-').join('')}-`) + .replace(/-plugin-plugin$/, '-plugin'); +} diff --git a/packages/kbn-pm/src/utils/regenerate_base_tsconfig.ts b/packages/kbn-pm/src/utils/regenerate_base_tsconfig.ts new file mode 100644 index 0000000000000..48a7735937e92 --- /dev/null +++ b/packages/kbn-pm/src/utils/regenerate_base_tsconfig.ts @@ -0,0 +1,35 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import Fs from 'fs/promises'; +import Path from 'path'; + +import { KibanaPlatformPlugin } from '@kbn/plugin-discovery'; +import { convertPluginIdToPackageId } from './convert_plugin_id_to_package_id'; + +export async function regenerateBaseTsconfig(plugins: KibanaPlatformPlugin[], repoRoot: string) { + const tsconfigPath = Path.resolve(repoRoot, 'tsconfig.base.json'); + const lines = (await Fs.readFile(tsconfigPath, 'utf-8')).split('\n'); + + const packageMap = plugins + .slice() + .sort((a, b) => a.manifestPath.localeCompare(b.manifestPath)) + .flatMap((p) => { + const id = convertPluginIdToPackageId(p.manifest.id); + const path = Path.relative(repoRoot, p.directory); + return [` "${id}": ["${path}"],`, ` "${id}/*": ["${path}/*"],`]; + }); + + const start = lines.findIndex((l) => l.trim() === '// START AUTOMATED PACKAGE LISTING'); + const end = lines.findIndex((l) => l.trim() === '// END AUTOMATED PACKAGE LISTING'); + + await Fs.writeFile( + tsconfigPath, + [...lines.slice(0, start + 1), ...packageMap, ...lines.slice(end)].join('\n') + ); +} diff --git a/packages/kbn-pm/src/utils/regenerate_package_json.ts b/packages/kbn-pm/src/utils/regenerate_package_json.ts new file mode 100644 index 0000000000000..88460132df2a6 --- /dev/null +++ b/packages/kbn-pm/src/utils/regenerate_package_json.ts @@ -0,0 +1,18 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import Fsp from 'fs/promises'; +import Path from 'path'; + +import { sortPackageJson } from '@kbn/dev-utils/sort_package_json'; + +export async function regeneratePackageJson(rootPath: string) { + const path = Path.resolve(rootPath, 'package.json'); + const json = await Fsp.readFile(path, 'utf8'); + await Fsp.writeFile(path, sortPackageJson(json)); +} diff --git a/packages/kbn-pm/src/utils/regenerate_synthetic_package_map.ts b/packages/kbn-pm/src/utils/regenerate_synthetic_package_map.ts new file mode 100644 index 0000000000000..c502e11f1a3c8 --- /dev/null +++ b/packages/kbn-pm/src/utils/regenerate_synthetic_package_map.ts @@ -0,0 +1,33 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import Fs from 'fs/promises'; +import Path from 'path'; + +import normalizePath from 'normalize-path'; +import { KibanaPlatformPlugin } from '@kbn/plugin-discovery'; +import { convertPluginIdToPackageId } from './convert_plugin_id_to_package_id'; + +export async function regenerateSyntheticPackageMap( + plugins: KibanaPlatformPlugin[], + repoRoot: string +) { + const entries: Array<[string, string]> = [['@kbn/core', 'src/core']]; + + for (const plugin of plugins) { + entries.push([ + convertPluginIdToPackageId(plugin.manifest.id), + normalizePath(Path.relative(repoRoot, plugin.directory)), + ]); + } + + await Fs.writeFile( + Path.resolve(repoRoot, 'packages/kbn-synthetic-package-map/synthetic-packages.json'), + JSON.stringify(entries, null, 2) + ); +} diff --git a/packages/kbn-pm/src/utils/watch.test.ts b/packages/kbn-pm/src/utils/watch.test.ts deleted file mode 100644 index e310557cf209f..0000000000000 --- a/packages/kbn-pm/src/utils/watch.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import { EventEmitter } from 'events'; -import { waitUntilWatchIsReady } from './watch'; - -describe('#waitUntilWatchIsReady', () => { - let buildOutputStream: EventEmitter; - let completionHintPromise: Promise; - beforeEach(() => { - jest.useFakeTimers(); - - buildOutputStream = new EventEmitter(); - completionHintPromise = waitUntilWatchIsReady(buildOutputStream, { - handlerDelay: 100, - handlerReadinessTimeout: 50, - }); - }); - - test('`waitUntilWatchIsReady` correctly handles `webpack` output', async () => { - buildOutputStream.emit('data', Buffer.from('$ webpack')); - buildOutputStream.emit('data', Buffer.from('Chunk Names')); - - jest.runAllTimers(); - - expect(await completionHintPromise).toBe('webpack'); - }); - - test('`waitUntilWatchIsReady` correctly handles `tsc` output', async () => { - buildOutputStream.emit('data', Buffer.from('$ tsc')); - buildOutputStream.emit('data', Buffer.from('Compilation complete.')); - - jest.runAllTimers(); - - expect(await completionHintPromise).toBe('tsc'); - }); - - test('`waitUntilWatchIsReady` fallbacks to default output handler if output is not recognizable', async () => { - buildOutputStream.emit('data', Buffer.from('$ some-cli')); - buildOutputStream.emit('data', Buffer.from('Compilation complete.')); - buildOutputStream.emit('data', Buffer.from('Chunk Names.')); - - jest.runAllTimers(); - - expect(await completionHintPromise).toBe('timeout'); - }); - - test('`waitUntilWatchIsReady` fallbacks to default output handler if none output is detected', async () => { - jest.runAllTimers(); - expect(await completionHintPromise).toBe('timeout'); - }); - - test('`waitUntilWatchIsReady` fails if output stream receives error', async () => { - buildOutputStream.emit('error', new Error('Uh, oh!')); - - jest.runAllTimers(); - - await expect(completionHintPromise).rejects.toThrow(/Uh, oh!/); - }); -}); diff --git a/packages/kbn-storybook/src/webpack.config.ts b/packages/kbn-storybook/src/webpack.config.ts index 4da3c58688f75..7f4821767cd9c 100644 --- a/packages/kbn-storybook/src/webpack.config.ts +++ b/packages/kbn-storybook/src/webpack.config.ts @@ -140,13 +140,13 @@ export default ({ config: storybookConfig }: { config: Configuration }) => { const options = (loader.options = { ...(loader.options as Record) }); // capture the plugins defined at the root level - const plugins: string[] = options.plugins; + const plugins: string[] = options.plugins ?? []; options.plugins = []; // move the plugins to the top of the preset array so they will run after the typescript preset options.presets = [ { - plugins, + plugins: [...plugins, require.resolve('@kbn/babel-plugin-synthetic-packages')], }, ...(options.presets as Preset[]).filter(isDesiredPreset).map((preset) => { const tsPreset = getTsPreset(preset); diff --git a/packages/kbn-synthetic-package-map/BUILD.bazel b/packages/kbn-synthetic-package-map/BUILD.bazel new file mode 100644 index 0000000000000..6b1d32fcbbb1e --- /dev/null +++ b/packages/kbn-synthetic-package-map/BUILD.bazel @@ -0,0 +1,51 @@ +load("@npm//@bazel/typescript:index.bzl", "ts_config") +load("@build_bazel_rules_nodejs//:index.bzl", "js_library") +load("//src/dev/bazel:index.bzl", "jsts_transpiler", "pkg_npm", "pkg_npm_types", "ts_project") + +PKG_DIRNAME = "kbn-synthetic-package-map" +PKG_REQUIRE_NAME = "@kbn/synthetic-package-map" + +NPM_MODULE_EXTRA_FILES = [ + "package.json", + "index.js", + "index.d.ts", + "synthetic-packages.json", +] + +# In this array place runtime dependencies, including other packages and NPM packages +# which must be available for this code to run. +# +# To reference other packages use: +# "//repo/relative/path/to/package" +# eg. "//packages/kbn-utils" +# +# To reference a NPM package use: +# "@npm//name-of-package" +# eg. "@npm//lodash" +RUNTIME_DEPS = [ +] + +js_library( + name = PKG_DIRNAME, + srcs = NPM_MODULE_EXTRA_FILES, + deps = RUNTIME_DEPS, + package_name = PKG_REQUIRE_NAME, + visibility = ["//visibility:public"], +) + +pkg_npm( + name = "npm_module", + deps = [":" + PKG_DIRNAME], +) + +filegroup( + name = "build", + srcs = [":npm_module"], + visibility = ["//visibility:public"], +) + +alias( + name = "npm_module_types", + actual = ":" + PKG_DIRNAME, + visibility = ["//visibility:public"], +) diff --git a/packages/kbn-synthetic-package-map/index.d.ts b/packages/kbn-synthetic-package-map/index.d.ts new file mode 100644 index 0000000000000..92724eed486b1 --- /dev/null +++ b/packages/kbn-synthetic-package-map/index.d.ts @@ -0,0 +1,18 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +export type PackageMap = Map; + +/** + * Read the package map from disk + */ +export function readPackageMap(): PackageMap; +/** + * Read the package map and calculate a cache key/hash of the package map + */ +export function readHashOfPackageMap(): string; diff --git a/packages/kbn-synthetic-package-map/index.js b/packages/kbn-synthetic-package-map/index.js new file mode 100644 index 0000000000000..9a9b8c51d90a9 --- /dev/null +++ b/packages/kbn-synthetic-package-map/index.js @@ -0,0 +1,26 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +const Fs = require('fs'); +const Path = require('path'); +const Crypto = require('crypto'); + +const PACKAGE_MAP_PATH = Path.resolve(__dirname, 'synthetic-packages.json'); + +function readPackageMap() { + return new Map(JSON.parse(Fs.readFileSync(PACKAGE_MAP_PATH, 'utf8'))); +} + +function readHashOfPackageMap() { + return Crypto.createHash('sha256').update(Fs.readFileSync(PACKAGE_MAP_PATH)).digest('hex'); +} + +module.exports = { + readPackageMap, + readHashOfPackageMap, +}; diff --git a/packages/kbn-synthetic-package-map/package.json b/packages/kbn-synthetic-package-map/package.json new file mode 100644 index 0000000000000..ae209fdf98db0 --- /dev/null +++ b/packages/kbn-synthetic-package-map/package.json @@ -0,0 +1,10 @@ +{ + "name": "@kbn/synthetic-package-map", + "private": true, + "version": "1.0.0", + "main": "./index.js", + "license": "SSPL-1.0 OR Elastic License 2.0", + "kibana": { + "devOnly": true + } +} diff --git a/packages/kbn-synthetic-package-map/tsconfig.json b/packages/kbn-synthetic-package-map/tsconfig.json new file mode 100644 index 0000000000000..7b74a1e555c86 --- /dev/null +++ b/packages/kbn-synthetic-package-map/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "../../tsconfig.bazel.json", + "compilerOptions": { + "declaration": true, + "emitDeclarationOnly": true, + "outDir": "target_types", + "stripInternal": false, + "types": [ + "node" + ] + }, + "include": [ + "index.d.ts" + ] +} diff --git a/packages/kbn-telemetry-tools/BUILD.bazel b/packages/kbn-telemetry-tools/BUILD.bazel index 50336dc44da00..1c9f6113851ff 100644 --- a/packages/kbn-telemetry-tools/BUILD.bazel +++ b/packages/kbn-telemetry-tools/BUILD.bazel @@ -31,7 +31,9 @@ NPM_MODULE_EXTRA_FILES = [ RUNTIME_DEPS = [ "//packages/kbn-dev-utils", + "//packages/kbn-eslint-plugin-imports", "//packages/kbn-utility-types", + "//packages/kbn-utils", "@npm//glob", "@npm//listr", "@npm//normalize-path", @@ -39,7 +41,9 @@ RUNTIME_DEPS = [ TYPES_DEPS = [ "//packages/kbn-dev-utils:npm_module_types", + "//packages/kbn-eslint-plugin-imports:npm_module_types", "//packages/kbn-utility-types:npm_module_types", + "//packages/kbn-utils:npm_module_types", "@npm//tslib", "@npm//@types/glob", "@npm//@types/jest", diff --git a/packages/kbn-telemetry-tools/src/tools/compiler_host.ts b/packages/kbn-telemetry-tools/src/tools/compiler_host.ts new file mode 100644 index 0000000000000..a49bee64e5642 --- /dev/null +++ b/packages/kbn-telemetry-tools/src/tools/compiler_host.ts @@ -0,0 +1,59 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import Path from 'path'; + +import ts from 'typescript'; +import { REPO_ROOT } from '@kbn/utils'; +import { ImportResolver } from '@kbn/import-resolver'; + +function readTsConfigFile(path: string) { + const json = ts.readConfigFile(path, ts.sys.readFile); + + if (json.error) { + throw new Error(`Unable to load tsconfig file: ${json.error.messageText}`); + } + + return json.config; +} + +function loadTsConfigFile(path: string) { + return ts.parseJsonConfigFileContent(readTsConfigFile(path) ?? {}, ts.sys, Path.dirname(path)); +} + +const baseTsConfig = loadTsConfigFile(Path.resolve(REPO_ROOT, 'tsconfig.base.json')); +const resolver = ImportResolver.create(REPO_ROOT); + +function isTsCompatible(path: string) { + const extname = Path.extname(path); + return extname === '.ts' || extname === '.tsx' || extname === '.js'; +} + +export const compilerHost: ts.CompilerHost = { + ...ts.createCompilerHost(baseTsConfig.options), + + resolveModuleNames(moduleNames, sourceFilePath) { + const dirname = Path.dirname(sourceFilePath); + + const results: Array = []; + + for (const req of moduleNames) { + const result = resolver.resolve(req, dirname); + if (result?.type !== 'file' || !isTsCompatible(result.absolute)) { + results.push(undefined); + } else { + results.push({ + resolvedFileName: result.absolute, + isExternalLibraryImport: !!result.nodeModule, + }); + } + } + + return results; + }, +}; diff --git a/packages/kbn-telemetry-tools/src/tools/extract_collectors.ts b/packages/kbn-telemetry-tools/src/tools/extract_collectors.ts index 9655b397c8d1d..aa69abc555b18 100644 --- a/packages/kbn-telemetry-tools/src/tools/extract_collectors.ts +++ b/packages/kbn-telemetry-tools/src/tools/extract_collectors.ts @@ -11,6 +11,7 @@ import * as path from 'path'; import { parseUsageCollection } from './ts_parser'; import { globAsync } from './utils'; import { TelemetryRC } from './config'; +import { compilerHost } from './compiler_host'; export async function getProgramPaths({ root, @@ -48,7 +49,7 @@ export async function getProgramPaths({ } export function* extractCollectors(fullPaths: string[], tsConfig: any) { - const program = ts.createProgram(fullPaths, tsConfig); + const program = ts.createProgram(fullPaths, tsConfig, compilerHost); program.getTypeChecker(); const sourceFiles = fullPaths.map((fullPath) => { const sourceFile = program.getSourceFile(fullPath); diff --git a/packages/kbn-telemetry-tools/src/tools/serializer.test.ts b/packages/kbn-telemetry-tools/src/tools/serializer.test.ts index 3398cd0ae6947..5661db270186c 100644 --- a/packages/kbn-telemetry-tools/src/tools/serializer.test.ts +++ b/packages/kbn-telemetry-tools/src/tools/serializer.test.ts @@ -10,6 +10,7 @@ import * as ts from 'typescript'; import * as path from 'path'; import { getDescriptor, TelemetryKinds } from './serializer'; import { traverseNodes } from './ts_parser'; +import { compilerHost } from './compiler_host'; export function loadFixtureProgram(fixtureName: string) { const fixturePath = path.resolve( @@ -23,7 +24,7 @@ export function loadFixtureProgram(fixtureName: string) { if (!tsConfig) { throw new Error('Could not find a valid tsconfig.json.'); } - const program = ts.createProgram([fixturePath], tsConfig as any); + const program = ts.createProgram([fixturePath], tsConfig as any, compilerHost); const checker = program.getTypeChecker(); const sourceFile = program.getSourceFile(fixturePath); if (!sourceFile) { diff --git a/packages/kbn-telemetry-tools/src/tools/ts_parser.test.ts b/packages/kbn-telemetry-tools/src/tools/ts_parser.test.ts index 4a58e3fc1101b..205ab6594fda6 100644 --- a/packages/kbn-telemetry-tools/src/tools/ts_parser.test.ts +++ b/packages/kbn-telemetry-tools/src/tools/ts_parser.test.ts @@ -9,6 +9,7 @@ import { parseUsageCollection } from './ts_parser'; import * as ts from 'typescript'; import * as path from 'path'; +import { compilerHost } from './compiler_host'; import { parsedWorkingCollector } from './__fixture__/parsed_working_collector'; import { parsedNestedCollector } from './__fixture__/parsed_nested_collector'; import { parsedExternallyDefinedCollector } from './__fixture__/parsed_externally_defined_collector'; @@ -30,7 +31,7 @@ export function loadFixtureProgram(fixtureName: string) { if (!tsConfig) { throw new Error('Could not find a valid tsconfig.json.'); } - const program = ts.createProgram([fixturePath], tsConfig as any); + const program = ts.createProgram([fixturePath], tsConfig as any, compilerHost); const checker = program.getTypeChecker(); const sourceFile = program.getSourceFile(fixturePath); if (!sourceFile) { diff --git a/packages/kbn-telemetry-tools/src/tools/utils.ts b/packages/kbn-telemetry-tools/src/tools/utils.ts index c9526fe7d0403..074f9ff2d5f29 100644 --- a/packages/kbn-telemetry-tools/src/tools/utils.ts +++ b/packages/kbn-telemetry-tools/src/tools/utils.ts @@ -154,6 +154,12 @@ export function getResolvedModuleSourceFile( importedModuleName: string ) { const resolvedModule = (originalSource as any).resolvedModules.get(importedModuleName); + if (!resolvedModule) { + throw new Error( + `Import for [${importedModuleName}] in [${originalSource.fileName}] could not be resolved by TypeScript` + ); + } + const resolvedModuleSourceFile = program.getSourceFile(resolvedModule.resolvedFileName); if (!resolvedModuleSourceFile) { throw new Error(`Unable to find resolved module ${importedModuleName}`); diff --git a/packages/kbn-test/jest-preset.js b/packages/kbn-test/jest-preset.js index 1021283936495..6245532b00e44 100644 --- a/packages/kbn-test/jest-preset.js +++ b/packages/kbn-test/jest-preset.js @@ -9,6 +9,8 @@ // For a detailed explanation regarding each configuration property, visit: // https://jestjs.io/docs/en/configuration.html +const pkgMap = require('@kbn/synthetic-package-map').readPackageMap(); + /** @typedef {import("@jest/types").Config.InitialOptions} JestConfig */ /** @type {JestConfig} */ module.exports = { @@ -36,13 +38,17 @@ module.exports = { '\\.(css|less|scss)$': '/node_modules/@kbn/test/target_node/jest/mocks/style_mock.js', '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': '/node_modules/@kbn/test/target_node/jest/mocks/file_mock.js', - '\\.ace\\.worker.js$': + '\\.ace\\.worker$': '/node_modules/@kbn/test/target_node/jest/mocks/worker_module_mock.js', - '\\.editor\\.worker.js$': + '\\.editor\\.worker(\\.js)?$': '/node_modules/@kbn/test/target_node/jest/mocks/worker_module_mock.js', '^(!!)?file-loader!': '/node_modules/@kbn/test/target_node/jest/mocks/file_mock.js', - '^src/core/(.*)': '/src/core/$1', - '^src/plugins/(.*)': '/src/plugins/$1', + ...Object.fromEntries( + Array.from(pkgMap.entries()).map(([pkgId, repoRelativeDir]) => [ + `^${pkgId}(/?.*)$`, + `/${repoRelativeDir}$1`, + ]) + ), }, // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader diff --git a/scripts/kbn.js b/scripts/kbn.js index f384c13a3acfc..459c590ddf8cc 100644 --- a/scripts/kbn.js +++ b/scripts/kbn.js @@ -8,4 +8,4 @@ require('../src/setup_node_env/ensure_node_preserve_symlinks'); require('../src/setup_node_env/node_version_validator'); -require('../packages/kbn-pm/cli'); +require('../packages/kbn-pm/dist').run(process.argv.slice(2)); diff --git a/scripts/type_summarizer.js b/scripts/type_summarizer.js index 09d3aa69138e9..cb1b46e941954 100644 --- a/scripts/type_summarizer.js +++ b/scripts/type_summarizer.js @@ -6,6 +6,6 @@ * Side Public License, v 1. */ -require('../src/setup_node_env'); +require('../src/setup_node_env/no_transpilation'); require('source-map-support/register'); -require('../packages/kbn-type-summarizer/src/bazel_cli'); +require('@kbn/type-summarizer/target_node/bazel_cli'); diff --git a/src/core/server/elasticsearch/elasticsearch_config.test.mocks.ts b/src/core/server/elasticsearch/elasticsearch_config.test.mocks.ts index 63b2233b06a96..3a8f3c459768d 100644 --- a/src/core/server/elasticsearch/elasticsearch_config.test.mocks.ts +++ b/src/core/server/elasticsearch/elasticsearch_config.test.mocks.ts @@ -7,7 +7,10 @@ */ export const mockReadFileSync = jest.fn(); -jest.mock('fs', () => ({ readFileSync: mockReadFileSync })); +jest.mock('fs', () => ({ + ...jest.requireActual('fs'), + readFileSync: mockReadFileSync, +})); export const mockReadPkcs12Keystore = jest.fn(); export const mockReadPkcs12Truststore = jest.fn(); diff --git a/src/dev/bazel/pkg_npm_types.bzl b/src/dev/bazel/pkg_npm_types.bzl index e5caba5149053..03ec4209f6f6c 100644 --- a/src/dev/bazel/pkg_npm_types.bzl +++ b/src/dev/bazel/pkg_npm_types.bzl @@ -142,7 +142,7 @@ pkg_npm_types = rule( "_packager": attr.label( doc = "Target that executes the npm types package assembler binary", executable = True, - cfg = "host", + cfg = "target", default = Label("//packages/kbn-type-summarizer:bazel-cli"), ), }, diff --git a/src/dev/build/tasks/package_json/create_package_json_tasks.ts b/src/dev/build/tasks/package_json/create_package_json_tasks.ts index 62280252fe34e..a84cd050e461d 100644 --- a/src/dev/build/tasks/package_json/create_package_json_tasks.ts +++ b/src/dev/build/tasks/package_json/create_package_json_tasks.ts @@ -6,7 +6,6 @@ * Side Public License, v 1. */ -import normalizePosixPath from 'normalize-path'; // @ts-ignore import { transformDependencies } from '@kbn/pm'; import { findUsedDependencies } from './find_used_dependencies'; @@ -18,10 +17,7 @@ export const CreatePackageJson: Task = { async run(config, log, build) { const pkg = config.getKibanaPkg(); const transformedDeps = transformDependencies(pkg.dependencies as { [key: string]: string }); - const foundPkgDeps = await findUsedDependencies( - transformedDeps, - normalizePosixPath(build.resolvePath('.')) - ); + const foundPkgDeps = await findUsedDependencies(transformedDeps, build.resolvePath('.')); const newPkg = { name: pkg.name, diff --git a/src/dev/build/tasks/package_json/find_used_dependencies.ts b/src/dev/build/tasks/package_json/find_used_dependencies.ts index e49d57c6f794f..4250b0a6b7990 100644 --- a/src/dev/build/tasks/package_json/find_used_dependencies.ts +++ b/src/dev/build/tasks/package_json/find_used_dependencies.ts @@ -6,66 +6,56 @@ * Side Public License, v 1. */ -import Path from 'path'; import globby from 'globby'; -import normalize from 'normalize-path'; -// @ts-ignore -import { parseEntries, dependenciesParseStrategy } from '@kbn/babel-code-parser'; - -async function getDependencies(cwd: string, entries: string[]) { - // Return the dependencies retrieve from the - // provided code entries (sanitized) and - // parseStrategy (dependencies one) - return Object.keys(await parseEntries(cwd, entries, dependenciesParseStrategy, {})); -} +import { ImportResolver } from '@kbn/import-resolver'; +import { findUsedNodeModules } from '@kbn/find-used-node-modules'; export async function findUsedDependencies(listedPkgDependencies: any, baseDir: any) { // Define the entry points for the server code in order to - // start here later looking for the server side dependencies - const mainCodeEntries = await globby(normalize(Path.resolve(baseDir, `src/cli*/dist.js`))); - - const discoveredPluginEntries = await globby([ - normalize(Path.resolve(baseDir, `src/plugins/**/server/index.js`)), - `!${normalize(Path.resolve(baseDir, `/src/plugins/**/public`))}`, - normalize(Path.resolve(baseDir, `x-pack/plugins/**/server/index.js`)), - `!${normalize(Path.resolve(baseDir, `/x-pack/plugins/**/public`))}`, - ]); - - // It will include entries that cannot be discovered - // statically as they are required with dynamic imports. - // In vis_type_timelion the problem is the loadFunctions() - // which dynamically requires all the files inside of function folders - // Another way would be to include an index file and import all the functions - // using named imports - const dynamicRequiredEntries = await globby([ - normalize(Path.resolve(baseDir, 'src/plugins/vis_types/timelion/server/**/*.js')), - ]); + // look for the server side dependencies + const serverEntries = await globby( + [ + // main code entries + 'src/cli*/dist.js', + // core entry + 'src/core/server/index.js', + // plugin entries + 'src/plugins/**/server/index.js', + 'x-pack/plugins/**/server/index.js', + // entries that are loaded into the server with dynamic require() calls + 'src/plugins/vis_types/timelion/server/**/*.js', + ], + { + cwd: baseDir, + ignore: ['**/public/**'], + absolute: true, + } + ); - // Compose all the needed entries - const serverEntries = [...mainCodeEntries, ...discoveredPluginEntries, ...dynamicRequiredEntries]; + const resolver = ImportResolver.create(baseDir); // Get the dependencies found searching through the server // side code entries that were provided - const serverDependencies = await getDependencies(baseDir, serverEntries); - - // List of hardcoded dependencies that we need and that are not discovered - // searching through code imports - // TODO: remove this once we get rid off @kbn/ui-framework - const hardCodedDependencies = ['@kbn/ui-framework']; - - // Consider this as our whiteList for the modules we can't delete - const whiteListedModules = [...serverDependencies, ...hardCodedDependencies]; - - const listedDependencies = Object.keys(listedPkgDependencies); - const filteredListedDependencies = listedDependencies.filter((entry) => { - return whiteListedModules.some((nonEntry) => entry === nonEntry); - }); - - return filteredListedDependencies.reduce((foundUsedDeps: any, usedDep) => { - if (listedPkgDependencies[usedDep]) { - foundUsedDeps[usedDep] = listedPkgDependencies[usedDep]; + const usedDeps = [ + // TODO: remove this once we get rid off @kbn/ui-framework, for now it isn't detectable as "used" so we hard code it + '@kbn/ui-framework', + // find all the node modules we actually use on the server, including the peerDependencies of our used node_modules which are used within those deps + ...(await findUsedNodeModules({ + resolver, + entryPaths: serverEntries, + findUsedPeers: true, + })), + ]; + + // only include dependencies in the package.json file that are already listed in the package.json dependencies + const neededDeps: Record = {}; + + for (const dep of usedDeps) { + const version = listedPkgDependencies[dep]; + if (version) { + neededDeps[dep] = version; } + } - return foundUsedDeps; - }, {}); + return neededDeps; } diff --git a/src/dev/build/tasks/transpile_babel_task.ts b/src/dev/build/tasks/transpile_babel_task.ts index 7e95679df1bf7..37f63d31415e9 100644 --- a/src/dev/build/tasks/transpile_babel_task.ts +++ b/src/dev/build/tasks/transpile_babel_task.ts @@ -17,7 +17,7 @@ import { Task, Build } from '../lib'; const asyncPipeline = promisify(pipeline); -const transpileWithBabel = async (srcGlobs: string[], build: Build, presets: string[]) => { +const transpileWithBabel = async (srcGlobs: string[], build: Build, preset: string) => { const buildRoot = build.resolvePath(); await asyncPipeline( @@ -36,7 +36,18 @@ const transpileWithBabel = async (srcGlobs: string[], build: Build, presets: str gulpBabel({ babelrc: false, - presets, + presets: [ + [ + preset, + { + // we pass this so that @kbn/babel-plugin-synthetic-packages can correct absolute imports + // for packages to relative requests, without having to discover the Kibana repo root, which + // it can't do because at this point in the build there isn't a package.json file for the + // plugin to find. + 'kibana/rootDir': build.resolvePath('.'), + }, + ], + ], }), vfs.dest(buildRoot) @@ -48,15 +59,19 @@ export const TranspileBabel: Task = { async run(config, log, build) { // Transpile server code - await transpileWithBabel(['**/*.{js,ts,tsx}', '!**/public/**'], build, [ - require.resolve('@kbn/babel-preset/node_preset'), - ]); + await transpileWithBabel( + ['**/*.{js,ts,tsx}', '!**/public/**'], + build, + require.resolve('@kbn/babel-preset/node_preset') + ); // Transpile client code // NOTE: For the client, as we have the optimizer, we are only // pre-transpiling the typescript based files - await transpileWithBabel(['**/public/**/*.{ts,tsx}'], build, [ - require.resolve('@kbn/babel-preset/webpack_preset'), - ]); + await transpileWithBabel( + ['**/public/**/*.{ts,tsx}'], + build, + require.resolve('@kbn/babel-preset/webpack_preset') + ); }, }; diff --git a/src/dev/plugin_discovery/find_plugins.ts b/src/dev/plugin_discovery/find_plugins.ts index 7e46894813f0e..698a9816a5312 100644 --- a/src/dev/plugin_discovery/find_plugins.ts +++ b/src/dev/plugin_discovery/find_plugins.ts @@ -7,7 +7,7 @@ */ import Path from 'path'; -import { getPluginSearchPaths } from '@kbn/config'; +import { getPluginSearchPaths } from '@kbn/plugin-discovery'; import { KibanaPlatformPlugin, simpleKibanaPlatformPluginDiscovery } from '@kbn/plugin-discovery'; import { REPO_ROOT } from '@kbn/utils'; diff --git a/src/dev/run_find_plugins_with_circular_deps.ts b/src/dev/run_find_plugins_with_circular_deps.ts index f9ee7bd84c54f..f174561b49f9b 100644 --- a/src/dev/run_find_plugins_with_circular_deps.ts +++ b/src/dev/run_find_plugins_with_circular_deps.ts @@ -9,7 +9,7 @@ import dedent from 'dedent'; import { parseDependencyTree, parseCircular, prettyCircular } from 'dpdm'; import { relative } from 'path'; -import { getPluginSearchPaths } from '@kbn/config'; +import { getPluginSearchPaths } from '@kbn/plugin-discovery'; import { run } from '@kbn/dev-utils'; import { REPO_ROOT } from '@kbn/utils'; diff --git a/tsconfig.base.json b/tsconfig.base.json index b7c6505389f0c..b8dfc58796297 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -2,13 +2,442 @@ "compilerOptions": { "baseUrl": ".", "paths": { - // Setup @kbn paths for Bazel compilations - "@kbn/*": [ - "node_modules/@kbn/*", - "bazel-out/darwin-fastbuild/bin/packages/kbn-*", - "bazel-out/k8-fastbuild/bin/packages/kbn-*", - "bazel-out/x64_windows-fastbuild/bin/packages/kbn-*" - ], + "@kbn/core": ["src/core"], + "@kbn/core/*": ["src/core/*"], + // START AUTOMATED PACKAGE LISTING + "@kbn/bfetch-explorer-plugin": ["examples/bfetch_explorer"], + "@kbn/bfetch-explorer-plugin/*": ["examples/bfetch_explorer/*"], + "@kbn/dashboard-embeddable-examples-plugin": ["examples/dashboard_embeddable_examples"], + "@kbn/dashboard-embeddable-examples-plugin/*": ["examples/dashboard_embeddable_examples/*"], + "@kbn/data-view-field-editor-example-plugin": ["examples/data_view_field_editor_example"], + "@kbn/data-view-field-editor-example-plugin/*": ["examples/data_view_field_editor_example/*"], + "@kbn/developer-examples-plugin": ["examples/developer_examples"], + "@kbn/developer-examples-plugin/*": ["examples/developer_examples/*"], + "@kbn/embeddable-examples-plugin": ["examples/embeddable_examples"], + "@kbn/embeddable-examples-plugin/*": ["examples/embeddable_examples/*"], + "@kbn/embeddable-explorer-plugin": ["examples/embeddable_explorer"], + "@kbn/embeddable-explorer-plugin/*": ["examples/embeddable_explorer/*"], + "@kbn/expressions-explorer-plugin": ["examples/expressions_explorer"], + "@kbn/expressions-explorer-plugin/*": ["examples/expressions_explorer/*"], + "@kbn/field-formats-example-plugin": ["examples/field_formats_example"], + "@kbn/field-formats-example-plugin/*": ["examples/field_formats_example/*"], + "@kbn/hello-world-plugin": ["examples/hello_world"], + "@kbn/hello-world-plugin/*": ["examples/hello_world/*"], + "@kbn/locator-examples-plugin": ["examples/locator_examples"], + "@kbn/locator-examples-plugin/*": ["examples/locator_examples/*"], + "@kbn/locator-explorer-plugin": ["examples/locator_explorer"], + "@kbn/locator-explorer-plugin/*": ["examples/locator_explorer/*"], + "@kbn/paertial-results-example-plugin": ["examples/partial_results_example"], + "@kbn/paertial-results-example-plugin/*": ["examples/partial_results_example/*"], + "@kbn/preboot-example-plugin": ["examples/preboot_example"], + "@kbn/preboot-example-plugin/*": ["examples/preboot_example/*"], + "@kbn/routing-example-plugin": ["examples/routing_example"], + "@kbn/routing-example-plugin/*": ["examples/routing_example/*"], + "@kbn/screenshot-mode-example-plugin": ["examples/screenshot_mode_example"], + "@kbn/screenshot-mode-example-plugin/*": ["examples/screenshot_mode_example/*"], + "@kbn/search-examples-plugin": ["examples/search_examples"], + "@kbn/search-examples-plugin/*": ["examples/search_examples/*"], + "@kbn/share-examples-plugin": ["examples/share_examples"], + "@kbn/share-examples-plugin/*": ["examples/share_examples/*"], + "@kbn/state-containers-examples-plugin": ["examples/state_containers_examples"], + "@kbn/state-containers-examples-plugin/*": ["examples/state_containers_examples/*"], + "@kbn/ui-actions-examples-plugin": ["examples/ui_action_examples"], + "@kbn/ui-actions-examples-plugin/*": ["examples/ui_action_examples/*"], + "@kbn/ui-actions-explorer-plugin": ["examples/ui_actions_explorer"], + "@kbn/ui-actions-explorer-plugin/*": ["examples/ui_actions_explorer/*"], + "@kbn/advanced-settings-plugin": ["src/plugins/advanced_settings"], + "@kbn/advanced-settings-plugin/*": ["src/plugins/advanced_settings/*"], + "@kbn/bfetch-plugin": ["src/plugins/bfetch"], + "@kbn/bfetch-plugin/*": ["src/plugins/bfetch/*"], + "@kbn/expression-gauge-plugin": ["src/plugins/chart_expressions/expression_gauge"], + "@kbn/expression-gauge-plugin/*": ["src/plugins/chart_expressions/expression_gauge/*"], + "@kbn/expression-heatmap-plugin": ["src/plugins/chart_expressions/expression_heatmap"], + "@kbn/expression-heatmap-plugin/*": ["src/plugins/chart_expressions/expression_heatmap/*"], + "@kbn/expression-metric-vis-plugin": ["src/plugins/chart_expressions/expression_metric"], + "@kbn/expression-metric-vis-plugin/*": ["src/plugins/chart_expressions/expression_metric/*"], + "@kbn/expression-partition-vis-plugin": ["src/plugins/chart_expressions/expression_partition_vis"], + "@kbn/expression-partition-vis-plugin/*": ["src/plugins/chart_expressions/expression_partition_vis/*"], + "@kbn/expression-tagcloud-plugin": ["src/plugins/chart_expressions/expression_tagcloud"], + "@kbn/expression-tagcloud-plugin/*": ["src/plugins/chart_expressions/expression_tagcloud/*"], + "@kbn/expression-xy-plugin": ["src/plugins/chart_expressions/expression_xy"], + "@kbn/expression-xy-plugin/*": ["src/plugins/chart_expressions/expression_xy/*"], + "@kbn/charts-plugin": ["src/plugins/charts"], + "@kbn/charts-plugin/*": ["src/plugins/charts/*"], + "@kbn/console-plugin": ["src/plugins/console"], + "@kbn/console-plugin/*": ["src/plugins/console/*"], + "@kbn/controls-plugin": ["src/plugins/controls"], + "@kbn/controls-plugin/*": ["src/plugins/controls/*"], + "@kbn/custom-integrations-plugin": ["src/plugins/custom_integrations"], + "@kbn/custom-integrations-plugin/*": ["src/plugins/custom_integrations/*"], + "@kbn/dashboard-plugin": ["src/plugins/dashboard"], + "@kbn/dashboard-plugin/*": ["src/plugins/dashboard/*"], + "@kbn/data-view-editor-plugin": ["src/plugins/data_view_editor"], + "@kbn/data-view-editor-plugin/*": ["src/plugins/data_view_editor/*"], + "@kbn/data-view-field-editor-plugin": ["src/plugins/data_view_field_editor"], + "@kbn/data-view-field-editor-plugin/*": ["src/plugins/data_view_field_editor/*"], + "@kbn/data-view-management-plugin": ["src/plugins/data_view_management"], + "@kbn/data-view-management-plugin/*": ["src/plugins/data_view_management/*"], + "@kbn/data-views-plugin": ["src/plugins/data_views"], + "@kbn/data-views-plugin/*": ["src/plugins/data_views/*"], + "@kbn/data-plugin": ["src/plugins/data"], + "@kbn/data-plugin/*": ["src/plugins/data/*"], + "@kbn/dev-tools-plugin": ["src/plugins/dev_tools"], + "@kbn/dev-tools-plugin/*": ["src/plugins/dev_tools/*"], + "@kbn/discover-plugin": ["src/plugins/discover"], + "@kbn/discover-plugin/*": ["src/plugins/discover/*"], + "@kbn/embeddable-plugin": ["src/plugins/embeddable"], + "@kbn/embeddable-plugin/*": ["src/plugins/embeddable/*"], + "@kbn/es-ui-shared-plugin": ["src/plugins/es_ui_shared"], + "@kbn/es-ui-shared-plugin/*": ["src/plugins/es_ui_shared/*"], + "@kbn/event-annotation-plugin": ["src/plugins/event_annotation"], + "@kbn/event-annotation-plugin/*": ["src/plugins/event_annotation/*"], + "@kbn/expression-error-plugin": ["src/plugins/expression_error"], + "@kbn/expression-error-plugin/*": ["src/plugins/expression_error/*"], + "@kbn/expression-image-plugin": ["src/plugins/expression_image"], + "@kbn/expression-image-plugin/*": ["src/plugins/expression_image/*"], + "@kbn/expression-metric-plugin": ["src/plugins/expression_metric"], + "@kbn/expression-metric-plugin/*": ["src/plugins/expression_metric/*"], + "@kbn/expression-repeat-image-plugin": ["src/plugins/expression_repeat_image"], + "@kbn/expression-repeat-image-plugin/*": ["src/plugins/expression_repeat_image/*"], + "@kbn/expression-reveal-image-plugin": ["src/plugins/expression_reveal_image"], + "@kbn/expression-reveal-image-plugin/*": ["src/plugins/expression_reveal_image/*"], + "@kbn/expression-shape-plugin": ["src/plugins/expression_shape"], + "@kbn/expression-shape-plugin/*": ["src/plugins/expression_shape/*"], + "@kbn/expressions-plugin": ["src/plugins/expressions"], + "@kbn/expressions-plugin/*": ["src/plugins/expressions/*"], + "@kbn/field-formats-plugin": ["src/plugins/field_formats"], + "@kbn/field-formats-plugin/*": ["src/plugins/field_formats/*"], + "@kbn/home-plugin": ["src/plugins/home"], + "@kbn/home-plugin/*": ["src/plugins/home/*"], + "@kbn/input-control-vis-plugin": ["src/plugins/input_control_vis"], + "@kbn/input-control-vis-plugin/*": ["src/plugins/input_control_vis/*"], + "@kbn/inspector-plugin": ["src/plugins/inspector"], + "@kbn/inspector-plugin/*": ["src/plugins/inspector/*"], + "@kbn/interactive-setup-plugin": ["src/plugins/interactive_setup"], + "@kbn/interactive-setup-plugin/*": ["src/plugins/interactive_setup/*"], + "@kbn/kibana-overview-plugin": ["src/plugins/kibana_overview"], + "@kbn/kibana-overview-plugin/*": ["src/plugins/kibana_overview/*"], + "@kbn/kibana-react-plugin": ["src/plugins/kibana_react"], + "@kbn/kibana-react-plugin/*": ["src/plugins/kibana_react/*"], + "@kbn/kibana-usage-collection-plugin": ["src/plugins/kibana_usage_collection"], + "@kbn/kibana-usage-collection-plugin/*": ["src/plugins/kibana_usage_collection/*"], + "@kbn/kibana-utils-plugin": ["src/plugins/kibana_utils"], + "@kbn/kibana-utils-plugin/*": ["src/plugins/kibana_utils/*"], + "@kbn/management-plugin": ["src/plugins/management"], + "@kbn/management-plugin/*": ["src/plugins/management/*"], + "@kbn/maps-ems-plugin": ["src/plugins/maps_ems"], + "@kbn/maps-ems-plugin/*": ["src/plugins/maps_ems/*"], + "@kbn/navigation-plugin": ["src/plugins/navigation"], + "@kbn/navigation-plugin/*": ["src/plugins/navigation/*"], + "@kbn/newsfeed-plugin": ["src/plugins/newsfeed"], + "@kbn/newsfeed-plugin/*": ["src/plugins/newsfeed/*"], + "@kbn/presentation-util-plugin": ["src/plugins/presentation_util"], + "@kbn/presentation-util-plugin/*": ["src/plugins/presentation_util/*"], + "@kbn/saved-objects-management-plugin": ["src/plugins/saved_objects_management"], + "@kbn/saved-objects-management-plugin/*": ["src/plugins/saved_objects_management/*"], + "@kbn/saved-objects-tagging-oss-plugin": ["src/plugins/saved_objects_tagging_oss"], + "@kbn/saved-objects-tagging-oss-plugin/*": ["src/plugins/saved_objects_tagging_oss/*"], + "@kbn/saved-objects-plugin": ["src/plugins/saved_objects"], + "@kbn/saved-objects-plugin/*": ["src/plugins/saved_objects/*"], + "@kbn/screenshot-mode-plugin": ["src/plugins/screenshot_mode"], + "@kbn/screenshot-mode-plugin/*": ["src/plugins/screenshot_mode/*"], + "@kbn/share-plugin": ["src/plugins/share"], + "@kbn/share-plugin/*": ["src/plugins/share/*"], + "@kbn/shared-ux-plugin": ["src/plugins/shared_ux"], + "@kbn/shared-ux-plugin/*": ["src/plugins/shared_ux/*"], + "@kbn/telemetry-collection-manager-plugin": ["src/plugins/telemetry_collection_manager"], + "@kbn/telemetry-collection-manager-plugin/*": ["src/plugins/telemetry_collection_manager/*"], + "@kbn/telemetry-management-section-plugin": ["src/plugins/telemetry_management_section"], + "@kbn/telemetry-management-section-plugin/*": ["src/plugins/telemetry_management_section/*"], + "@kbn/telemetry-plugin": ["src/plugins/telemetry"], + "@kbn/telemetry-plugin/*": ["src/plugins/telemetry/*"], + "@kbn/ui-actions-plugin": ["src/plugins/ui_actions"], + "@kbn/ui-actions-plugin/*": ["src/plugins/ui_actions/*"], + "@kbn/unified-search-plugin": ["src/plugins/unified_search"], + "@kbn/unified-search-plugin/*": ["src/plugins/unified_search/*"], + "@kbn/url-forwarding-plugin": ["src/plugins/url_forwarding"], + "@kbn/url-forwarding-plugin/*": ["src/plugins/url_forwarding/*"], + "@kbn/usage-collection-plugin": ["src/plugins/usage_collection"], + "@kbn/usage-collection-plugin/*": ["src/plugins/usage_collection/*"], + "@kbn/vis-default-editor-plugin": ["src/plugins/vis_default_editor"], + "@kbn/vis-default-editor-plugin/*": ["src/plugins/vis_default_editor/*"], + "@kbn/vis-type-markdown-plugin": ["src/plugins/vis_type_markdown"], + "@kbn/vis-type-markdown-plugin/*": ["src/plugins/vis_type_markdown/*"], + "@kbn/vis-type-gauge-plugin": ["src/plugins/vis_types/gauge"], + "@kbn/vis-type-gauge-plugin/*": ["src/plugins/vis_types/gauge/*"], + "@kbn/vis-type-heatmap-plugin": ["src/plugins/vis_types/heatmap"], + "@kbn/vis-type-heatmap-plugin/*": ["src/plugins/vis_types/heatmap/*"], + "@kbn/vis-type-metric-plugin": ["src/plugins/vis_types/metric"], + "@kbn/vis-type-metric-plugin/*": ["src/plugins/vis_types/metric/*"], + "@kbn/vis-type-pie-plugin": ["src/plugins/vis_types/pie"], + "@kbn/vis-type-pie-plugin/*": ["src/plugins/vis_types/pie/*"], + "@kbn/vis-type-table-plugin": ["src/plugins/vis_types/table"], + "@kbn/vis-type-table-plugin/*": ["src/plugins/vis_types/table/*"], + "@kbn/vis-type-tagcloud-plugin": ["src/plugins/vis_types/tagcloud"], + "@kbn/vis-type-tagcloud-plugin/*": ["src/plugins/vis_types/tagcloud/*"], + "@kbn/vis-type-timelion-plugin": ["src/plugins/vis_types/timelion"], + "@kbn/vis-type-timelion-plugin/*": ["src/plugins/vis_types/timelion/*"], + "@kbn/vis-type-timeseries-plugin": ["src/plugins/vis_types/timeseries"], + "@kbn/vis-type-timeseries-plugin/*": ["src/plugins/vis_types/timeseries/*"], + "@kbn/vis-type-vega-plugin": ["src/plugins/vis_types/vega"], + "@kbn/vis-type-vega-plugin/*": ["src/plugins/vis_types/vega/*"], + "@kbn/vis-type-vislib-plugin": ["src/plugins/vis_types/vislib"], + "@kbn/vis-type-vislib-plugin/*": ["src/plugins/vis_types/vislib/*"], + "@kbn/vis-type-xy-plugin": ["src/plugins/vis_types/xy"], + "@kbn/vis-type-xy-plugin/*": ["src/plugins/vis_types/xy/*"], + "@kbn/visualizations-plugin": ["src/plugins/visualizations"], + "@kbn/visualizations-plugin/*": ["src/plugins/visualizations/*"], + "@kbn/analytics-ftr-helpers-plugin": ["test/analytics/__fixtures__/plugins/analytics_ftr_helpers"], + "@kbn/analytics-ftr-helpers-plugin/*": ["test/analytics/__fixtures__/plugins/analytics_ftr_helpers/*"], + "@kbn/analytics-plugin-a-plugin": ["test/analytics/__fixtures__/plugins/analytics_plugin_a"], + "@kbn/analytics-plugin-a-plugin/*": ["test/analytics/__fixtures__/plugins/analytics_plugin_a/*"], + "@kbn/coverage-fixtures-plugin": ["test/common/fixtures/plugins/coverage"], + "@kbn/coverage-fixtures-plugin/*": ["test/common/fixtures/plugins/coverage/*"], + "@kbn/newsfeed-fixtures-plugin": ["test/common/fixtures/plugins/newsfeed"], + "@kbn/newsfeed-fixtures-plugin/*": ["test/common/fixtures/plugins/newsfeed/*"], + "@kbn/kbn-tp-run-pipeline-plugin": ["test/interpreter_functional/plugins/kbn_tp_run_pipeline"], + "@kbn/kbn-tp-run-pipeline-plugin/*": ["test/interpreter_functional/plugins/kbn_tp_run_pipeline/*"], + "@kbn/app-link-test-plugin": ["test/plugin_functional/plugins/app_link_test"], + "@kbn/app-link-test-plugin/*": ["test/plugin_functional/plugins/app_link_test/*"], + "@kbn/core-app-status-plugin": ["test/plugin_functional/plugins/core_app_status"], + "@kbn/core-app-status-plugin/*": ["test/plugin_functional/plugins/core_app_status/*"], + "@kbn/core-history-block-plugin": ["test/plugin_functional/plugins/core_history_block"], + "@kbn/core-history-block-plugin/*": ["test/plugin_functional/plugins/core_history_block/*"], + "@kbn/core-http-plugin": ["test/plugin_functional/plugins/core_http"], + "@kbn/core-http-plugin/*": ["test/plugin_functional/plugins/core_http/*"], + "@kbn/core-plugin-a-plugin": ["test/plugin_functional/plugins/core_plugin_a"], + "@kbn/core-plugin-a-plugin/*": ["test/plugin_functional/plugins/core_plugin_a/*"], + "@kbn/core-plugin-appleave-plugin": ["test/plugin_functional/plugins/core_plugin_appleave"], + "@kbn/core-plugin-appleave-plugin/*": ["test/plugin_functional/plugins/core_plugin_appleave/*"], + "@kbn/core-plugin-b-plugin": ["test/plugin_functional/plugins/core_plugin_b"], + "@kbn/core-plugin-b-plugin/*": ["test/plugin_functional/plugins/core_plugin_b/*"], + "@kbn/core-plugin-chromeless-plugin": ["test/plugin_functional/plugins/core_plugin_chromeless"], + "@kbn/core-plugin-chromeless-plugin/*": ["test/plugin_functional/plugins/core_plugin_chromeless/*"], + "@kbn/core-plugin-deep-links-plugin": ["test/plugin_functional/plugins/core_plugin_deep_links"], + "@kbn/core-plugin-deep-links-plugin/*": ["test/plugin_functional/plugins/core_plugin_deep_links/*"], + "@kbn/core-plugin-deprecations-plugin": ["test/plugin_functional/plugins/core_plugin_deprecations"], + "@kbn/core-plugin-deprecations-plugin/*": ["test/plugin_functional/plugins/core_plugin_deprecations/*"], + "@kbn/core-plugin-execution-context-plugin": ["test/plugin_functional/plugins/core_plugin_execution_context"], + "@kbn/core-plugin-execution-context-plugin/*": ["test/plugin_functional/plugins/core_plugin_execution_context/*"], + "@kbn/core-plugin-helpmenu-plugin": ["test/plugin_functional/plugins/core_plugin_helpmenu"], + "@kbn/core-plugin-helpmenu-plugin/*": ["test/plugin_functional/plugins/core_plugin_helpmenu/*"], + "@kbn/core-plugin-route-timeouts-plugin": ["test/plugin_functional/plugins/core_plugin_route_timeouts"], + "@kbn/core-plugin-route-timeouts-plugin/*": ["test/plugin_functional/plugins/core_plugin_route_timeouts/*"], + "@kbn/core-plugin-static-assets-plugin": ["test/plugin_functional/plugins/core_plugin_static_assets"], + "@kbn/core-plugin-static-assets-plugin/*": ["test/plugin_functional/plugins/core_plugin_static_assets/*"], + "@kbn/core-provider-plugin": ["test/plugin_functional/plugins/core_provider_plugin"], + "@kbn/core-provider-plugin/*": ["test/plugin_functional/plugins/core_provider_plugin/*"], + "@kbn/data-search-plugin": ["test/plugin_functional/plugins/data_search"], + "@kbn/data-search-plugin/*": ["test/plugin_functional/plugins/data_search/*"], + "@kbn/elasticsearch-client-plugin": ["test/plugin_functional/plugins/elasticsearch_client_plugin"], + "@kbn/elasticsearch-client-plugin/*": ["test/plugin_functional/plugins/elasticsearch_client_plugin/*"], + "@kbn/index-patterns-test-plugin": ["test/plugin_functional/plugins/index_patterns"], + "@kbn/index-patterns-test-plugin/*": ["test/plugin_functional/plugins/index_patterns/*"], + "@kbn/kbn-sample-panel-action-plugin": ["test/plugin_functional/plugins/kbn_sample_panel_action"], + "@kbn/kbn-sample-panel-action-plugin/*": ["test/plugin_functional/plugins/kbn_sample_panel_action/*"], + "@kbn/kbn-top-nav-plugin": ["test/plugin_functional/plugins/kbn_top_nav"], + "@kbn/kbn-top-nav-plugin/*": ["test/plugin_functional/plugins/kbn_top_nav/*"], + "@kbn/kbn-tp-custom-visualizations-plugin": ["test/plugin_functional/plugins/kbn_tp_custom_visualizations"], + "@kbn/kbn-tp-custom-visualizations-plugin/*": ["test/plugin_functional/plugins/kbn_tp_custom_visualizations/*"], + "@kbn/management-test-plugin": ["test/plugin_functional/plugins/management_test_plugin"], + "@kbn/management-test-plugin/*": ["test/plugin_functional/plugins/management_test_plugin/*"], + "@kbn/rendering-plugin": ["test/plugin_functional/plugins/rendering_plugin"], + "@kbn/rendering-plugin/*": ["test/plugin_functional/plugins/rendering_plugin/*"], + "@kbn/saved-object-export-transforms-plugin": ["test/plugin_functional/plugins/saved_object_export_transforms"], + "@kbn/saved-object-export-transforms-plugin/*": ["test/plugin_functional/plugins/saved_object_export_transforms/*"], + "@kbn/saved-object-import-warnings-plugin": ["test/plugin_functional/plugins/saved_object_import_warnings"], + "@kbn/saved-object-import-warnings-plugin/*": ["test/plugin_functional/plugins/saved_object_import_warnings/*"], + "@kbn/saved-objects-hidden-type-plugin": ["test/plugin_functional/plugins/saved_objects_hidden_type"], + "@kbn/saved-objects-hidden-type-plugin/*": ["test/plugin_functional/plugins/saved_objects_hidden_type/*"], + "@kbn/session-notifications-plugin": ["test/plugin_functional/plugins/session_notifications"], + "@kbn/session-notifications-plugin/*": ["test/plugin_functional/plugins/session_notifications/*"], + "@kbn/telemetry-test-plugin": ["test/plugin_functional/plugins/telemetry"], + "@kbn/telemetry-test-plugin/*": ["test/plugin_functional/plugins/telemetry/*"], + "@kbn/ui-settings-plugin": ["test/plugin_functional/plugins/ui_settings_plugin"], + "@kbn/ui-settings-plugin/*": ["test/plugin_functional/plugins/ui_settings_plugin/*"], + "@kbn/usage-collection-test-plugin": ["test/plugin_functional/plugins/usage_collection"], + "@kbn/usage-collection-test-plugin/*": ["test/plugin_functional/plugins/usage_collection/*"], + "@kbn/alerting-example-plugin": ["x-pack/examples/alerting_example"], + "@kbn/alerting-example-plugin/*": ["x-pack/examples/alerting_example/*"], + "@kbn/embedded-lens-example-plugin": ["x-pack/examples/embedded_lens_example"], + "@kbn/embedded-lens-example-plugin/*": ["x-pack/examples/embedded_lens_example/*"], + "@kbn/exploratory-view-example-plugin": ["x-pack/examples/exploratory_view_example"], + "@kbn/exploratory-view-example-plugin/*": ["x-pack/examples/exploratory_view_example/*"], + "@kbn/reporting-example-plugin": ["x-pack/examples/reporting_example"], + "@kbn/reporting-example-plugin/*": ["x-pack/examples/reporting_example/*"], + "@kbn/screenshotting-example-plugin": ["x-pack/examples/screenshotting_example"], + "@kbn/screenshotting-example-plugin/*": ["x-pack/examples/screenshotting_example/*"], + "@kbn/testing-embedded-lens-plugin": ["x-pack/examples/testing_embedded_lens"], + "@kbn/testing-embedded-lens-plugin/*": ["x-pack/examples/testing_embedded_lens/*"], + "@kbn/third-party-lens-navigation-prompt-plugin": ["x-pack/examples/third_party_lens_navigation_prompt"], + "@kbn/third-party-lens-navigation-prompt-plugin/*": ["x-pack/examples/third_party_lens_navigation_prompt/*"], + "@kbn/third-party-vis-lens-example-plugin": ["x-pack/examples/third_party_vis_lens_example"], + "@kbn/third-party-vis-lens-example-plugin/*": ["x-pack/examples/third_party_vis_lens_example/*"], + "@kbn/ui-actions-enhanced-examples-plugin": ["x-pack/examples/ui_actions_enhanced_examples"], + "@kbn/ui-actions-enhanced-examples-plugin/*": ["x-pack/examples/ui_actions_enhanced_examples/*"], + "@kbn/actions-plugin": ["x-pack/plugins/actions"], + "@kbn/actions-plugin/*": ["x-pack/plugins/actions/*"], + "@kbn/alerting-plugin": ["x-pack/plugins/alerting"], + "@kbn/alerting-plugin/*": ["x-pack/plugins/alerting/*"], + "@kbn/apm-plugin": ["x-pack/plugins/apm"], + "@kbn/apm-plugin/*": ["x-pack/plugins/apm/*"], + "@kbn/banners-plugin": ["x-pack/plugins/banners"], + "@kbn/banners-plugin/*": ["x-pack/plugins/banners/*"], + "@kbn/canvas-plugin": ["x-pack/plugins/canvas"], + "@kbn/canvas-plugin/*": ["x-pack/plugins/canvas/*"], + "@kbn/cases-plugin": ["x-pack/plugins/cases"], + "@kbn/cases-plugin/*": ["x-pack/plugins/cases/*"], + "@kbn/cloud-security-posture-plugin": ["x-pack/plugins/cloud_security_posture"], + "@kbn/cloud-security-posture-plugin/*": ["x-pack/plugins/cloud_security_posture/*"], + "@kbn/cloud-plugin": ["x-pack/plugins/cloud"], + "@kbn/cloud-plugin/*": ["x-pack/plugins/cloud/*"], + "@kbn/cross-cluster-replication-plugin": ["x-pack/plugins/cross_cluster_replication"], + "@kbn/cross-cluster-replication-plugin/*": ["x-pack/plugins/cross_cluster_replication/*"], + "@kbn/dashboard-enhanced-plugin": ["x-pack/plugins/dashboard_enhanced"], + "@kbn/dashboard-enhanced-plugin/*": ["x-pack/plugins/dashboard_enhanced/*"], + "@kbn/data-enhanced-plugin": ["x-pack/plugins/data_enhanced"], + "@kbn/data-enhanced-plugin/*": ["x-pack/plugins/data_enhanced/*"], + "@kbn/data-visualizer-plugin": ["x-pack/plugins/data_visualizer"], + "@kbn/data-visualizer-plugin/*": ["x-pack/plugins/data_visualizer/*"], + "@kbn/discover-enhanced-plugin": ["x-pack/plugins/discover_enhanced"], + "@kbn/discover-enhanced-plugin/*": ["x-pack/plugins/discover_enhanced/*"], + "@kbn/url-drilldown-plugin": ["x-pack/plugins/drilldowns/url_drilldown"], + "@kbn/url-drilldown-plugin/*": ["x-pack/plugins/drilldowns/url_drilldown/*"], + "@kbn/embeddable-enhanced-plugin": ["x-pack/plugins/embeddable_enhanced"], + "@kbn/embeddable-enhanced-plugin/*": ["x-pack/plugins/embeddable_enhanced/*"], + "@kbn/encrypted-saved-objects-plugin": ["x-pack/plugins/encrypted_saved_objects"], + "@kbn/encrypted-saved-objects-plugin/*": ["x-pack/plugins/encrypted_saved_objects/*"], + "@kbn/enterprise-search-plugin": ["x-pack/plugins/enterprise_search"], + "@kbn/enterprise-search-plugin/*": ["x-pack/plugins/enterprise_search/*"], + "@kbn/event-log-plugin": ["x-pack/plugins/event_log"], + "@kbn/event-log-plugin/*": ["x-pack/plugins/event_log/*"], + "@kbn/features-plugin": ["x-pack/plugins/features"], + "@kbn/features-plugin/*": ["x-pack/plugins/features/*"], + "@kbn/file-upload-plugin": ["x-pack/plugins/file_upload"], + "@kbn/file-upload-plugin/*": ["x-pack/plugins/file_upload/*"], + "@kbn/fleet-plugin": ["x-pack/plugins/fleet"], + "@kbn/fleet-plugin/*": ["x-pack/plugins/fleet/*"], + "@kbn/global-search-bar-plugin": ["x-pack/plugins/global_search_bar"], + "@kbn/global-search-bar-plugin/*": ["x-pack/plugins/global_search_bar/*"], + "@kbn/global-search-providers-plugin": ["x-pack/plugins/global_search_providers"], + "@kbn/global-search-providers-plugin/*": ["x-pack/plugins/global_search_providers/*"], + "@kbn/global-search-plugin": ["x-pack/plugins/global_search"], + "@kbn/global-search-plugin/*": ["x-pack/plugins/global_search/*"], + "@kbn/graph-plugin": ["x-pack/plugins/graph"], + "@kbn/graph-plugin/*": ["x-pack/plugins/graph/*"], + "@kbn/grokdebugger-plugin": ["x-pack/plugins/grokdebugger"], + "@kbn/grokdebugger-plugin/*": ["x-pack/plugins/grokdebugger/*"], + "@kbn/index-lifecycle-management-plugin": ["x-pack/plugins/index_lifecycle_management"], + "@kbn/index-lifecycle-management-plugin/*": ["x-pack/plugins/index_lifecycle_management/*"], + "@kbn/index-management-plugin": ["x-pack/plugins/index_management"], + "@kbn/index-management-plugin/*": ["x-pack/plugins/index_management/*"], + "@kbn/infra-plugin": ["x-pack/plugins/infra"], + "@kbn/infra-plugin/*": ["x-pack/plugins/infra/*"], + "@kbn/ingest-pipelines-plugin": ["x-pack/plugins/ingest_pipelines"], + "@kbn/ingest-pipelines-plugin/*": ["x-pack/plugins/ingest_pipelines/*"], + "@kbn/lens-plugin": ["x-pack/plugins/lens"], + "@kbn/lens-plugin/*": ["x-pack/plugins/lens/*"], + "@kbn/license-api-guard-plugin": ["x-pack/plugins/license_api_guard"], + "@kbn/license-api-guard-plugin/*": ["x-pack/plugins/license_api_guard/*"], + "@kbn/license-management-plugin": ["x-pack/plugins/license_management"], + "@kbn/license-management-plugin/*": ["x-pack/plugins/license_management/*"], + "@kbn/licensing-plugin": ["x-pack/plugins/licensing"], + "@kbn/licensing-plugin/*": ["x-pack/plugins/licensing/*"], + "@kbn/lists-plugin": ["x-pack/plugins/lists"], + "@kbn/lists-plugin/*": ["x-pack/plugins/lists/*"], + "@kbn/logstash-plugin": ["x-pack/plugins/logstash"], + "@kbn/logstash-plugin/*": ["x-pack/plugins/logstash/*"], + "@kbn/maps-plugin": ["x-pack/plugins/maps"], + "@kbn/maps-plugin/*": ["x-pack/plugins/maps/*"], + "@kbn/ml-plugin": ["x-pack/plugins/ml"], + "@kbn/ml-plugin/*": ["x-pack/plugins/ml/*"], + "@kbn/monitoring-collection-plugin": ["x-pack/plugins/monitoring_collection"], + "@kbn/monitoring-collection-plugin/*": ["x-pack/plugins/monitoring_collection/*"], + "@kbn/monitoring-plugin": ["x-pack/plugins/monitoring"], + "@kbn/monitoring-plugin/*": ["x-pack/plugins/monitoring/*"], + "@kbn/observability-plugin": ["x-pack/plugins/observability"], + "@kbn/observability-plugin/*": ["x-pack/plugins/observability/*"], + "@kbn/osquery-plugin": ["x-pack/plugins/osquery"], + "@kbn/osquery-plugin/*": ["x-pack/plugins/osquery/*"], + "@kbn/painless-lab-plugin": ["x-pack/plugins/painless_lab"], + "@kbn/painless-lab-plugin/*": ["x-pack/plugins/painless_lab/*"], + "@kbn/remote-clusters-plugin": ["x-pack/plugins/remote_clusters"], + "@kbn/remote-clusters-plugin/*": ["x-pack/plugins/remote_clusters/*"], + "@kbn/reporting-plugin": ["x-pack/plugins/reporting"], + "@kbn/reporting-plugin/*": ["x-pack/plugins/reporting/*"], + "@kbn/rollup-plugin": ["x-pack/plugins/rollup"], + "@kbn/rollup-plugin/*": ["x-pack/plugins/rollup/*"], + "@kbn/rule-registry-plugin": ["x-pack/plugins/rule_registry"], + "@kbn/rule-registry-plugin/*": ["x-pack/plugins/rule_registry/*"], + "@kbn/runtime-fields-plugin": ["x-pack/plugins/runtime_fields"], + "@kbn/runtime-fields-plugin/*": ["x-pack/plugins/runtime_fields/*"], + "@kbn/saved-objects-tagging-plugin": ["x-pack/plugins/saved_objects_tagging"], + "@kbn/saved-objects-tagging-plugin/*": ["x-pack/plugins/saved_objects_tagging/*"], + "@kbn/screenshotting-plugin": ["x-pack/plugins/screenshotting"], + "@kbn/screenshotting-plugin/*": ["x-pack/plugins/screenshotting/*"], + "@kbn/searchprofiler-plugin": ["x-pack/plugins/searchprofiler"], + "@kbn/searchprofiler-plugin/*": ["x-pack/plugins/searchprofiler/*"], + "@kbn/security-solution-plugin": ["x-pack/plugins/security_solution"], + "@kbn/security-solution-plugin/*": ["x-pack/plugins/security_solution/*"], + "@kbn/security-plugin": ["x-pack/plugins/security"], + "@kbn/security-plugin/*": ["x-pack/plugins/security/*"], + "@kbn/session-view-plugin": ["x-pack/plugins/session_view"], + "@kbn/session-view-plugin/*": ["x-pack/plugins/session_view/*"], + "@kbn/snapshot-restore-plugin": ["x-pack/plugins/snapshot_restore"], + "@kbn/snapshot-restore-plugin/*": ["x-pack/plugins/snapshot_restore/*"], + "@kbn/spaces-plugin": ["x-pack/plugins/spaces"], + "@kbn/spaces-plugin/*": ["x-pack/plugins/spaces/*"], + "@kbn/stack-alerts-plugin": ["x-pack/plugins/stack_alerts"], + "@kbn/stack-alerts-plugin/*": ["x-pack/plugins/stack_alerts/*"], + "@kbn/task-manager-plugin": ["x-pack/plugins/task_manager"], + "@kbn/task-manager-plugin/*": ["x-pack/plugins/task_manager/*"], + "@kbn/telemetry-collection-xpack-plugin": ["x-pack/plugins/telemetry_collection_xpack"], + "@kbn/telemetry-collection-xpack-plugin/*": ["x-pack/plugins/telemetry_collection_xpack/*"], + "@kbn/timelines-plugin": ["x-pack/plugins/timelines"], + "@kbn/timelines-plugin/*": ["x-pack/plugins/timelines/*"], + "@kbn/transform-plugin": ["x-pack/plugins/transform"], + "@kbn/transform-plugin/*": ["x-pack/plugins/transform/*"], + "@kbn/translations-plugin": ["x-pack/plugins/translations"], + "@kbn/translations-plugin/*": ["x-pack/plugins/translations/*"], + "@kbn/triggers-actions-ui-plugin": ["x-pack/plugins/triggers_actions_ui"], + "@kbn/triggers-actions-ui-plugin/*": ["x-pack/plugins/triggers_actions_ui/*"], + "@kbn/ui-actions-enhanced-plugin": ["x-pack/plugins/ui_actions_enhanced"], + "@kbn/ui-actions-enhanced-plugin/*": ["x-pack/plugins/ui_actions_enhanced/*"], + "@kbn/upgrade-assistant-plugin": ["x-pack/plugins/upgrade_assistant"], + "@kbn/upgrade-assistant-plugin/*": ["x-pack/plugins/upgrade_assistant/*"], + "@kbn/uptime-plugin": ["x-pack/plugins/uptime"], + "@kbn/uptime-plugin/*": ["x-pack/plugins/uptime/*"], + "@kbn/ux-plugin": ["x-pack/plugins/ux"], + "@kbn/ux-plugin/*": ["x-pack/plugins/ux/*"], + "@kbn/watcher-plugin": ["x-pack/plugins/watcher"], + "@kbn/watcher-plugin/*": ["x-pack/plugins/watcher/*"], + "@kbn/alerting-fixture-plugin": ["x-pack/test/functional_with_es_ssl/fixtures/plugins/alerts"], + "@kbn/alerting-fixture-plugin/*": ["x-pack/test/functional_with_es_ssl/fixtures/plugins/alerts/*"], + "@kbn/test-feature-usage-plugin": ["x-pack/test/licensing_plugin/plugins/test_feature_usage"], + "@kbn/test-feature-usage-plugin/*": ["x-pack/test/licensing_plugin/plugins/test_feature_usage/*"], + "@kbn/elasticsearch-client-xpack-plugin": ["x-pack/test/plugin_api_integration/plugins/elasticsearch_client"], + "@kbn/elasticsearch-client-xpack-plugin/*": ["x-pack/test/plugin_api_integration/plugins/elasticsearch_client/*"], + "@kbn/event-log-fixture-plugin": ["x-pack/test/plugin_api_integration/plugins/event_log"], + "@kbn/event-log-fixture-plugin/*": ["x-pack/test/plugin_api_integration/plugins/event_log/*"], + "@kbn/feature-usage-test-plugin": ["x-pack/test/plugin_api_integration/plugins/feature_usage_test"], + "@kbn/feature-usage-test-plugin/*": ["x-pack/test/plugin_api_integration/plugins/feature_usage_test/*"], + "@kbn/sample-task-plugin": ["x-pack/test/plugin_api_integration/plugins/sample_task_plugin"], + "@kbn/sample-task-plugin/*": ["x-pack/test/plugin_api_integration/plugins/sample_task_plugin/*"], + "@kbn/task-manager-performance-plugin": ["x-pack/test/plugin_api_perf/plugins/task_manager_performance"], + "@kbn/task-manager-performance-plugin/*": ["x-pack/test/plugin_api_perf/plugins/task_manager_performance/*"], + "@kbn/global-search-test-plugin": ["x-pack/test/plugin_functional/plugins/global_search_test"], + "@kbn/global-search-test-plugin/*": ["x-pack/test/plugin_functional/plugins/global_search_test/*"], + "@kbn/resolver-test-plugin": ["x-pack/test/plugin_functional/plugins/resolver_test"], + "@kbn/resolver-test-plugin/*": ["x-pack/test/plugin_functional/plugins/resolver_test/*"], + "@kbn/timelines-test-plugin": ["x-pack/test/plugin_functional/plugins/timelines_test"], + "@kbn/timelines-test-plugin/*": ["x-pack/test/plugin_functional/plugins/timelines_test/*"], + "@kbn/security-test-endpoints-plugin": ["x-pack/test/security_functional/fixtures/common/test_endpoints"], + "@kbn/security-test-endpoints-plugin/*": ["x-pack/test/security_functional/fixtures/common/test_endpoints/*"], + "@kbn/application-usage-test-plugin": ["x-pack/test/usage_collection/plugins/application_usage_test"], + "@kbn/application-usage-test-plugin/*": ["x-pack/test/usage_collection/plugins/application_usage_test/*"], + "@kbn/stack-management-usage-test-plugin": ["x-pack/test/usage_collection/plugins/stack_management_usage_test"], + "@kbn/stack-management-usage-test-plugin/*": ["x-pack/test/usage_collection/plugins/stack_management_usage_test/*"], + // END AUTOMATED PACKAGE LISTING // Allows for importing from `kibana` package for the exported types. "kibana": ["./kibana"], "kibana/public": ["src/core/public"], diff --git a/x-pack/plugins/canvas/scripts/shareable_runtime.js b/x-pack/plugins/canvas/scripts/shareable_runtime.js index b760a92811b8e..d182543b5a092 100644 --- a/x-pack/plugins/canvas/scripts/shareable_runtime.js +++ b/x-pack/plugins/canvas/scripts/shareable_runtime.js @@ -51,9 +51,10 @@ run( if (flags.run) { log.info('Starting Webpack Dev Server...'); execa.sync( - 'yarn', + process.execPath, [ - 'webpack-dev-server', + '--preserve-symlinks', + require.resolve('webpack-dev-server/bin/webpack-dev-server'), '--config', webpackConfig, ...(process.stdout.isTTY && !process.env.CI ? ['--progress'] : []), @@ -87,9 +88,10 @@ run( clean(); log.info('Building Canvas Shareable Workpad Runtime...'); execa.sync( - 'yarn', + process.execPath, [ - 'webpack', + '--preserve-symlinks', + require.resolve('webpack/bin/webpack'), '--config', webpackConfig, '--hide-modules', diff --git a/x-pack/plugins/canvas/shareable_runtime/webpack.config.js b/x-pack/plugins/canvas/shareable_runtime/webpack.config.js index 42e96ab4471fe..1a22af80da28d 100644 --- a/x-pack/plugins/canvas/shareable_runtime/webpack.config.js +++ b/x-pack/plugins/canvas/shareable_runtime/webpack.config.js @@ -38,15 +38,8 @@ module.exports = { filename: '[name].js', library: LIBRARY_NAME, }, - // Include a require alias for legacy UI code and styles resolve: { alias: { - 'data/interpreter': path.resolve( - KIBANA_ROOT, - 'src/plugins/data/public/expressions/interpreter' - ), - 'kbn/interpreter': path.resolve(KIBANA_ROOT, 'packages/kbn-interpreter/target/common'), - tinymath: path.resolve(KIBANA_ROOT, 'node_modules/tinymath/lib/tinymath.min.js'), core_app_image_assets: path.resolve(KIBANA_ROOT, 'src/core/public/core_app/images'), }, extensions: ['.js', '.json', '.ts', '.tsx', '.scss'], diff --git a/x-pack/plugins/fleet/server/routes/preconfiguration/handler.ts b/x-pack/plugins/fleet/server/routes/preconfiguration/handler.ts index 79fbfc7f9a686..aa9d6acbbc472 100644 --- a/x-pack/plugins/fleet/server/routes/preconfiguration/handler.ts +++ b/x-pack/plugins/fleet/server/routes/preconfiguration/handler.ts @@ -16,7 +16,7 @@ import type { } from '../../types'; import { defaultIngestErrorHandler } from '../../errors'; import { ensurePreconfiguredPackagesAndPolicies, outputService } from '../../services'; -import { resetPreconfiguredAgentPolicies } from '../../services/preconfiguration/index'; +import { resetPreconfiguredAgentPolicies } from '../../services/preconfiguration/reset_agent_policies'; export const updatePreconfigurationHandler: FleetRequestHandler< undefined, diff --git a/x-pack/plugins/fleet/server/services/preconfiguration/index.ts b/x-pack/plugins/fleet/server/services/preconfiguration/index.ts deleted file mode 100644 index e9ebc473af8f2..0000000000000 --- a/x-pack/plugins/fleet/server/services/preconfiguration/index.ts +++ /dev/null @@ -1,10 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -export { resetPreconfiguredAgentPolicies } from './reset_agent_policies'; - -export { ensurePreconfiguredOutputs } from './outputs'; diff --git a/x-pack/plugins/fleet/server/services/setup.test.ts b/x-pack/plugins/fleet/server/services/setup.test.ts index cd760adf7c8cb..7a52999524b20 100644 --- a/x-pack/plugins/fleet/server/services/setup.test.ts +++ b/x-pack/plugins/fleet/server/services/setup.test.ts @@ -18,7 +18,7 @@ import { upgradeManagedPackagePolicies } from './managed_package_policies'; import { setupFleet } from './setup'; jest.mock('./preconfiguration'); -jest.mock('./preconfiguration/index'); +jest.mock('./preconfiguration/outputs'); jest.mock('./settings'); jest.mock('./output'); jest.mock('./epm/packages'); diff --git a/x-pack/plugins/fleet/server/services/setup.ts b/x-pack/plugins/fleet/server/services/setup.ts index 6e3aed538fb07..20695a6ddc33b 100644 --- a/x-pack/plugins/fleet/server/services/setup.ts +++ b/x-pack/plugins/fleet/server/services/setup.ts @@ -23,7 +23,7 @@ import { DEFAULT_SPACE_ID } from '../../../spaces/common/constants'; import { appContextService } from './app_context'; import { agentPolicyService } from './agent_policy'; import { ensurePreconfiguredPackagesAndPolicies } from './preconfiguration'; -import { ensurePreconfiguredOutputs } from './preconfiguration/index'; +import { ensurePreconfiguredOutputs } from './preconfiguration/outputs'; import { outputService } from './output'; import { generateEnrollmentAPIKey, hasEnrollementAPIKeysForPolicy } from './api_keys'; diff --git a/x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/worker_src_harness.js b/x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/worker_src_harness.js index e180c130bc4af..0b6dde0a3eeb0 100644 --- a/x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/worker_src_harness.js +++ b/x-pack/plugins/screenshotting/server/formats/pdf/pdf_maker/worker_src_harness.js @@ -11,4 +11,5 @@ */ require('../../../../../../../src/setup_node_env'); +// eslint-disable-next-line @kbn/imports/uniform_imports require('./worker.ts'); diff --git a/yarn.lock b/yarn.lock index 9bdfd3f5b4218..095bde19073aa 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2948,7 +2948,7 @@ version "0.0.0" uid "" -"@kbn/babel-code-parser@link:bazel-bin/packages/kbn-babel-code-parser": +"@kbn/babel-plugin-synthetic-packages@link:bazel-bin/packages/kbn-babel-plugin-synthetic-packages": version "0.0.0" uid "" @@ -3024,6 +3024,10 @@ version "0.0.0" uid "" +"@kbn/find-used-node-modules@link:bazel-bin/packages/kbn-find-used-node-modules": + version "0.0.0" + uid "" + "@kbn/flot-charts@link:bazel-bin/packages/kbn-flot-charts": version "0.0.0" uid "" @@ -3040,6 +3044,10 @@ version "0.0.0" uid "" +"@kbn/import-resolver@link:bazel-bin/packages/kbn-import-resolver": + version "0.0.0" + uid "" + "@kbn/interpreter@link:bazel-bin/packages/kbn-interpreter": version "0.0.0" uid "" @@ -3188,6 +3196,10 @@ version "0.0.0" uid "" +"@kbn/synthetic-package-map@link:bazel-bin/packages/kbn-synthetic-package-map": + version "0.0.0" + uid "" + "@kbn/telemetry-tools@link:bazel-bin/packages/kbn-telemetry-tools": version "0.0.0" uid "" @@ -5320,10 +5332,10 @@ resolved "https://registry.yarnpkg.com/@types/aria-query/-/aria-query-4.2.0.tgz#14264692a9d6e2fa4db3df5e56e94b5e25647ac0" integrity sha512-iIgQNzCm0v7QMhhe4Jjn9uRh+I6GoPmt03CbEtwx3ao8/EfoQcmgtqH4vQ5Db/lxiIGaWDv6nwvunuh0RyX0+A== -"@types/babel__core@^7.0.0", "@types/babel__core@^7.1.7": - version "7.1.10" - resolved "https://registry.yarnpkg.com/@types/babel__core/-/babel__core-7.1.10.tgz#ca58fc195dd9734e77e57c6f2df565623636ab40" - integrity sha512-x8OM8XzITIMyiwl5Vmo2B1cR1S1Ipkyv4mdlbJjMa1lmuKvKY9FrBbEANIaMlnWn5Rf7uO+rC/VgYabNkE17Hw== +"@types/babel__core@*", "@types/babel__core@^7.1.19": + version "7.1.19" + resolved "https://registry.yarnpkg.com/@types/babel__core/-/babel__core-7.1.19.tgz#7b497495b7d1b4812bdb9d02804d0576f43ee460" + integrity sha512-WEOTgRsbYkvA/KCsDwVEGkd7WAr1e3g31VHQ8zy5gul/V1qKullU/BU5I68X5v7V3GnB9eotmom4v5a5gjxorw== dependencies: "@babel/parser" "^7.1.0" "@babel/types" "^7.0.0" @@ -5331,10 +5343,10 @@ "@types/babel__template" "*" "@types/babel__traverse" "*" -"@types/babel__core@^7.1.19": - version "7.1.19" - resolved "https://registry.yarnpkg.com/@types/babel__core/-/babel__core-7.1.19.tgz#7b497495b7d1b4812bdb9d02804d0576f43ee460" - integrity sha512-WEOTgRsbYkvA/KCsDwVEGkd7WAr1e3g31VHQ8zy5gul/V1qKullU/BU5I68X5v7V3GnB9eotmom4v5a5gjxorw== +"@types/babel__core@^7.0.0", "@types/babel__core@^7.1.7": + version "7.1.10" + resolved "https://registry.yarnpkg.com/@types/babel__core/-/babel__core-7.1.10.tgz#ca58fc195dd9734e77e57c6f2df565623636ab40" + integrity sha512-x8OM8XzITIMyiwl5Vmo2B1cR1S1Ipkyv4mdlbJjMa1lmuKvKY9FrBbEANIaMlnWn5Rf7uO+rC/VgYabNkE17Hw== dependencies: "@babel/parser" "^7.1.0" "@babel/types" "^7.0.0" @@ -5349,6 +5361,13 @@ dependencies: "@babel/types" "^7.0.0" +"@types/babel__helper-plugin-utils@^7.10.0": + version "7.10.0" + resolved "https://registry.yarnpkg.com/@types/babel__helper-plugin-utils/-/babel__helper-plugin-utils-7.10.0.tgz#dcd2416f9c189d5837ab2a276368cf67134efe78" + integrity sha512-60YtHzhQ9HAkToHVV+TB4VLzBn9lrfgrsOjiJMtbv/c1jPdekBxaByd6DMsGBzROXWoIL6U3lEFvvbu69RkUoA== + dependencies: + "@types/babel__core" "*" + "@types/babel__template@*": version "7.0.2" resolved "https://registry.yarnpkg.com/@types/babel__template/-/babel__template-7.0.2.tgz#4ff63d6b52eddac1de7b975a5223ed32ecea9307" @@ -6048,6 +6067,10 @@ version "0.0.0" uid "" +"@types/kbn__find-used-node-modules@link:bazel-bin/packages/kbn-find-used-node-modules/npm_module_types": + version "0.0.0" + uid "" + "@types/kbn__generate@link:bazel-bin/packages/kbn-generate/npm_module_types": version "0.0.0" uid "" @@ -6060,6 +6083,10 @@ version "0.0.0" uid "" +"@types/kbn__import-resolver@link:bazel-bin/packages/kbn-import-resolver/npm_module_types": + version "0.0.0" + uid "" + "@types/kbn__interpreter@link:bazel-bin/packages/kbn-interpreter/npm_module_types": version "0.0.0" uid ""